Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, inherited copy ctors does not work?

Tags:

c++

c++11

Consider following code:

class TBase {
public:
   TBase();
   TBase(const TBase &);
};

class TDerived: public TBase {
public:
   using TBase::TBase;
};

void f() {
   TBase Base;
   TDerived Derived(Base); // <=== ERROR
}

so, I have base and derived classes, and want to use "using TBase::TBase" to pull copy ctor from base class to be able to create instance of derived class in such way:

   TDerived Derived(Base);

But all compilers rejects this with these error messages

7 : note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'TBase' to 'const TDerived' for 1st argument

Why? What am I doing wrong? Why "using TBase::TBase" does not work in this situation?

UPDATE How can be explained following piece of code from cppreference.com?

struct B1 {
    B1(int);
};
struct D1 : B1 {
    using B1::B1;
// The set of inherited constructors is 
// 1. B1(const B1&)
// 2. B1(B1&&)
// 3. B1(int)
like image 664
Void Avatar asked Sep 15 '25 14:09

Void


1 Answers

Copy and move consturctors (and the default constructor) are never inherited, simply because the standard says so. All other constructors are.

That comment on cppreference was misleading(1). The same comment in the standard says:

The candidate set of inherited constructors in D1 for B1 is

(Emphasis mine).

The standard then goes on to say that only the D1(int) constructor is actually inherited. The copy and move constructors for D1 are implicitly-declared as for any other class, not inherited.

Refer to C++14 12.9 [class.inhctor] for details.


(1) I submitted a change to cppreference to hopefully clarify this.

like image 141
Angew is no longer proud of SO Avatar answered Sep 17 '25 06:09

Angew is no longer proud of SO