Don't forget to implement pure virtual method:
virtual void quack() = 0 ;
When you declare an object normally, you can not new
it. And when you declare it as a pointer you have to call its items by ->
.
QuackBehavior quackBehavior;
quackBehavior = new Quack() ; // <------- ERROR, quackBehavior is not a pointer
and
Duck mallard = new MallardDuck(); // <------- ERROR, mallard is not a pointer
mallard.performFly() ; // <-------- ERROR, you must use -> instead of .
// if mallard is a pointer
Finally, use this code:
class MallardDuck: public Duck
{
public:
MallardDuck()
{
}
void display()
{
std::cout << "I'm a real duck\n" ;
}
};
int main(int argc, char const *argv[])
{
Duck *mallard = new MallardDuck() ;
mallard->performFly() ;
mallard->performQuack() ;
...
delete mallard;
}
You're learning C++, after understanding pointers, it's good to know and use smart-pointers(std::unique_ptr
, std::shared_ptr
) instead of bare pointers.