I am building a program requiring making some classes with inheritance. I can't seem to be able to access the members of the class objects. My code looks like this:

#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;
}

Basically, all animals have a random number, and each animal type has a different number of legs. When running, I get an error saying that 'number' and 'legs' are not declared. Help?

Children cant access fields of the parent class. Add accessor and mutator methods to Animal to allow access to these fields from the children.

Since your classes are really pointers you need the -> operator to dereference and dot them (*A.member() is the same as A->member() )

(also, instead of iostream.h #include<iostream> and instead of stdlib.h #include<cstdlib> and <ctime> in place of time.h -- these are the standard headers you should be using -- unless you're really attached to pre 1998 for some reason)

Children cant access fields of the parent class. Add accessor and mutator methods to Animal to allow access to these fields from the children.

I reserve the right to be wrong (lol) but aren't these public members OP is trying to access via public inheritance?

Since your classes are really pointers you need the -> operator to dereference and dot them (*A.member() is the same as A->member() )

(also, instead of iostream.h #include<iostream> and instead of stdlib.h #include<cstdlib> and <ctime> in place of time.h -- these are the standard headers you should be using -- unless you're really attached to pre 1998 for some reason)

Awesome! Exactly what I needed... My bloodshed dev C++ cannot recognize ctime though... time.h works fine. Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.