Answer to Question #213854 in C++ for ismail khan

Question #213854

Answer the following short questions. Your answer should be precise.

a)     Can we declare base class constructor or destructor as virtual if yes then why we want to do?

b)    How we can declare a class as abstract and why we need abstract classes? 

c)     Why we cannot able to create objects of abstract classes give reasonable justification of that.           



1
Expert's answer
2021-07-05T14:14:03-0400

a) Virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to base class:

class Base 
{
    // some virtual methods
};

class Derived : public Base
{
    ~Derived()
    {
        // Do some important cleanup
    }
};

Here, you'll notice that I didn't declare Base's destructor to be virtual. Now, let's have a look at the following snippet:

Base *b = new Derived();
// use b
delete b; // Here's the problem!

Since Base's destructor is not virtual and b is a Base* pointing to a Derived object, delete b has undefined behaviour:

[In delete b], if the static type of the object to be deleted is different from its dynamic type, the static

type shall be a base class of the dynamic type of the object to be deleted and the static type shall

have a virtual destructor or the behavior is undefined.

In most implementations, the call to the destructor will be resolved like any non-virtual code, meaning that the destructor of the base class will be called but not the one of the derived class, resulting in a resources leak.

To sum up, always make base classes' destructors virtual when they're meant to be manipulated polymorphically.

If you want to prevent the deletion of an instance through a base class pointer, you can make the base class destructor protected and nonvirtual; by doing so, the compiler won't let you call delete on a base class pointer.

b) https://www.ibm.com/docs/en/zos/2.2.0?topic=only-abstract-classes-c

c) The abstract modifier can be used with classes, methods, properties, indexers, and events.

Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes.

Abstract classes have the following features:

An abstract class cannot be instantiated.

An abstract class may contain abstract methods and accessors.

It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.

A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS