Sarah
Sarah

Reputation: 191

Error: no default constructor exists for class

I have a class derived from base class, and set constructors for each classes, but I keep getting error that I do not have any constructor for base class.

class Dog
    {
    protected:
    string name;
    int age;

    public:

    Dog(string dogsName, int dogsAge)
    {
        name = dogsName;
        age = dogsAge;
    }

    virtual void Bark()
    {
        cout << "Woof Woof I am a dog" << endl;
    }


class Huey: public Dog
{
public:

    Huey()
    {
        name = "goodboy";
        age = 13;
    }

     void Bark()
    {
    cout << "woof" << endl;
    }
}

Here I get an error on Huey() and it says " no default constructor exists for 'Dog'". But I think I have created a constructor for class Dog. Can you please explain why this code is wrong?

Upvotes: 1

Views: 7089

Answers (3)

Brady Dean
Brady Dean

Reputation: 3573

When you specify any constructor of your own, the default constructor is not created anymore. However, you can just add it back.

class Dog
    {
    protected:
    string name;
    int age;

    public:

    Dog() = default;

    Dog(string dogsName, int dogsAge)
    {
        name = dogsName;
        age = dogsAge;
    }

    virtual void Bark()
    {
        cout << "Woof Woof I am a dog" << endl;
    }
};

class Huey: public Dog
{
public:

    Huey()
    {
        name = "goodboy";
        age = 13;
    }

     void Bark()
    {
    cout << "woof" << endl;
    }
};

EDIT: It seems like you want to call your custom Dog constructor from Huey. It is done like so

class Dog
    {
    protected:
    string name;
    int age;

    public:

    Dog(string dogsName, int dogsAge)
    {
        name = dogsName;
        age = dogsAge;
    }

    virtual void Bark()
    {
        cout << "Woof Woof I am a dog" << endl;
    }
};

class Huey: public Dog
{
public:

    Huey() : Dog("goodboy", 13) {}

    void Bark()
    {
    cout << "woof" << endl;
    }
};

Upvotes: 3

Binu
Binu

Reputation: 157

Two ways: 1) have a default constructor with no params. 2) call the existing constructor you have in Dog from Huey ( this is the right thing in your case since Huey is a Dog after all). Huey is currently calling the default constructor of Dog since this isn’t defined and explicitly called.

Upvotes: 0

HaroldSer
HaroldSer

Reputation: 2065

You need to create a constructor with no parameters and no implementation. As below:

 public:
    Dog() = default;

Upvotes: 0

Related Questions