Calling virtual functions from child class

Started by
8 comments, last by Muzlack 19 years, 1 month ago
Hi. This should be a pretty simple question. Is it possible to call a base class's version of a virtual function? For example, if you wanted to implement your virtual function in a way that "extends" the base class's. Here's a (crude) example of what I'm trying to do:

class class1
{
     virtual int func()
     {
         //do some stuff here   
     }
}

class class2 : public class1
{
     int func()
     {
          class1::func();
         
          //do some more stuff here
     }
}

The way I displayed my code was the way I would IMAGINE that it would work. Is this possible to do? Thanks, Bryce The way de
--Muzlack
Advertisement
yup.
Yeah, but it doesn't work :(
--Muzlack
Quote:Original post by Muzlack
Yeah, but it doesn't work :(


really?

*double check code*

Ah, this is the syntax I used, which compiles and works with MS VC++6:
((base_class *)this)->base_class::function();


but umm... that's really nasty, and most OOP folks will chastize you for trying to superset classes like that.
No, the first thing you posted should work. It might have private scope, which may be the error, though.
Quote:Original post by Muzlack
Yeah, but it doesn't work :(
Yes, it does. The error lies elsewhere, such as not realizing that there is no way to inherit private members.
You can inherit private members and override them, but you cannot call them. It's perfectly acceptable to override a virtual function in a derived class (and is actually advocated by Herb Sutter)
"Is life so dear, or peace so sweet, as to be purchased at the price of chains and slavery?" - Patrick Henry
One easy workaround would be the following. It's a little ugly, but it does get the job done easily.

By moving the guts to a different non-virtual function, it can still be accessable from subclasses (so you can do other stuff, as well as call the super-classes functionality.

class class1 {     public:     virtual int func() {         return func_class1();        }     protected:     int func_class1() {         //  do stuff, notice this isn't virtual     }}class class2 : public class1 {     int func() {         //  do some stuff         func_class1();         //  do some other stuff     }}

The orignal code will work, func just has to be protected or public, not private, in order to call it from the derived class.
"Is life so dear, or peace so sweet, as to be purchased at the price of chains and slavery?" - Patrick Henry
Actually, I realized the problem was elsewhere... I accidently stuck the code in the base class (on the real classes)

*ashamed*
--Muzlack

This topic is closed to new replies.

Advertisement