Valeri Grishin
Valeri Grishin

Reputation: 102

Is it possible to use a copy constructor in Derived class without using Base copy constructor?

I am new to C++ and from what i learned until now is when we call a copy constructor from a Derived class, The copy constructor of the Base class is called. Let's say that i have a copy constructor in the private area of the Base class. How can i call the copy constructor of the Derived class without calling the copy constructor of the Base class? (In this code A doesn't have the implementation of the copy constructor and this is what i would like to know).

class NonCopyable
{
protected:
NonCopyable(){}
~NonCopyable(){}
private:
NonCopyable(const NonCopyable& nonCopyable);
NonCopyable& operator=(const NonCopyable& nonCopyable);
};
class A: public NonCopyable
{
};

Upvotes: 2

Views: 1282

Answers (2)

Valeri Grishin
Valeri Grishin

Reputation: 102

After some search I found a way. There is a way to call a copy constructor of the Derived class without calling the copy constructor of the Base class. All what we have to do is to build the copy constructor in A, and A inherit the constructor of NonCopyable while the copy constructor is private:

class NonCopyable
{
protected:
    NonCopyable(){}
    ~NonCopyable(){}
private:
    NonCopyable(const NonCopyable& nonCopyable);
    NonCopyable& operator=(const NonCopyable& nonCopyable);
};
class A: public NonCopyable
{
public:
    A(){}
    A(const A& other){}
};

Upvotes: 1

Ralf Ulrich
Ralf Ulrich

Reputation: 1724

The simple answer is: yes, this is possible.

You only need to define a dedicated Derived copy-constructor that does not call the NonCopyable copy-constructor (of course this might be just confusing in a real software application, but this is a different issue):

This class is constructible, but not copy-constructible:

class CannotBeCopied: public NonCopyable {};

This class is constructible, and also copy-constructible:

class CanBeCopied: public NonCopyable {
public: 
    CanBeCopied() = default; // needed since otherwise CopyConstructor is only known construtor
    CanBeCopied(const CanBeCopied& b) { } // calls NonCopyable::NonCopyable() default-constructor, which is just protected
};

See life example here: http://coliru.stacked-crooked.com/a/60c9fc42fa2dd59a

Upvotes: 1

Related Questions