So I've got a simple task to do. There are 3 classes derived from one base class. They're quite simple and will be provided below.
What I need to do is create a new class called PolymorphicAnimal
, that'll be able to behave just as any other animal
derived from the Animal
base class.
To be exact, all they need to do is display the right text after method SoundOff
is called. I'm guessing I need to use dynamic_cast
here. My question is, what's the right syntax for using dynamic_cast
as an if
statement, and do all the derived classes need to have at least one virtual method as well?
#include "stdafx.h"
#include <iostream>
#include <string>
class Animal {
public:
virtual std::string SoundOff() = 0;
};
class Dog : public Animal {
std::string SoundOff() override { return "Woof"; }
};
class Cat : public Animal {
std::string SoundOff() override { return "Meow"; }
};
class Cow : public Animal {
std::string SoundOff() override { return "Muu"; }
};
class PolymorphicAnimal : public Animal {
std::string sound;
public:
PolymorphicAnimal(const Animal &a) {
if(std::dynamic_cast<Cat*>(a))
}
};
The line if(std::dynamic_cast...
generates compiler errors:
syntax error '<', illegal token on the right side of ::
and expected an identifier