Eduard Fedoruk
Eduard Fedoruk

Reputation: 350

can't take member of base class from derived class. C++

I have 2 classes. Base - Animal and derived MyDog. I want to change the ageOfAnimal from the setAge method and then display changed value from derived class - MyDog

code:

#include <iostream>
#include <string>

using namespace std;
class Animal
{
 public:
 int ageOfAnimal = 0;
 int setAge(int age) {
    ageOfAnimal = age;
    return ageOfAnimal;
 }
};

class MyDog: public Animal
{
 public:
    void getInfo() {
    cout << ageOfAnimal;
    }

};

int main()
{
   Animal *animal = new Animal;
   animal->setAge(20);
   MyDog myDog;
   myDog.getInfo();

   return 0;
}

Output: 0

Why can't I get 20? Is this even posible?

UPDATE
Thanks for answers but what i want is to change the state of ageOfAnimal property from different objects

class Animal
{
  public:
  int ageOfAnimal = 0;
  int setAge(int age) {
    ageOfAnimal += age;
    return ageOfAnimal;
  }
}

class MyCat: public Animal
{
 public:
  void getInfo() {
  cout << ageOfAnimal;
 }
}


class MyDog: public Animal
{
 public:
     void getInfo() {
     cout << endl << ageOfAnimal;
    }
}
int main() {
 myDog dog;
 dog.getInfo();
 MyCat cat;
 cat.getInfo();
}

output: 20 20

but what i want to see it's 20 21. How to do this?

Upvotes: 0

Views: 83

Answers (1)

AMA
AMA

Reputation: 4214

In the usage code there are two different objects: Animal * animal and MyDog myDog. Both objects have their own instances of ageOfAnimal: changing it in one object does not modify the second object (which is the expected behavior).

1. As MyDog is derived from Animal one could simply:

MyDog myDog;
myDog.setAge(20);
myDog.getInfo();

2. If you want ageOfAnimal to be global for all instances of Animal you should make it a static member.

UPDATE

To reflect the updated question: one can put getInfo into Animal class. Default age for cats and dogs can be then specified in the constructors. Even better way would be to specify age in Animal ctor and use constructor initializer lists for MyDog and MyAnimal ctors.

class Animal
{
public:
   int ageOfAnimal = 0;
   int setAge(int age)
   {
      ageOfAnimal += age;
      return ageOfAnimal;
   }
   void getInfo()
   {
      cout << endl << ageOfAnimal;
   }
};

class MyCat : public Animal
{
public:
    MyCat()
    {
        setAge(40);
    }
};

class MyDog : public Animal
{
public:
    MyDog()
    {
        setAge(20);
    }
};

int main()
{
   MyDog dog;
   dog.getInfo();
   MyCat cat;
   cat.getInfo();
}

Output:

20
40

Or if you want age to be shared between all objects, make it a static member as suggested earlier:

class Animal
{
public:
   static int ageOfAnimal;
   int setAge(int age)
   {
      ageOfAnimal += age;
      return ageOfAnimal;
   }
   void getInfo()
   {
      cout << ageOfAnimal;
   }
};

// Initialize age
int Animal::ageOfAnimal = 0;

Upvotes: 2

Related Questions