1

I have a template class "Derived" which does a constructor inheritance:

template <class T>
class Derived : public T
{
    using T::T;
    Derived()
    {
         std::cout<<"in derived"; 
    }
};

My base class has a constructor that expects arguments:

class Base
{
public:
    Base(int a)
    {
        std::cout<<"in base";
    }
};

When I create an object of type Derived it seems the derived constructor is not called:

Derived<Base> derived(2);

prints "in base";

Why? Is there a way to tell it to call Derived constructor?

1
  • Why do you expect it to be called? It's a parameterless constructor and you're calling a constructor with a parameter. Also, how is the template part relevant to the question? Wouldn't the same be true had it not been a template?
    – Rotem
    Mar 4, 2019 at 17:10

1 Answer 1

2

Initialization by an inherited constructor happens as follows:

[class.inhctor.init] (emphasis mine)

1 When a constructor for type B is invoked to initialize an object of a different type D (that is, when the constructor was inherited), initialization proceeds as if a defaulted default constructor were used to initialize the D object and each base class subobject from which the constructor was inherited, except that the B subobject is initialized by the invocation of the inherited constructor. The complete initialization is considered to be a single function call; in particular, the initialization of the inherited constructor's parameters is sequenced before the initialization of any part of the D object.

The key point is the defaulted word. Defaulted c'tors are generated by the compiler, for instance a copy c'tor can be defaulted. And so it doesn't use any c'tor that's defined in the derived class. A compiler generated c'tor is always going to have an empty compound statement. So one should not expect anything to be printed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.