So I'm still trying to learn C++ classes...

So I'm still trying to learn C++ classes...

General — Page [1]
CornJer
Metal does cocaine.

Frontline Heroism Medal
2005 Mar 21 • 1531
36 ₧
Question: How does one execute code in all instances of a class?

Please remember that I am a newbie at C++, and the code may be wrong.

For example:

[code:1]
class animal
{
public:
int x;
int y;
int move()
{
x += 1;
y += 1;
}
}

class cat : class animal
{
public
int toes
int move()
{
x+=1
y+=2
toes = 6
}
}

cat Mrbonkers;
animal Rat;
animal dog;
[/code:1]

Yes, the cat class is inherrited from animal.

How do I execute the move() function in all three instances of the classes, without doing this:

[code:1]
Rat.move();
dog.move();
Mrbonkers.move();
[/code:1]

Any help would be appreciated.
If you jump high enough you'll hurt your ankles when you land.
 
 
 
2006 Sep 26 at 14:49 UTC
SuperJer
Websiteman

2005 Mar 21 • 6666
[code:1]
animal *allAnimals[3];
allAnimals[0] = &Mrbonkers;
allAnimals[1] = &Rat;
allAnimals[2] = &dog;

for(int i=0; i<3; i++)
allAnimals[i]->move();
[/code:1]

It seems to me the code needs to run three times, you're going to have to call it three times.

I'd keep my animals in an array to begin with and then it would be even easier to call it on all three.
 
 
 
2006 Sep 26 at 21:42 UTC
Homeslice
Homebread

Badass Mothafucka Medal
2006 May 21 • 287
216 ₧
Listen to jer he has a pet shark ...he knows about animals
 
 
 
2006 Sep 26 at 22:38 UTC
Page [1]