vendredi 24 mars 2017

Class: illegal member initialization, inherited variable [duplicate]

The question may be a duplicate but I assume, because I read some question about this topic and I couldn't find solution for this.

I have a Base class named Animal and a Derived class named Dog. Animal have a protected int variable named animalType which have to recognize what type of animal is because I want to add more derived class to define more animals.

Here is my Animal.h

class Animal {

protected:
    int animalType_;
    std::vector<std::string> food_;
public:
    Animal();
    Animal(const int&);
    virtual ~Animal();}

Here is Animal.cpp

Animal::Animal() {}

Animal::~Animal() {}

void Animal::buyFood(std::string food) {

    mancare_.push_back(food);
}

Animal::Animal(const int& animalType) : animalType_(animalType) {}

My derived Dog class header

class Dog : public Animal {

public:
    Dog::Dog();
    Dog(const int&);
    void virtual buyFood(std::string food);
}

My Dog.cpp

Dog::Dog() {}


void Dog::buyFood(std::string food) {

    food_.push_back(food);
}

Dog::Dog(const int& animalType) : animalType_(animalType) {} // here is the error

The error is in my Dog.cpp at animalType_

The odd thing is that: - If I initialize my explicit constructor as above in Dog.cpp I get this error: " 'Dog:' illegal member initialization: 'animalType_' is not a base or member "

My Question is: Why if I initialize with this type of constructor I don't get an error:

 Dog::Dog(const int& animalType) {
     animalType_ = animalType;
}

Aucun commentaire:

Enregistrer un commentaire