Sunday, 21 December 2008

STL with virtual classes and inheritance

The problem:
A fundamental concept in object oriented programming is inheritance. Inheritance allows you to declare a basic object and its derivatives as being a natural extensions one of the other. Virtual classes are the extreme manifestations of this concept, where the base class declares an interface and partial implementation and the true implementation is in the derived classes.
However, it turns out that when you try to combine STL with virtual and inherited classes you encounter a problem. For example, if class A is a pure virtual class, then the declaration list<A>will cause a compile time error.
The situation might be even worst in the following situation:

#include <vector>
#include <iostream>

using namespace std;

class A {


virtual void exe() {cout << "in class A" << endl;}


class B: public A {


void exe() {cout << "in class B" << endl;}


int main()


A a;

B b;

vector<A> v







Produces the following output:
in class A
in class B

in class A

It turns out that there is no easy way out of this problem.

No comments:

Post a Comment