Skip to main content
gamedev.net
🔒 Locked

Inheritance problem...

Started by Toolmaker Nov 26, 2003 at 5:40 AM 5 replies 700+ views
Original Post
Toolmaker
Toolmaker
I am having a few weird inheritance problems, which I don''t seem to be able to solve. I always figured that use a virtual function in the base class, would have it overwritten when it''s derived. Since I did this(below), somehow it doesn''t call the functions in the derived class.
class CBase
{
public:
    CBase();
    ~CBase();
    virtual void X(int i, int n);
};

class CDerived : public CBase
{
public:
    CDerived();
    ~CDerived();
    virtual void X(int i, int n);
};

class CApp : public CDerived
{
public:
    CApp();
    ~CApp();
    void X(int i, int n);
};
CApp App;
App.X(1, 1);
 
That code results in CDerived::X(int i, int n) being called, instead of my CApp::X() function, why is this? Toolmaker
-Earth is 98% full. Please delete anybody you can.
 
Buzzy
Buzzy
[Edit] Nevermind... its really late/early, and I didn't read the entire code chunk...

I don't know what you could be doing wrong, sorry.

[edited by - Buzzy on November 26, 2003 6:47:14 AM]
Toolmaker
Toolmaker
Found it, seems I need to make the functions in CApp virtual aswell. Problem solved.

Toolmaker



-Earth is 98% full. Please delete anybody you can.
 
arunvb
arunvb
May I know which compiler you are using ?

The function in CApp does not have to be virtual to be called by a CApp object and your original code works fine (calls the CApp:X as expected) in VC++ 7
Qw3r7yU10p!
Qw3r7yU10p!
quote:
Original post by Toolmaker
Found it, seems I need to make the functions in CApp virtual aswell. Problem solved.



That''s not right. There shouldn''t be a problem with the original code. How do you know Derived::X is being called rather than CApp::X ?

Is the example you are showing not the actual code?
LiquidNRG
LiquidNRG
Declaring the function as virtual in the base class should be enough. There must be a problem somewhere else....
Jingo
Jingo
As the others said, you should not need to declare the function virtual, as stated in 10.3.2 of the standard

quote:

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or
indirectly from Base, a member function vf with the same name and same parameter list as Base::vf is
declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.



[edited by - jingo on November 27, 2003 7:26:51 AM]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.