Posted by JHD on 1999-09-14
Kspansel@xxx.xxx wrote:
>
> > But in your example, the method show() is defined as virtual in the parent
> > class. And as the documentation states you don't have to add the virtual
> > keyword in the childclass. If you add the virtual keyword to some method it
> > will be a virtual method in all it's childclasses.
>
> What I understood with the virtual functions is that if you have some thing
> like this:
>
> class Test
> {
> public:
> int SomeFunction();
> };
>
> And you derive a child class from this with the same function:
>
> class ChildTest : public Test
> {
> public:
> int SomeFunction();
> }
>
> You can call it fine when you do it this way:
>
> ChildTest ct;
> int ret = ct.SomeFunction(); //calls ChildTest::SomeFunction()
>
> But you make it a pointer then like so:
>
> ChildTest *ct;
> int ret = ct->SomeFunction(); //calls Test::SomeFunction();
^^^^^^^^^^^^^^^^^^^
This calls ChildTest::SomeFunction();...
an example:
ChildTest ct;
ChildTest *pct = ct;
Test *pt = ct;
int ret = pt->SomeFunction(); //This one calls Test::SomeFunction();
int ret2 = pct->SomeFunction(); //This one calls
ChildTest::SomeFunction();
if the function was virtual the pt->SomeFunction(); would call
ChildTest::SomeFunction();
it makes it easy to have one pointer that can control different derived
objects that need slightly different functionality. it's very useful in
some inctances like GUIs as Frank pointed out.
---
Name: James H. Durbin
E-mail: divine-bovine@xxxx.xxx
Previous post | Next post | Timeline | Home