Jump to content
  • Advertisement
Sign in to follow this  
Muzlack

Calling virtual functions from child class

This topic is 4818 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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
}
}


Share this post


Link to post
Share on other sites
The orignal code will work, func just has to be protected or public, not private, in order to call it from the derived class.

Share this post


Link to post
Share on other sites
Actually, I realized the problem was elsewhere... I accidently stuck the code in the base class (on the real classes)

*ashamed*

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!