Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Inheritance

Status
Not open for further replies.

marcusaurelius

Technical User
Jun 21, 2003
3
0
0
US
Hey, i was wondering, when we use inheritance, is there a need to created constructors and destructors for the parent class, or is it enough that we create them only for the child?
 
I believe if there the parent constructor take no values, it is ok to not pass any values. But it would not hurt to call the parent in any case.

Child(int nVar, CString strVar) : Parent(nVar, strVar)
{
...
}

I don't know about the destructor, but just do it.

Hope that's helpful
 
thanks for the response, but waht i meant was:

class parent
{
protected:
blah;
}

class child : public parent{
public:
bloop;
}

in this case, would i NEED to define constructors and destructors for the parent class? i don't plan to use the parent class in any situation, its only there for design purposes.
I suppose what i really want to know is that when a child object goes out of scope, i.e, gets destructed, will the parent's destructor get called?
 
If you don't provide a constructor to the parent, the compiler will generate one that tkaes not arguments and initializes all the class's memebers with their default constructors.

If a derived class doesn't explicitly call a parent's constructor, the compiler has it call the parent's default constructor (which would be the compiler-generated one if you didn't provide one).


When a local object whose type is the derived class goes out of scope, it calls the derived destructor and the parent destructor.

BUT

When a dynamically allocated object of the derived type is deleted through a pointer to the parent type, unless the destructor is declared virtual, only the parent destructor will get called (which is wrong, since part of the object doesn't get deleted).

Thus, if the class heirarchy will never be manipulated polymorphically, (i.e. all objects are going to be local), you can leave out the destructor. In this case, you should probably be using private inheritance to kill the possibility of anyone erroneously using the classes polymorphically.

Otherwise, you must put a virtual destructor in the parent class, even if it does nothing. It's good practice to do this whenever there's even a chance for your classes to be used polymorphically (i.e. you use public inheritance).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top