Reputation: 102
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
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
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