milliar
milliar

Reputation: 1

How to call construction on another inherited class in c++?

I am attempting to write a constructor using inheritance.

Why does mammal class not inherit the animal constructor ?

Also, why can't I overload it ?

PS: constructor takes 4 parameters.

Here is my code :

class animal {

    public:
        string name;
        string diet;
        float dailycalories;
        float expectedlifetime;

    virtual void display() {

    }

    virtual void calculateExpectedLifeTime() {

    }

    animal(string nam, string dit, float dacalo, float explife) {
        expectedlifetime = 0;
        nam = name;
        dit = dailycalories;
        dacalo = dailycalories;
        explife = expectedlifetime;
    }
};

class mammal: public animal {

    animal(string nam, string dit, float dacalo, float explife) {

    }

    public:
        float brainsize;
};

Upvotes: 0

Views: 85

Answers (1)

CKasper
CKasper

Reputation: 622

Here is how you call the parent constructor in the child constructor in C++:

class mammal: public animal{
        mammal(string name, string dit, float dacalo,float explife, float brainsize):animal(name, dit, dacalo, explife){
          this -> brainsize = brainsize;
        }

    public:
        float brainsize;
};

Hope this answers your question

Upvotes: 4

Related Questions