John R. Strohm
John R. Strohm

Reputation: 7667

Does this work? C++ multiple inheritance and constructor chaining

Consider a class Waldo, that inherits from Foo and Baz, viz.:

class Waldo : public Foo, public Baz {
  ...
};

When I create a new instance of Waldo:

   Waldo *w = new Waldo;

do the Foo and Baz constructors get called? If they are not called by default, is there an easy way IN THE CLASS DECLARATION OR IN THE DECLARATION/DEFINITION of the Waldo constructor to force them to be called?

(It looks like I may be trying to do constructor chaining, and C++ allegedly doesn't do that. I'm not sure.)

What I'm trying to do is "annotate" various class declarations, where the annotations cause (among other things) instances of the annotated class to be linked into lists maintained by the annotation classes. This lets me, for example, walk the list of all objects with Baz-nature, applying a certain operation to them, and not have to worry about whether I remembered to add the instance to the list of objects with Baz-nature, because the constructor did it automagically.

Upvotes: 5

Views: 713

Answers (2)

bhuwansahni
bhuwansahni

Reputation: 1844

The constructors of all the members of a class are called in the order they are declared in the class.

The default constructors of derived classes call the constructors of base class by default. If they need arguments, they need to be invoked explicitly else it is an error...

 class Employee {
 private:
     //
 public:
    Employee();
    //...
 };



 class Manager: public Employee {
 private:
     short level;
 public:
     Manager(): Employee(), level() {}    // This is the default constructor, it calls Employee(). 
     // The definition is equivalent to default constructor of Manager..
     //...
  };

Upvotes: 1

Sebastian Mach
Sebastian Mach

Reputation: 39089

Yes, they are called. Left to right.

Upvotes: 7

Related Questions