I'm working on a small C++ project that requires using classes. I'm supposed to create a super class Animal and the sub classes Fish, Bird and Insect. In the main function, the object of type animal is created. I need that object to 'become' one of the 3 other types at random (each sub class has a different number of legs). Any Idea how to do that? Thanks

Objects in C++ can't change their type. You can have a variable of some pointer-to-animal type and then assign a new pointer-to-animal to that variable though.

Something like this

animal *myAnimal;

myAnimal = new fish;
std::cout<< myAnimal->numLegs() << "\n";
delete myAnimal;

myAnimal = new cat;
std::cout<< myAnimal->numLegs() << "\n";
delete myAnimal;

// etc...

That is provided that you've a structure like this:

class animal { /*...*/ };
class fish : public animal { /*...*/ };
class cat: public animal { /*...*/ };

And that the numLegs method is virtually defined either in animal and overwritten in the inherited classes. Or however you wanna do it. There are a few ways I can think of.

Edited 7 Years Ago by twomers: n/a

Something like this

animal *myAnimal;

myAnimal = new fish;
std::cout<< myAnimal->numLegs() << "\n";
delete myAnimal;

myAnimal = new cat;
std::cout<< myAnimal->numLegs() << "\n";
delete myAnimal;

// etc...

That is provided that you've a structure like this:

class animal { /*...*/ };
class fish : public animal { /*...*/ };
class cat: public animal { /*...*/ };

And that the numLegs method is virtually defined either in animal and overwritten in the inherited classes. Or however you wanna do it. There are a few ways I can think of.

This seems to be the ticket... However, now I cant seem to be able to access the values of the members of an object... I am getting the errors saying that number and legs are undeclared when running this code:

#include <iostream.h>
#include <stdlib.h>
#include <time.h>

class Animal{
      public:
      int number;
      int legs;
      Animal(){
           number = rand()%9;
           }
      };
      
class Fish : public Animal{
      public:
      Fish () : Animal (){
           legs = 0;
           }
      
      };
      
class Bird : public Animal{
      public:
      Bird () : Animal (){
           legs = 2;
           }
      };
      
class Insect : public Animal{
      public:
      Insect () : Animal (){
           legs = 6;
           }
      };
      

            
int main() {
    
    Animal *a, *b, *x;
    
    a = new Fish;
    b = new Bird;
    x = new Insect;
    
    cout<< a.number << "\t" << a.legs << endl;
    cout<< b.number << "\t" << b.legs << endl;
    cout<< x.number << "\t" << x.legs << endl;
    
    system("pause");
    return 0;
}

Any ideas?

This article has been dead for over six months. Start a new discussion instead.