Reputation: 13
could you please help me? I have a question about virtual functions. I'm having a hard time getting this code to work. Could someone help me please? I can't get the attributes of the dog or cat to be printed at the end of the program. This is the error code: error: invalid use of ‘class Animal::soundDuringFeeding’ error: invalid use of ‘class Animal::animalSound’
#include <iostream>
using namespace std;
class Animal
{
public:
class soundDuringFeeding
{
public:
virtual void eat() = 0;
};
class animalSound
{
public:
virtual void meow() = 0;
virtual void bark() = 0;
};
};
class Dog : public Animal
{
public:
void bark()
{
cout<<"Au Au Au"<<endl;
}
void eat()
{
cout<<"Chomp chomp"<<endl;
}
};
class Cat : public Animal
{
public:
void meow()
{
cout<< "Miau"<<endl;
}
void eat()
{
cout<<"Slurp"<<endl;
}
};
int main()
{
Animal *songs;
int choose = 0;
cout<<"Choose the animal: 1 - Dog | 2 - Cat"<<endl;
cin>>choose;
if(choose == 1)
{
songs = new Dog();
}
else if(choose == 2)
{
songs = new Cat();
}
songs->soundDuringFeeding;
songs->animalSound;
return 0;
}
Upvotes: 0
Views: 312
Reputation: 2625
your structure and understanding of inheritance is little off, eather way you have to use it like this to achive common behavior:
#include <iostream>
using namespace std;
class Animal
{
public:
public:
virtual void eat() = 0;
// method has to have more general name but mainly the same name, the
// nested class action you were doing there was far from right, its as if
// you just tried random staff
virtual void makeSound() = 0;
};
class Dog : public Animal
{
public:
// renamed
void makeSound()
{
cout<<"Au Au Au"<<endl;
}
void eat()
{
cout<<"Chomp chomp"<<endl;
}
};
class Cat : public Animal
{
public:
// renamed
void makeSound()
{
cout<< "Miau"<<endl;
}
void eat()
{
cout<<"Slurp"<<endl;
}
};
int main()
{
Animal *a;
int choose = 0;
cout<<"Choose the animal: 1 - Dog | 2 - Cat"<<endl;
cin>>choose;
if(choose == 1)
{
a = new Dog();
}
else if(choose == 2)
{
a = new Cat();
}
// now you can call methods invoked with '()' syntax
a->eat();
a->makeSound();
return 0;
}
i highli recomend entering inheritance cpp
or virtual cpp
to browser
Upvotes: 1