virtual class in c++
Here's a example to make a virtual class in c++, similar to "interface" in Pascal and Java:
1 #include <stdio.h>
2 #include <string>
3 #include <vector>
4
5 class base_foo {
6 public:
7 virtual std::string name() { return "base_foo"; }
8 };
9
10 class foo: public base_foo {
11 public:
12 std::string name() { return "foo"; }
13 };
14
15 class bar: public base_foo {
16 public:
17 std::string name() { return "bar"; }
18 };
19
20 int main() {
21 std::vector<base_foo*> foo_list;
22 foo f;
23 bar b;
24 foo_list.push_back(&f);
25 foo_list.push_back(&b);
26 printf("%s\n%s\n",
27 foo_list[0]->name().c_str(),
28 foo_list[1]->name().c_str());
29 return 0;
30 }
The result of this program is:
foo
bar