Thursday, June 07, 2012

Virtual Function revisited

http://objectlayer.blogspot.ca/2006/01/what-is-virtual-function.html
Equivalent of the interface in java for polymorphism. It is static late binding for virtual function which the derived class will override this virtual function, it is not a member of class. If append by = 0 , the object cannot instantiate only from pointer because it is a pure virtual function. The cla will be called Abstract Base Class (ABC). The pure virtual function is not defined so does the object therefore cannot create an object from ABC.
//--C++ virtual function
#include <iostream>
#include <string>

using namespace std;

class Animal
{
        public:
        Animal(const string& name) : name(name) {};
        virtual string talk() = 0;  //Need pure virtual function here
        //virtual string talk();
        const string name;
};

class Cat : public Animal
{
        public:
        Cat(const string& name) : Animal(name) {};
        virtual string talk() { return "Meow!"; }
};

class Dog : public Animal
{
        public:
        Dog(const string& name) : Animal(name) {};
        virtual string talk() { return "Arf! Arf!"; }
};

// prints the following:
//
// Missy: Meow!
// Mr. Mistoffelees: Meow!
// Lassie: Arf! Arf!
//
int main()
{
        Animal* animals[] =           // only create pointer no object for Animal
        {
                new Cat("Missy"),
                new Cat("Mr. Mistoffelees"),
                new Dog("Lassie")
        };

        for(int i = 0; i < 3; i++)
        {
                cout << animals[i]->name << ": " << animals[i]->talk() << endl;
                delete animals[i];
        }
        return 0;
}

No comments: