0

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?

3
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by xcorpionxting
0

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

0

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)

Edited by jonsca: n/a

0

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?

Edited by jonsca: n/a

0

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!

This question has already been answered. Start a new discussion instead.
Take the time to help us to help you. Please be thoughtful and detailed and be sure to adhere to our posting rules.