0

C++ Virtual Functions Animal Zoo Challenge

can someone please HALP #include <iostream> using namespace std; class Animal { public: int x; string name; //your code goes here void speak(){ cout << &name <<end; } }; class Dog: public Animal { public: void speak() { cout <<"Woof!"<<endl; } }; class Cat: public Animal { public: void speak() { cout <<"Meaw!"<<endl; } }; int main() { Cat c1; c1.name = "Fluffy"; Dog d1; d1.name = "Bingo"; Animal *a1 = &c1; Animal *a2 = &d1; Animal* arr[] = {a1, a2}; for(int i=0;i<2;i++){ arr[i]->speak(); } }

6th Nov 2023, 10:34 PM
David
David - avatar
3 Antworten
+ 3
//your code goes here void speak(){ cout << name << endl; //debug }
7th Nov 2023, 12:05 AM
Solo
Solo - avatar
+ 2
You have couple of errors in the code. Your speak function in Animal class should be declared as virtual because it allows it to be owerridden in derived classes. virtual void speak(){ cout << name << endl; } Then for Dog and Cat respectively: void speak() override { cout << "Woof!" << endl; } void speak() override { cout << "Meaw!" << endl; }
7th Nov 2023, 12:29 AM
Dejan Francuz🥇
Dejan Francuz🥇 - avatar
+ 1
Worng way:- void speak(){ cout << &name << endl; //debug } correct way :- virtual void speak(){ cout << name << endl; //debug } if you use '&' with name it will return address value which store in heaps
7th Nov 2023, 12:02 PM
Alhaaz
Alhaaz - avatar