Reputation: 483
I have the following code in a single cpp file:
class Base
{
public:
//constructor
Base() = delete;
};
class Derived : public Base
{
public:
//copy constructor
Derived( const Derived & other ){};
};
int main( int argc, char* argv[] )
{
//empty
}
However, compiling the cpp file results in an error
exp.cpp: In copy constructor ‘Derived::Derived(const Derived&)’:
exp.cpp:15:37: error: use of deleted function ‘Base::Base()’
Derived( const Derived & other ){};
exp.cpp:7:5: note: declared here
Base() = delete;
^~~~
I don't understand why. How does the base class default constructor come into play when you define the copy constructor for derived class?
Upvotes: 1
Views: 170
Reputation: 36441
Constructing an object of derived class necessitate to construct an object of its base class (as a derived instance is a base instance + extension).
Thus initializing the derived instance necessitate to initialize the base instance. The question is then when I call a ctor for the derived class, which ctor of the base class is called? As you defined the derived ctor as:
Derived( const Derived & other ){};
the compiler observed that you didn't specified a call to a specific base class ctor, it then generates a call to the ctor with no parameter. But, alas, you deleted it from the base class. It then emits an error.
You may think that calling a copy ctor for the derived class will generates a call to the copy ctor of the base class which wasn't deleted. But, alas, no, the rule is that if you don't specify a specific ctor call for the base class, the ctor with no parameter is called.
Upvotes: 6