Class c is a child class of B which is class of A. A, B, and C all have destructor and constructor functions.

QUESTION

Class c is a child class of B which is class of A. A, B, and C all have destructor and constructor functions. Each constructor outputs the name of the class and each destructor outputs the name of the class with a “~” in front. Thus

A*p_myA = new();

delete p_myA

results in an output of A~A

What is the output if I make 2 C objects and then delete both?

a) AABBCC~A~A~B~B~C~C

b) CBACBA~A~B~C~A~B~C

c) CBBAAC~C~C~B~B~A~A

d) ZCC~C~C

e) ABCABC~C~B~A~C~B~A

 

ANSWER

The correct option is option-e.

The output will be ABCABC~C~B~A

 

EXPLANATION

Class B is a child of class A and class C is the child of class B

The constructor is called when an object is created and when this object id deleted, its destructor is called. 

 

In this case, when the two objects of class C are created the constructor is immediately called. Since in this case, C

Class C is a child class of B and which in turn is a child class of A.

When an object is created its constructor is called and when an object is deleted its destructor is called. 

 

When two objects of the C class are created, immediately its constructor is called. In this case, since C is a child class of B, and B, in turn, is the child of class A, first the constructor of A is called and then the constructor of B is called and in the last, the constructor of C is called. 

 

For deleting an object it is the opposite, The child class destructor is always called first and then the superclass constructors.

a) C* object1 = new C();

    Output: ABC

b) C* object2 = new C();

    Output: ABC

c) Delete object1;

    Output: ~C~B~A

d) Delete object2:

    Output: ~C~B~A

 

Overall output: ABCABC~C~B~A~C~B~A

 

CODE

#include <iostream>
using namespace std;
class A 
{
    public:
    A(){
        cout<<"A";
    }
    ~A(){
        cout<<"~A";
    }
};
class B : public A
{
    public:
    B(){
        cout<<"B";
    }
    ~B(){
        cout<<"~B";
    }
};
class C : public B
{
    public:
    C(){
        cout<<"C";
    }
    ~C(){
        cout<<"~C";
    }
};
 
int main()
{
    A* p_myA = new A();
    delete p_myA;
    cout<<endl<<endl;
    C* obj1=new C();
    C* obj2=new C();
    delete obj1;
    delete obj2;
}

 

Output:

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *