C++ Programming - Constructors and Destructors - Discussion

Discussion Forum : Constructors and Destructors - Programs (Q.No. 8)
8.
What will be the output of the following program?
#include<iostream.h>
class BixBase
{   
    public:
    BixBase()
    {
        cout<< "Base OK. "; 
    }
};
class BixDerived: public BixBase
{
    public:
    BixDerived()
    { 
        cout<< "Derived OK. "; 
    }
    ~BixDerived()
    { 
        cout<< "Derived DEL. "; 
    }
};
int main()
{
    BixBase    objB;
    BixDerived objD;
    objD.~BixDerived();
    return 0;
}
Base OK. Derived OK. Derived DEL.
Base OK. Base OK. Derived OK. Derived DEL.
Base OK. Derived OK. Derived DEL. Derived DEL.
Base OK. Base OK. Derived OK. Derived DEL. Derived DEL.
The program will report compile time error.
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
13 comments Page 1 of 2.

Shrey said:   1 decade ago
The answer is correct .I compiled in Dev c++;

Bittooo said:   1 decade ago
Can we call destructor from main function? is it possible?

Kiran said:   1 decade ago
We only create objects of classes, constructor and destructor gets automatically called.

Bishu said:   1 decade ago
Couldn't understand. Can anyone please explain why "Base OK" gets print twice as its obj formed only once.

Anonymous said:   1 decade ago
First is when base class constructor is called as(BixBase objB).

Second time when derived class constructor is called as(BixDerived objD) in which base class constructor called again and then derived class consructor called.

Pranathi said:   1 decade ago
When base class object is called it invokes the base call constructor (Base OK) , when the derived class object is called first it will call base class constructor then it invokes derived class constructor (Base OK, Derived OK). Destructor invokes in reverse order.

Anil said:   1 decade ago
Why derived del is displayed 2 times ?

Arvind said:   1 decade ago
1. Firstly when objD.~BixDerived() is called explicitly.
2. Secondly when the program ends...Destructor will be invoked implicitly.
(1)

Sammy14 said:   1 decade ago
In oops,when a constructor of derived class is called compiler automatically invokes base class's default constructor (However in java we can use super(a,b) to specify parameterized constructor).

Therefore the virtually the definition of derived class constructor becomes:

BixDerived()
{
BixBase();//Line added By Compiler internally
cout<< "Derived OK. ";
}

Unknown said:   1 decade ago
When I ran the same piece of code in Dev C++, destructor of derived class is called only once. I think answer is wrong.


Post your comments here:

Your comments will be displayed after verification.