0 votes
in C Plus Plus by

What do you mean by Pure Virtual Functions?

1 Answer

0 votes
by

Virtual Destructors: When we use a base class pointer pointing to a derived class object and use it to destroy it, then instead of calling the derived class destructor, the base class destructor is called.

Example:

Class A{

              ….

              ~A();

};

Class B:publicA{

               …

               ~B();

};

B b;

A a = &b;

delete a;

As shown in the above example, when we say delete a, the destructor is called but it’s actually the base class destructor. This gives rise to the ambiguity that all the memory held by b will not be cleared properly.

This problem can be solved by using the “Virtual Destructor” concept.

What we do is, we make the base class constructor “Virtual” so that all the child class destructors also become virtual and when we delete the object of the base class pointing to the object of the derived class, the appropriate destructor is called and all the objects are properly deleted.

This is shown as follows:

Class A{

              ….

              virtual ~A();

};

Class B:publicA{

               …

               ~B();

};

B b;

A a = &b;

delete a;

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

Related questions

+2 votes
asked Jun 19, 2019 in C Plus Plus by anonymous
0 votes
asked Jun 10, 2022 in Apache by Robin
0 votes
+1 vote
asked Jul 16, 2019 in C Plus Plus by Indian
...