La Vita è Bella

Wednesday, September 13, 2006

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



tags: , , ,

22:51:34 by fishy - dev - Permanent Link

Revision: 1.0/1.0, last modified on 2006-09-14 @ 13:51.

Karma: 4 (52.13% out of 94 were positive) [+/-]

You can subscribe to RSS 2.0 feed for comments and trackbacks

Trackbacks:
There are currently no trackbacks for this item.
Use this TrackBack url to ping this item (right-click, copy link target). If your blog does not support Trackbacks you can manually add your trackback by using this form.

yasker

yasker wrote:

...
What are you doing...

Thursday, September 14, 2006 09:29:30

fishy

fishy wrote:

coding

Thursday, September 14, 2006 10:00:23

boost

boost wrote:

ok...
somewhat impressive...

Friday, September 15, 2006 08:44:54

Add Comment

 

May the Force be with you. RAmen