Re: c++ : a baseclass, derived classes, a list of baseclass pointers, a problem.
- From: Gerry Quinn <gerryq@xxxxxxxxxxxxxxxxxxx>
- Date: Thu, 12 Jan 2006 13:19:24 -0000
In article <43c58a1c$0$21033$9b4e6d93@xxxxxxxxxxxxxxxxxxxxxxxxxx>,
sid_kkr@xxxxxxxx says...
> Hello out there..
> I have a problem and no idea how to fix it..
> The language is c++.
>
> I have a base class, for example:
>
> class a{
> public:
> virtual void func1(void) { }
> };
>
> Then i have some derived classes, maybe c, d, e...
> I overwrote the virtual function func1() in each derived class.
>
> Now i created a list of pointers to insances of the baseclass
> within stl.
>
> list<a*>mylist;
>
> This is used to store pointers of the instances from
> classes c, d, e.
> So I could use this in one list..
>
> The only Problem is:
> If i go trough the list in a for loop,
> and execute the func1-
> How can I execute the right function?
> I use a pointer to the baseclass to loop trough
> the list.
>
> I think i should determine which class it really is,
> so i can cast the pointer to the right type,
> because now theres always the function of the baseclass
> executed.
That's the clever bit - you don't have to. Each instance of the
classes c, d and e contains a pointer to a thing called the vtable, of
which a separate one exists for c, d and e. The vtable in turn points
to the correct virtual function for each class.
So when the virtual function is called, the computer finds the correct
function for the class that is actually present.
> Is this idea right?
> How can i find out, which class the instance is of,
> from outside of the class?
As you see, it's not necessary. That's the whole point of virtual
functions!
You could cast to the base class and investigate the vtable pointer,
but there are probably better ways to do such things if you need to.
- Gerry Quinn
.
- Follow-Ups:
- References:
- Prev by Date: Re: What is the difference between reversing a string and reversing a string in place?
- Next by Date: Re: Who's Jeff Arnold?
- Previous by thread: c++ : a baseclass, derived classes, a list of baseclass pointers, a problem.
- Next by thread: Re: c++ : a baseclass, derived classes, a list of baseclass pointers, a problem.
- Index(es):
Relevant Pages
|