0

I am having trouble understanding the concept of virtual functionsin c++.i couldn't find any simple example code for me to understand.can anyone show a simple program using virtual functions and it's importance?

Thanks

2
Contributors
1
Reply
16
Views
4 Years
Discussion Span
Last Post by deceptikon
1

Here's a simple example:

#include <iostream>

class foo {
public:
    virtual void action() const { std::cout << "foo\n"; }
};

class bar: public foo {
public:
    virtual void action() const { std::cout << "bar\n"; }
};

class baz: public foo {
public:
    virtual void action() const { std::cout << "baz\n"; }
};

void do_action(const foo& obj)
{
    obj.action();
}

int main()
{
    do_action(foo());
    do_action(bar());
    do_action(baz());
}

The magic is in do_action(). It doesn't care what object in the inheritance hierarchy it's given as long as that object provides the correct interface (ie. it inherits or overrides action()). This means that you don't need to have three different overloads of do_action() that a foo, a bar, and a baz, respectively. It all just works with a reference to foo through virtual functions and dynamic binding.

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.