8. Inheritance and Polymorphism

8. Inheritance and Polymorphism

Postby Cuchulainn » Wed Jan 21, 2009 1:43 pm

What's 'wrong' with this code?



class B

{ // Class with non-virtual destructor

private:

double* d;

public:

B() { d = new double (1.0); }

~B() { cout << "Base destructor\n"; delete d; }





};



class D : public B

{ // Derived class

private:

int* iarr;

public:

D(int N) : B() { iarr = new int[N]; }

~D() { cout << "Derived destructor\n"; delete [] iarr; }

};





int main()

{

{

B* b = new D(10);

delete b;

}





return 0;

}
User avatar
Cuchulainn
 
Posts: 677
Joined: Mon Dec 18, 2006 2:48 pm
Location: Amsterdam, the Netherlands

Postby ImplicitScheme » Tue Nov 16, 2010 7:00 pm

The short answer is the code makes a memory leak. The line



B * b = new D(6) ;



will call the constructor for D and allocate memory on the heap for D's private data member iarr. Since the destructor in class B is not marked as virtual when delete is called on object b only the base class destructor will be called and the memory allocated for iarr will be never be recovered.
ImplicitScheme
 
Posts: 6
Joined: Thu Nov 04, 2010 7:01 pm

Postby Cuchulainn » Tue Nov 16, 2010 7:08 pm

Correct!
User avatar
Cuchulainn
 
Posts: 677
Joined: Mon Dec 18, 2006 2:48 pm
Location: Amsterdam, the Netherlands


Return to C++ Certification and Examinations: Intermediate Level

Who is online

Users browsing this forum: No registered users and 0 guests

cron