Class C is a child class of B which is a child class of A.

Question

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

A*p_myA=new A();
delete p_myA;

results in an output of A~A
What is output if I make 2 C objects and then delete both?
Select one:
a. AABBCC~A~A~B~B~C~C
b. CBACBA~A~B~C~A~B~C
c. CCBBAA~C~C~B~B~A~A
d. CC~C~C
e. ABCABC~C~B~A~C~B~A

Summary

Option e is the correct answer.
The output will be ABCABC~C~B~A

Explanation

Here class C is a child class of B which is a child class of A.
When we create any object the constructor of it is called as well as when we delete any object the destructor of it is get called and as mentioned in the question each class has its own constructor and destructor.
So when we create two objects of class C, the constructor of class C is immediately called. But as we know here Class C is a child class of Class B and Class B is a child Class of Class A. As a result Constructor of class A is first called, and then the constructor of Class B and then later of class C.

But at the time of destructor calling, the child class destructor is first called and then the superclass destructor. As a result
⦁ C* object1 = new C();
Output: ABC
⦁ C* object2 = new C();
Output: ABC
⦁ Delete object1;
Output: ~C~B~A
⦁ Delete object2:
Output: ~C~B~A
In the end, the output is: ABCABC~C~B~A~C~B~A

Code

#include <iostream>
using namespace std;
//Class A
class A 
{
    public:
    A(){
        cout<<"A";
    }
    ~A(){
        cout<<"~A";
    }
};
//Class B is a child class of class A
class B : public A
{
    public:
    B(){
        cout<<"B";
    }
    ~B(){
        cout<<"~B";
    }
};
// class C is a child class of class 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* object1=new C();
    C* object2=new C();
    delete object1;
    delete object2;
}

Output

 

Also read, write a program for the customer who are willing to take the vehicle on rent.

 

Share this post

Leave a Reply

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