C++ I have created code but need help with this last part. I don\'t seem to reme
ID: 3775161 • Letter: C
Question
C++
I have created code but need help with this last part. I don't seem to remember how to use for loops in the instance of an array.
I have 3 classes, and each one has a certain address. The for loop will just call these classes throught the method called "speak"
I will attach the code to show what I mean. Bottom Line I need a for loop in main() to call the classes.
main.cpp
#include <iostream>
using namespace std;
class Animal
{
private:
int legs;
public:
void setLegs(int legs);
int getLegs();
void talk();
Animal() :legs(4) {}
void talk();
virtual void speak() = 0;
};
void Animal::talk()
{
speak();
}
void Animal::setLegs(int legs)
{
this->legs = legs;
}
int Animal::getLegs()
{
return this->legs;
}
class Cat : public Animal
{
public:
void speak();
};
void Cat::speak()
{
cout << "meow" << endl;
}
class Dog : public Animal
{
public:
void speak();
};
void Dog::speak()
{
cout << "Woof" << endl;
}
class Lion : public Animal
{
public:
void speak();
};
void Lion::speak()
{
cout << "ROAR" << endl;
}
int main()
{
Lion lion;
Dog dog;
Cat cat;
Animal *an[3];
an[0] = & cat;
an[1] = &dog;
an[2] = &lion;
return 0;
}
Explanation / Answer
#include <iostream>
using namespace std;
class Animal
{
private:
int legs;
public:
void setLegs(int legs);
int getLegs();
void talk();
Animal() :legs(4) {}
//void talk();
virtual void speak() = 0;
};
void Animal::talk()
{
speak();
}
void Animal::setLegs(int legs)
{
this->legs = legs;
}
int Animal::getLegs()
{
return this->legs;
}
class Cat : public Animal
{
public:
void speak();
};
void Cat::speak()
{
cout << "meow" << endl;
}
class Dog : public Animal
{
public:
void speak();
};
void Dog::speak()
{
cout << "Woof" << endl;
}
class Lion : public Animal
{
public:
void speak();
};
void Lion::speak()
{
cout << "ROAR" << endl;
}
int main()
{
Lion lion;
Dog dog;
Cat cat;
Animal *an[3];
an[0] = & cat;
an[1] = &dog;
an[2] = &lion;
for(int i=0;i<3;i++)
{
an[i]->speak();
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.