C and C++

Moderators: None (Apply to moderate this forum)
Number of threads: 28695
Number of posts: 94715

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Destructor Question? Posted by ferdinandng on 17 May 2006 at 2:46 AM
Hi Experts,

I am new to C++. I want to ask is that if my class inherited from a parent class, when implemnting the my class's destructor, how do I call the parent's destructor? or the compiler will call the parent destuctor method automatically.

Thank you for your help.

Best Regards
Ferdinand Ng
Report
Re: Destructor Question? Posted by Donotalo on 17 May 2006 at 3:21 AM
: Hi Experts,
:
: I am new to C++. I want to ask is that if my class inherited from a parent class, when implemnting the my class's destructor, how do I call the parent's destructor? or the compiler will call the parent destuctor method automatically.
:
: Thank you for your help.
:
: Best Regards
: Ferdinand Ng
:
when a derived class' destructor is called, generally the base's destructor will be called automatically. but if u use dynamic allocation of a derived object to a pointer of the base class, then define the base class' destructor as virtual, otherwise, the derived class' destructor will not be called when u deallocate memory. here is a short example:
class Base {
public:
	Base() {cout << "Base constructed.\n";}
	virtual ~Base() {cout << "Base destructed.\n";}
};

class Derived : public Base {
public:
	Derived() {cout << "Derived constructed.\n";}
	~Derived() {cout << "Derived destructed.\n";}
};

int main()
{
	Base *b;
	b = new Derived;
	delete b;

        return 0;
}

in the code above, if ~Base() would not be defined virtual, ~Derived() would not be called.


~Donotalo()




 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.