+ 11
Constructor cannot be virtual. Why??
I just know that Constructor cannot be virtual but want to know that why is it so?
2 ответов
+ 7
good question👍👍👍👍
what does virtual do??.
it allows dynamic binding for functions having ""same name "at parent class and child class".
i think by this point u got it.
two constructors of different class will never have same name. as u know constructor name is class name itself.
this means there is no way to implement overriding with constructors..👀
so there is no need of virtual😉
+ 2
Manish gave a good answer but there is an additional reason. Suppose it was possible to do and you have the following base and derived class:
class B
{
public:
virtual B(){noCakes = 0;}
void AddCake(){noCakes++;}
private:
int noCakes;
};
class D : public B
{
public:
D(){}
void B(){AddCake();} //Lets imagine this overrides B's constructor
};
You can see that if D::B() is called rather than B::B() as constructor, B would not be completely constructed and its members would not have been initialized (noCakes in this case). It would also not be possible for D::B() to access B's private members for initialization purposes.
Constructors are there to put objects in valid states during construction, and parents need to be in valid states before the child is constructed, else the child cannot depend on the parent's members to initialize itself. What you are proposing means you are deferring initialization of the parent to the child, which inverts the whole idea.
In fact, the constructor initializer list is meant to achieve exactly the opposite - ensure any parent(s) are constructed before the children - all the way up the inheritance tree!