Skeen
Skeen

Reputation: 4732

Inherit copy constructor

Say I have a class A, which provide a copy constructor (accepting another A).

I then have a derived class B of A, which does not provide a copy constructor.

Can I inherit the copy constructor of A into B, alike what's possible for non-copy constructors?

Note: B does not have any state, except the state contained in A.

Upvotes: 0

Views: 137

Answers (1)

MikeMB
MikeMB

Reputation: 21166

If you don't need any special behaviour in addition to what the base class's copy constructor provides, you should be fine with simply telling the compiler to use the default copy constructor, which will invoke the base classes copy constructor

#include <iostream>

class A {
public:
    int a;
    A()=default;
    A(const A& other) {
        std::cout << "Class A copy constructor called" << std::endl;
        a = other.a;
    }

};

class B: public A {
public :
    int b;
    B() = default;
    B(const B& other) = default;
};


int main() {
    B b1;
    b1.a = 1;
    b1.b = 2;

    B b2(b1);

    std::cout << b2.a << " - " << b2.b << std::endl;
}

Output:

Class A copy constructor called
1 - 2

EDIT:

In order to answer your exact question: I believe that the using directive makes all base class constructors visible in the derived class. I'm personally not too fond of this behavior, so I prefer using the default constructors instead of the using directive, but that's just me.

Upvotes: 2

Related Questions