Virtual method in OOP

I have a chance to play with C++ in the last week. It wasn't so hard, but I forgot a lot, like namespace, library, method arguments or signature.. One big thing that I think I forgot is the "virtual method", or virtual function. So I post this article to remind me about this.

The idea of virtual function is simple. In OOP, you sure know about inheritance, virtual function is a method which child class can override (re-implement) the method of parent class. It seems simple but virtual function play an important role in OOP, especially for polymorphism. I'm quite lazy now, so I will grab the example code from wikipedia :-D

#include <iostream>
#include <vector>
 
using namespace std;
class Animal
{
public:
    virtual void eat() const { cout << "I eat like a generic Animal." << endl; }
    virtual ~Animal() {}
};
 
class Wolf : public Animal
{
public:
    void eat() const { cout << "I eat like a wolf!" << endl; }
};
 
class Fish : public Animal
{
public:
    void eat() const { cout << "I eat like a fish!" << endl; }
};
 
class GoldFish : public Fish
{
public:
    void eat() const { cout << "I eat like a goldfish!" << endl; }
};
 
 
class OtherAnimal : public Animal
{
};
 
int main()
{
    std::vector<animals>;
    animals.push_back( new Animal() );
    animals.push_back( new Wolf() );
    animals.push_back( new Fish() );
    animals.push_back( new GoldFish() );
    animals.push_back( new OtherAnimal() );
 
    for( std::vector::const_iterator it = animals.begin();
       it != animals.end(); ++it) 
    {
        (*it)->eat();
        delete *it;
    }
 
   return 0;
}

The output will look like this:

I eat like a generic Animal.
I eat like a wolf!
I eat like a fish!
I eat like a goldfish!
I eat like a generic Animal.

Without virtual declared, this will like this:

I eat like a generic Animal.
I eat like a generic Animal.
I eat like a generic Animal.
I eat like a generic Animal.
I eat like a generic Animal.

Actually, why I kept forgetting about virtual function because of the way languages are implemented differently. Like, in Java, all methods are virtual by default so no virtual explicit declaration is required. But in C# you must declare it explicitly (like C++).

An other problem with virtual function is pure virtual function or abstract function. This is how we declare it in C++

class Abstract {
public:
   virtual void pure_virtual() = 0;
};

And in C# or Java, we use abstract keyword.

abstract class B {
    abstract void a_pure_virtual_function();
}

I just get things wired up all the time. Maybe, finally, the only problem here is my short-term memory :(

2 Comments

Add new comment