Khalid Ahmed
Khalid Ahmed

Reputation: 13

How do I solve this inheritance problem with explicit initialization?

When I'm creating a constructor for a child class I get this error under the MyBook method:

Constructor for 'MyBook' must explicitly initialize the base class 'Book' which does not have a default constructorclang(missing_default_ctor) Solution.cpp(8, 7): 'Book' declared here

Here's the code below

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
class Book{
    protected:
        string title;
        string author;
    public:
        Book(string t,string a){
            title=t;
            author=a;
        }
        virtual void display()=0;

};

class MyBook : public Book
{
    protected:
    int price;
    string t;
    string a;

    public:
        MyBook(string t, string a, int p)
        {
            Book(t, a);
        }
};


int main() {
    string title,author;
    int price;
    getline(cin,title);
    getline(cin,author);
    cin>>price;
    MyBook novel(title,author,price);
    novel.display();
    return 0;
}

Upvotes: 0

Views: 263

Answers (3)

R Sahu
R Sahu

Reputation: 206577

MyBook(string t, string a, int p)
{
    Book(t, a);
}

is equivalent to:

MyBook(string t, string a, int p) : Book() // Initialize base class with default constructor
{
    Book(t, a); // Construct a temporary Book, unrleated to the 
                // Book sub-object of this class.
}

which explains the compiler error. You need to use:

MyBook(string t, string a, int p) : Book(t, a) // Initialize base class with the
                                               // constructor that accepts t and a
{
}

Upvotes: 1

Thomas Caissard
Thomas Caissard

Reputation: 866

You are declaring a constructor to Book that takes parameters, which implicitly erases the default constructor of Book. In you derive class MyBook, your constructor implicitely calls the default constructor of Book which is deleted thus the error.

You can either:

  • add a default constructor to Book
  • call the specialized Book constructor in the initialization list:
        MyBook(string t, string a, int p)
          : Book(t, a)
        {
        }

Upvotes: 1

cigien
cigien

Reputation: 60218

When constructing a base class object, you have to do it before entering the constructor body, which means you need to use a member-initializer-list, like this:

MyBook(string t, string a, int p) : Book(t, a) {}

Also note that in order to instantiate an object of type MyBook, you need to override the virtual display method in MyBook, like this:

void display() override {};

Here's a demo.

Upvotes: 3

Related Questions