Polymorphism question - not working like I tought
Ok, since I`m from Java background I tried to do the following
like in the Java, at first. Consider the Java code:
Code:
public abstract class Animal
{
public abstract void makeVoice(); // no implementation
}
public class Dog implements Animal
{
// the implementation of abstract method
public void makeVoice()
{
System.out.println("WUF!");
}
}
now, I tried to convert the above:
Code:
class Animal
{
private:
protected:
public:
virtual ~Animal() {}
virtual void makeVoice() = 0;
};
class Dog : public Animal
{
private:
protected:
public:
~Dog() {}
void makeVoice() { cout<<"WOF!";}
}
All fine this far. Ok, I can do thefollowing with Java
Code:
Animal animal = new Dog();
animal.makeVoice(); // -> "WOF!"
but if I do it with C++
Code:
Animal *animal = new Dog();
animal->makeVoice(); // this won`t compile
----------
c:/djgpp/lang/cxx-v3/bits/stl_construct.h:78: cannot allocate an object of type
`Animal'
c:/djgpp/lang/cxx-v3/bits/stl_construct.h:78: since type `Animal' has
abstract virtual functions
-----------
....but I assigned the animal to of type Dog, which implements
the needed function.
What I`m doing wrong here?