top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is virtual constructors/destructors in context of C++?

+5 votes
406 views
What is virtual constructors/destructors in context of C++?
posted Nov 19, 2013 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+2 votes

Virtual destructors: A destructor can be virtual as it is possible as at runtime depending on the type of object caller is calling to, proper destructor will be called.
Using virtual destructors, you can destroy objects without knowing their type - the correct destructor for the object is invoked using the virtual function mechanism. Note that destructors can also be declared as pure virtual functions for abstract classes. if someone will derive from your class, and if someone will say "new Derived", where "Derived" is derived from your class, and if someone will say delete p, where the actual object's type is "Derived" but the pointer p's type is your class.

Virtual Constructor There is nothing like Virtual Constructor. The Constructor can’t be virtual as the constructor is a code which is responsible for creating an instance of a class and it can’t be delegated to
any other object by virtual keyword means.

answer Nov 19, 2013 by Vikas Upadhyay
0 votes

Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object.

There is a simple solution to this problem – declare a virtual base-class destructor. This makes all derived-class destructors virtual even though they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called.

Virtual constructor: AFAIK Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error.

answer Nov 19, 2013 by Deepankar Dubey
...