-1

So, I know something like this is asked a lot, but the other answers seem to indicate that this should work, so I thought I'd ask about my code specifically. I spend more time in .NET and Java, so maybe I'm forgetting something.

I'm creating a base widget and a set of specific widgets (buttons, other graphical items). I'm trying to loop through a linked list of widgets and what I would like is for the specific rendering method for that specific widget to be called. Below is simplified code that demonstrates my problem, on my first call to Render, the specific render function is called. If I pass a cGeneralWidget pointer to a function which calls the Render object, the base method was called. I thought, as long as I send a pointer, C++ is smart enough to know what the object really is and call the overridden method.

Otherwise, whats the correct way to deal with a collection of base objects and call the derived methods as appropriate?

Thank you.

class cGeneralWidget
{
public:
    void Render()
    {
        int a = 99;
    }
};

class cSpecificWidget : public cGeneralWidget
{
public:
    void Render()
    {
        int a = 99;
    }
};

void GeneralRenderingFunction(cGeneralWidget * b)
{
    b->Render();   // <-- calls the base function
}

int main(int argc, char* argv[])
{

    cSpecificWidget wd;
    wd.Render();   // <-- calls the derived function
    GeneralRenderingFunction(&wd);  

    return 0;
}
Chris
  • 629
  • 1
  • 10
  • 28

2 Answers2

3

You should define Render() method in your base class with virtual keyword and in your derived class with override keyword. If you don't put virtual keyword in your base class implementation then C++ wouldn't mark it as virtual.

class cGeneralWidget
{
public:
    virtual void Render()
    {
        int a = 99;
    }
};

class cSpecificWidget : public cGeneralWidget
{
public:
    void Render() override
    {
        int a = 99;
    }
};
Onur A.
  • 3,007
  • 3
  • 22
  • 37
1

in your base class

class cGeneralWidget
{
public:
    virtual void Render()
    {
        int a = 99;
    }
};

Render has to be virtual so it overrides it

Note : A virtual function a member function which is declared within base class and is re-defined (Overriden) by derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.

Spinkoo
  • 2,080
  • 1
  • 7
  • 23