you can find loads of examples-definitions on google.. go through them.. then when you have more specific doubts ppl here can help .. happy learning :)
Agni
Practically a Master Poster
655 posts since Dec 2007
Reputation Points: 431
Solved Threads: 116
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
Virtual functions are the backbone of runtime polymorphism. You can use a member function declared as virtual to redefine the behavior of a base class. Then, when accessing a derived class through a pointer or reference to the base class, the redefined member function will be called:
#include <iostream>
class base {
public:
virtual void foo() const { std::cout<<"base\n"; }
};
class derived: public base {
public:
virtual void foo() const { std::cout<<"derived\n"; }
};
void do_foo ( const base& b )
{
b.foo();
}
int main()
{
do_foo ( base() ); // Call 1
do_foo ( derived() ); // Call 2
}
This works because in do_foo, b has two types. The static type is the type of object the code says the reference refers to (base in all cases). The dynamic type is the type of object the reference actually refers to (base in call 1, derived in call 2).
The virtual mechanism is a way to access the dynamic type safely and easily.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401