Question about inheration

Started by
5 comments, last by iMalc 12 years, 7 months ago
Hi,

I'm currently having troubles with inheration in c++. I want to have a menue like a gui with different elements, all with the same basic commands stored in the same std::vector. So I tried inherating all menue-elements from a basic class CMenueElement. My problem:


class CMenueElement
{
public:

virtual void Render();
}

class CMenueButton : public CMenueElement
{
public:

void Render();
}

std::vector<CMenueElement> m_Elements;
CMenueButton Button;
m_Elements.push_back(Button);
m_Elements[0].Render();


Although the Render() function is declared virtual, when I call it like in the example, the render function of CMenueElement and not of CMenueButton is called. Is there any native approach for it, without having a variable storing what type of element every classmember is?
Advertisement
I believe you have to make the Render function in CMenueButton virtual as well to override CMenueElement's Render function.
You need to call the function through a pointer or reference for polymorphism to work.
Thanks to both of you, but Wooh was right! Problem solved :)
As Wooh have said, you are trying to do polymorphism there.
In order to do that you need pointers to CMenueElement on your vector. The way you did, you simply declared static CMenueElements that can only assume CMenueElement values. With pointer you can assign a CMenueButton to a CMenueElement because the inheritance assures you that "CMenueButton is a CMenueElement"

Fix the following:

std::vector<CMenueElement*> m_Elements;
CMenueButton Button;
m_Elements.push_back(&Button);
m_Elements[0]->Render(); //Updated the method access to ->


Som other noters:
1) I noticed your classes are not ending with the semicolon ( ; ). This is a common error, don't forget the semicolon =D
2) I find that is good style and practice to declare the classes' constructor and destructor even if you are not using it yet. Don't forget to do that as well!
Programming is an art. Game programming is a masterpiece!

I believe you have to make the Render function in CMenueButton virtual as well to override CMenueElement's Render function.


In C++, once virtual always virtual. The declaration of virtual in the base class is sufficient. Overrides in other subclasses will also be virtual.
What you wrote "inheration", is not even close to being a real word, and at a glance I would pronounce it "in her A shun". Oops?!
What you actually meant was "inheritance".

As for your code, on top of what others have explained, what your code was doing is called slicing. The derived part of Button was sliced off when it was inserted into the vector because it was not being stored by pointer.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

This topic is closed to new replies.

Advertisement