Mammal *pDog = new Dog;
here Mammal is base class and Dog is it's derived class
In such declaration destructor is not called why is it rule of C++?
Printable View
Mammal *pDog = new Dog;
here Mammal is base class and Dog is it's derived class
In such declaration destructor is not called why is it rule of C++?
OK compile this ode in visual c++
#include <iostream>
using std::cout;
class Mammal
{
public:
Mammal():itsAge(1) { cout << "Mammal constructor...\n"; }
~Mammal() { cout << "Mammal destructor...\n"; }
void Move() const { cout << "Mammal move one step\n"; }
void Speak() const { cout << "Mammal speak!\n"; }
protected:
int itsAge;
};
class Dog : public Mammal
{
public:
Dog() { cout << "Dog Constructor...\n"; }
~Dog() { cout << "Dog destructor...\n"; }
void WagTail() { cout << "Wagging Tail...\n"; }
void Speak()const { cout << "Woof!\n"; }
void Move()const { cout << "Dog moves 5 steps...\n"; }
};
int main()
{
Mammal *pDog = new Dog;
pDog->Move();
pDog->Speak();
return 0;
}
mammal and dog constructor called but their destructor not called at the end of main that is what i want to ask you
t
Quote:
mammal and dog constructor called but their destructor not called at the end of main that is what i want to ask you
You aren't deleting pDog.Code:Mammal *pDog = new Dog;
Now the descructor will be called. Remember, C++ doesn't do garbage collection like Java does.Code:delete pDog
Inheritance has nothing to do with this. Every new must have a matching delete, no matter whether the types being created are related by inheritance or not.
thanks to all of you i got the point that is -> I have created pDog so i am responsible for their deletion destructor will called when i write delete pDog; in my code.
once again thanks to all of you.
Hi,
Just to clarify, as Paul pointed out the Dog destructor will only be called if the Mammal destructor is declared as virtual (which it isn't in the code that you posted.)
Alan