Error : base class constructor must explicitly initialize parent class constructor

后端 未结 5 684
傲寒
傲寒 2021-02-02 07:22

I am new to c++. When I try to compile the code below , I get this error

constructor for \'child\' must explicitly initialize the base class \'parent\' whic

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-02 07:55

    Another example where a MyBook class is being derived from the base class Book. Now a custom constructor with two arguments are supplied for the base class constructor, therefore there is no default constructor for the base class. When inside the main function, a derived class object novel is created, at first the compiler will attempt to invoke the base class constructor which does not exist. So, the base class constructor needs to be explicitly called from the derived class constructor to initialize any private variables that the derived class has inherited from the base class but can not access directly (e.g. title string variable). As user rook mentioned, we need follow these rules. You can get more detailed information from the nice explanation of Initialization Lists by Alex Allain. So, Initialization Lists are must required when there is no defined dafault constructor and also for initializing constant members. He summarises-

    Before the body of the constructor is run, all of the constructors for its parent class and then for its fields are invoked. By default, the no-argument constructors are invoked. Initialization lists allow you to choose which constructor is called and what arguments that constructor receives.

    #include 
    #include 
    
    using namespace std;
    
    class Book {
    private:
        string title;
    protected:
        string author;
    public:
        Book(string t, string a) {
            title = t;
            author = a;
        };
        virtual void display() = 0;
    };
    
    class MyBook : public Book {
    private:
            const string className;
    protected:
            int price;
    public:
            // Book(t,a) needs to be called before the {} block to initialize, otherwise error (does not match to Book::Book() default constructor will occur)         
            MyBook(string t, string a, int p) : Book(t, a), className("MyClass"), price(p){
            };
    
            void display() {
                cout << "Title: " << getTitle() << endl;
                cout << "Author: " << author << endl;
                cout << "Price: " << price << endl;
            };
    };
    
    int main() {
        string title, author;
        int price;
        getline(cin, title);
        getline(cin, author);
        cin >> price;
        MyBook novel(title, author, price);
        novel.display();
    
        return 0;
    }
    

提交回复
热议问题