inheritance?

19 Nov 2010

In C++, what does it mean when you have this:

Something::Something(int a, boolean b) : AnotherThing(x), YetAnotherThing(y)

and

Something::~Something

19 Nov 2010

Ok so I found out that the first one is the constructor and the second is the destructor but I'm still unsure what the stuff after the single : is.

19 Nov 2010 . Edited: 19 Nov 2010

If a class "Foo" inherits from a parent class "Bar" then when Foo's constructor is called you will also need to invoke the constructor for Bar's class.

So, really, it should look like this (assuming "Another" is yet a second inherited class):-

Foo::Foo(int a, bool b) : Bar(a), Another(b) 
{ 
  // class constructor code... 
}

Here, the to parameters a and b get passed to the parent class constructors. Bar::Bar(int x) gets a and Another::Another(bool y) gets b

 

(edit: Fixed it, Bar::Bar is one of the parents, not Foo::Foo as I originally put.)

19 Nov 2010 . Edited: 19 Nov 2010

The "thing after the colon" is called initialization (initializer) list. Besides explicit initialization of parent classes, it can be used to initialize class members (instead of doing assignments in the constructor's body).

19 Nov 2010

You need to use the initialization list if you have const-members. Since they cannot be modified, you cannot set them in the constructor.

19 Nov 2010

Thanks for the replies, got it now. :)