4
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by Narue
0

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 :)

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.