Alexander
Alexander

Reputation: 63197

Subclass from a Superclass with no default constructor, without calling any other constructors

I have a pretty basic problem but I can't find an acceptable solution (story of my life):

I would like to make a small change to a class' constructor, so I made a subclass, call it sub, of the superclass super. When constructing sub, I don't want to call any of the real constructors of super, but super doesn't have a default constructor.

Editing the super class to add a default constructor is a possibility, but it would involve editing a library that's frequently updated, which is its own can of worms.

What would you guys advise?

Upvotes: 1

Views: 451

Answers (4)

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99575

In C++11 you can use constructor inheritance to make your life a little bit easier:

class super
{
public:
  super( int x );
  // more constructors
};

class sub : public super
{
  using super::super; // now all constructors is here
};

In the code above sub::sub(int) is automatically defined as sub::sub(int x) : super(x) {} so you do not need to write constructors in sub manually.

Upvotes: 1

Tristan Brindle
Tristan Brindle

Reputation: 16824

As others have said, what you want (subclass to call the parent class's default constructor when there isn't one) isn't possible.

However, what you could do is add a protected default constructor to the parent class. This wouldn't alter the public interface for other library users, but would allow subclasses to call it.

Upvotes: 0

Eugene S
Eugene S

Reputation: 3122

When you derive from a parent class, or even use that class as a private member of your class through composition, you're stuck with the public interface that the parent class provides.

So if you're not happy with the constructors that the base class provides, you need to either modify the base class implementation or re-write it as a new class adding whatever interface modifications you would want.

Upvotes: 1

shintoZ
shintoZ

Reputation: 311

If the base class does not provides any default constructor, there is no way to define derived class without calling any of the constructors available.

Upvotes: 4

Related Questions