Why is the constructor of the derived class deleted?

The following compiler says that my constructor for derived classes was not found:

    struct Drink
    {
        Drink(const Drink& other);
    };

    struct PepsiMax : Drink {};

    int main()
    {
        PepsiMax myPepsi;         // <--- the default constructor of PepsiMax cannot be referenced, it is a deleted function
    }

I know that the default Drink constructor must be defined because I created the copy constructor and the compiler will not use the default constructor for me. However, the error message says that it cannot find the default constructor for my PepsiMax class, which I expected from it. If I define a default constructor for PepsiMax, it shows an error saying that it cannot find the default Drink constructor that I expect.

Can we assume that it refers to the default constructor of "Drink", and not to "PepsiMax", or am I not understanding something? I expected the compiler to create a default constructor for "PepsiMax", which immediately calls the base class constructor as the first thing it does.

Edit: I'm confused, thanks for your help. My explanation of my naive interpretation of the constructor created by the compiler is in the answer.

+4
source share
4 answers

The fix is ​​to write

struct Drink
{
    Drink() = default;
    Drink(const Drink& other);
};

( ). , PepsiMax, PepsiMax myPepsi;. .

+2

PepsiMax . (Drink), Drink. Drink . , , PepsiMax .

,

Drink() = default;

Drink.

+1

Cppreference quotes

T undefined, : T , , .

Drink - .

, PepsiMax undefined, Drink .

0

, . .

struct Base
{
    Base(const Base& other);       // <---- My copy constructor, putting this here prevents the compiler generating a default and empty constructor
};

Derived : Base
{
    // Nothing here. The compiler should generate a default constructor here
    // Something like Derived() : Base::Base() {}
}

, (). , , . , , , , , Derived.

, "" , , :

Derived() : Base::Base(){}

Parses it, does not find Base :: Base (), and does not generate this string at all, and then complains that it cannot find the default Derived constructor. This was obvious to those who responded. The confusion here was how the compiler accurately generated the default constructor. Thank you for enlightening me a little more.

0
source

Source: https://habr.com/ru/post/1664535/


All Articles