why we cannot create virtual constructor.
why we cannot create virtual constructor
Collapse
X
-
Tags: None
-
The simple answer is that a virtual function is used to avoid a situation where the compiler has a choice between calling the base class function or the derived class function. The virtual keyword says to call the base class function. Without the virtual keyword, the compiler will call the derived class function.
Next, a derived class has no idea how to intialize a base class so constructors are not inherited so you cannot override a base class constructor in a derived class. And that prevents a virtual constructor.
Lastly, factory classes are classes that can create various kinds of objects. Factory class methods sometimes are called virtual contructors. -
The simple answer is that when a class is constructed, if it inherits from another class, then the base class must be constructed first and only then the inherited class.
If the constructor was virtual, polymorphism would prevent from the base class to be constructed first.
Thats the same reason why the destructor is virtual, because the inherited class is the first to be destructed and only then the base class.Comment
-
Correct me if I'm wrong, but the destructor isn't virtual by default,.. you have to specify virtual before the destructor.Originally posted by oridimant...
Thats the same reason why the destructor is virtual, because the inherited class is the first to be destructed and only then the base class.Comment
-
You are correct. The destructor IS NOT virtual by default.
However, a virtual destructor does not mean the destructor is a virtual function in the virtual function table. Destructors are not inherited. All it means is that when the object is destroyed by using a BASE class pointer or reference that the DERIVED class destructor is called and then the base class destructor is called. Without this signal to the compiler, deleting an object by using a base class pointer will call only the base class destructor.
Example:
class Base
{
public:
~Base();
};
class Derived : public Base
{
public:
~Derived()
};
and you:
Base* obj = new Derived;
delete obj; //only Base::~Base() is called
Change things this way:
class Base
{
public:
virtual ~Base();
};
class Derived : public Base
{
public:
~Derived()
};
and you:
Base* obj = new Derived;
delete obj; //only Derived::~Deriv ed() called
// and then Base::~Base() is called.Comment
Comment