0

I am learning C++. And I really can't understand why I can't age like this (in cat class. Can anyone help me?

class Animal{   
 public :
        void speak();
        int getAge(){
            return age;
        }
    protected :
        int age;
};

class Cat : public Animal{
    public :
    
    Cat(int age = 0) : age{age}{
    }
    void eat(){
        std::cout << "I eat mouse." << std::endl;
    }
    void speak(){
        std::cout << "Miaow" << std::endl;
    }
};
  • 3
    Do you get any error? If yes, post that error in your question. **What do you expect the output to be and how does it different from the current output**. – Jason Oct 11 '22 at 08:02
  • 2
    Each class can initialize only its own variables directly, add `Animal` ctor instead and call it from `Cat`'s ctor. – Quimby Oct 11 '22 at 08:02
  • And you need to make `speak` *virtual* if you want your animal, if actually being a cat, speaking `meow` (`Animal* a = new Cat(); a->speak();`). If an animal speaking itself (without being sub-classed) is not meaningful then make `speak` pure virtual: `virtual void speak() = 0;`. – Aconcagua Oct 11 '22 at 08:10
  • 1
    Apart from please read about [mre] – your code does not reveal how you are using your classes and what expected and actual output is. – Aconcagua Oct 11 '22 at 08:12
  • Also see [How can I initialize base class member variables in derived class constructor?](https://stackoverflow.com/questions/7405740/how-can-i-initialize-base-class-member-variables-in-derived-class-constructor) – Jason Oct 11 '22 at 08:16
  • By the way, there are two common patterns for getters and setters: `unsigned int getAge(); void setAge(unsigned int);` on the one hand and `unsigned int age(); void age(unsigned int);` on the other one – the latter possible due to C++ allowing overloads. I personally consider the latter superior because `get/set` are redundant (number of parameters/return value provide the same information) and thus we can profit from more compact code/less typing – but make up your own mind ;) – Aconcagua Oct 11 '22 at 08:20
  • Note that I switched above to `unsigned int` – there is a *semantic* reason for: Are negative ages meaningful at all? Doesn't appear to me... You can express this fact by using unsigned types (-> self-documenting code). – Aconcagua Oct 11 '22 at 08:23

0 Answers0