0
votes

Scenario 1: No compilation issue.When base class is initialized in derived class using initialization list

class Base
{
    public:
        int x;
};
class D:public Base
{
    public:
        int y;
        D(int y1):Base{y1+1},y{y1}{}
};

int main()
{
    D d(5);
    return 0;
}

Scenario 2: Not compiling and asking for parameterized constructor . Note virtual destructor in base class $g++ -o main *.cpp main.cpp: In constructor ‘D::D(int)’: main.cpp:16:34: error: no matching function for call to ‘Base::Base()’ D(int y1):Base{y1+1},y{y1}{} ^ main.cpp:5:7: note: candidate: Base::Base() class Base ^~~~ main.cpp:5:7: note: candidate expects 0 arguments, 1 provided main.cpp:5:7: note: candidate: constexpr Base::Base(const Base&) main.cpp:5:7: note: no known conversion for argument 1 from ‘int’ to ‘const Base&’

class Base
{
    public:
    int x;
    virtual ~Base(){}    
};
class D:public Base
{
    public:
        int y;
        D(int y1):Base{y1+1},y{y1}{}
};

int main()
{
    D d(5);
    return 0;
}
1

1 Answers

1
votes

Base{y1+1} is an aggregate initialization. It only works on aggregates. In your second snippet, since Base contains a virtual function, it is no longer an aggregate, and so you can't initialize it like that.