Pure virtual function is any function that is virtual and is ending with =0;
virtual void Foo() = 0;//pure virtual function
Pure virtual function may have implementation, but can't be called by object - you can only call it like
Class::Function()
, and you are only allowed to do so in classes that are derived from this class.
(about pure virtual funct. implementation -> see
http://stackoverflow.com/questions/2089083/pure-virtual-function-with-implementation )
Each pure virtual function
must be implemented in derived class.
Any class that contains pure virtual function is an abstract class. You can't create instance of an abstract class. You can, however, create a pointer to abstract class:
Animals* ptr;
This is used for polymorphism.
You have your problem, because you don't understand abstract class and polymorphism well. It happens :)
Abstract class works as a "blueprint". When you are writing many complex classes, sometimes you may want to split them into few smaller classes - like you want to do with animals. This feels natural. However, you must remember one thing: abstract class should have such functions, that will allow you to do what you want.
Let's take a look at this small example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include <string>
#include <iostream>
class Animal
{
private:
std::string name;
public:
Animal(std::string _name) : name(_name) {}
virtual int GetLives() = 0;
inline std::string GetName() { return name; }
};
class Cat : public Animal
{
public:
Cat() : Animal("Cat") {}
int GetLives() { return 9; }
void Meow() { std::cout <<"Meow!" << std::endl; }
};
int main(int argc, char* args[] )
{
Cat pussy;
std::cout << "I'm a pussy! I'm a " << pussy.GetName() <<" and I have " << pussy.GetLives() << " lives! " << std::endl;
pussy.Meow();
Animal* pusy = new Cat();
std::cout << "I'm a pusy! I'm a " << pusy->GetName() <<" and I have " << pusy->GetLives() << " lives! " << std::endl;
//pusy->Meow(); -> This won't work! Class Animal has no member named "Meow()"
return 0;
}
|
As you can see, with polymorphism we can't use Meow() on Animal*. What should we do about it?
You can cast it:
|
dynamic_cast<Cat*>(pusy)->Meow();
|
However, casting isn't something great. What is another option?
You could make function like
1 2 3 4 5 6 7
|
class Animal
{
//code...
public:
virtual void Speak() = 0;
};
|
And have every animal implement it on its own. Or, you could use base class where you don't need to use Animal*.
Cheers!