Oceanescence
Oceanescence

Reputation: 2127

Can a derived class have a constructor that is not in the base class in C++?

Say I have a base class:

class Animal
{
public:
    Animal(double length, double height); 
    virtual ~Animal(); 

private:
    fLength;
    fHeight;
};

The constructor sets fLength = length and fHeight = height.

I have a derived class Fish which works fine.

But say I have a derived class Cat which has another property fLegs which needs to be set in the constructor. A fish does not have legs so it does not make sense for the Animal base class to have the property fLegs.

Can a constructor for Cat be created like:

Cat(double length, double height, double Legs) ?

I have tried this but an error comes up saying there is no matching function call to Animal.

Is there any way I can get around this without making the Fish have an fLegs property and setting it to 0 for the Fish?

Upvotes: 2

Views: 77

Answers (2)

amilamad
amilamad

Reputation: 480

You can use the code below. First initialize the base class constructor. Then derived class variables.

class Cat : public Animal
{
public:
    Cat(double length, double height, double legs) : Animal(length, height), fLength(legs)
    {
    } 

private:
   double flegs;
};

Upvotes: 0

gsamaras
gsamaras

Reputation: 73366

Yes.

Example:

class Animal
{
public:
    Animal(double length, double height) : fLength(length), fHeight(height) {}
    virtual ~Animal(){}; 

private:
    double fLength;
    double fHeight;
};

class Cat : public Animal
{
 public:
    Cat(double length, double height, double Legs) : Animal(length, height), fLegs(Legs) {}
 private:
    double fLegs;
};

int main(void)
{
    Cat(1,2,4);
    return 0;
}

Upvotes: 1

Related Questions