Luca
Luca

Reputation: 10996

C++: default constructor implementation

I have a class which inherits from a base class which provides a protected constructor which is empty.

Is it necessary for me to implement the blank constructor (and destructor) in the derived class or will the compiler generate the appropriate one for me. I am using C++ 11.

While some aspacts of the questions are answered in this post (How is "=default" different from "{}" for default constructor and destructor?), I am mostly interested in the behaviour when the class is derived.

So I have something like:

template<typename EnumClass>
class IVCounter
{
protected:
    //!
    //! \brief Ensure that this base class is never instantiated
    //! directly.
    //!
    IVCounter() {}


public:
    //!
    //! \brief Virtual destructor
    //!
    virtual ~IVCounter() {}
};

class Derived: public IVCounter<SomeType>
{
   // Do I have to do this?
   Derived() 
   : IVCounter()
   {}

   ~Derived() {}
};

Or perhaps in the derived I can simply do:

Derived() = default;
~Derived() = default;

or maybe even leave it out altogether?

Upvotes: 0

Views: 117

Answers (3)

Serge Ballesta
Serge Ballesta

Reputation: 148880

You do not need an explicit constructor here. The implicit default constructor is enough. Draft N4659 says at 15.6.2 Initializing bases and members [class.base.init] § 13:

In a non-delegating constructor, initialization proceeds in the following order:

  • First, and only for the constructor of the most derived class (4.5), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.
  • Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
  • Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
  • Finally, the compound-statement of the constructor body is executed.

The implicitely default constructor has just an empty body, but construction of an object implies construction of its base classes

Upvotes: 1

Jarod42
Jarod42

Reputation: 217135

Default generated constructor would be public, so following is enough

class Derived: public IVCounter<SomeType>
{
};

Upvotes: 1

code707
code707

Reputation: 1701

Yes. compiler will generate blank constructor, you need not.

Upvotes: 1

Related Questions