0

I'm trying to determine the difference between two ways to expose a constructor when you're using private inheritance under C++11.

Method 1:

class Base {
    public:
    int i;
    Base(int x): i(x) {}
};

class Derived : private Base {
    public:
    Derived(int x) : Base(x) {} // constructor method 1
};

Method 2:

class Base {
    public:
    int i;
    Base(int x): i(x) {}
};

class Derived : private Base {
    public:
    using Base::Base;  // constructor method 2
};

In superficial tests, both seem to work the same. The only real difference is that my code editor (clion) doesn't seem to like the latter. Is there more to the story here? Are either of these clearly preferable?

jep
  • 747
  • 6
  • 25

2 Answers2

1

The only real difference is that my code editor (clion) doesn't seem to like the latter. Is there more to the story here?

Both methods are valid ways to expose Base constructors in Derived. Your code editor might not be fully aware of the C++11 features.

Are either of these clearly preferable?

It probably depends on personal preference, team coding guidelines, the need to expose all base class constructors in the derived class or only a subset, etc. I prefer the second form since it allows you to inherit all base class constructors using one line of code. If you need to expose only a subset of the base class constructors, the first method is the only way to go.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

If you want to expose (almost) every Base ctor, use using. You are saying "I can be constructed like my parent".

If you want to pick ctors, use the first option. In a sense, you are independently describing how you can be constructed, so it also has a different connotation.

You should ask yourself: If Base got a new ctor, should derived get it automatically?

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524