Should child class override the constructors if they have identical parameter as the parent class?

Viewed 159

I am using VC++.

I define a parent class:

class A
{
   A();
   A(int a);

   virtual ~A();

   virtual void DoSomething();
}

Then define a child class:

class B: public A
{
   virtual void DoSomething();
}

In class B, only a new version of DoSomething is introduced. All other functions, including the constructors and destructor are same as A.

For example, both the following constructor are OK for B:

B MyB;
B MyB(1);

In such a case, need I create the constructors B() and B(int a)?

I try to obmit the constructors & destructor in B(), hoping it can inherit from A, but the compiler will report error for:

B MyB(1);
1 Answers

The default constructor B::B() would be implicitly-defined, while B::B(int) won't. You can define one explicitly, or apply using for inheriting constructor (since C++11).

If the using-declaration refers to a constructor of a direct base of the class being defined (e.g. using Base::Base;), all constructors of that base (ignoring member access) are made visible to overload resolution when initializing the derived class.

class B : public A
{
   using A::A;
   virtual void DoSomething();
}
Related