Consider a base class that is derived by two sub-classes and a third class derives from the above two classes. I make the base class virtual, so as to not make copies of the base class. My question is that do I have to include the base class constructor in the initialization of derived class constructor i.e. do I have to do something like this: derived-class(arg-list) : class 1(args), class2(args), virtual_base_class(args){}?? If so why? I have never instantiated the base class constructor within a class that derives from a class which derives from the base class i.e. the sub-class eventually calls the base class and I have to pass it all the arguments to instantiate the base class. Why do I need to instantiate the virtual base class in this case? Thanks in advance for your replies!

Derived classes only need to construct the classes the directly derive from. If those classes derive from something else then it the responsibility of those classes to construct what classes the directly derive from. Take the follwing example

class Foo {};

class Bar : public Foo
{
public:
    Bar() : Foo() {}
};

class Foobar : public Bar
{
public:
    Foobar() : Bar() {}
};

In Foobar we call the constructor for the Bar part but not the Foo part as that is Bar's responsibility. Bar then handles creating the Foo part and everything is good.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.