PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

General C++ OOP Problem

Hey all... I haven't in the past done much in C++, most of my PPC development has been mostly straight C. I'm doing something now that is OO, and I'm facing an issue, and because my OOP experience is almost entirely Java, I'm not quite sure how to deal with it in C++...

Here's what I have... I have a base class:

Code:

class OGEventHandler {
public:
void click() { }
};


This is to be an event handler class that will be "registered" with another class, which has the following:

Code:

class OGWidget {
public:
OGEventHandler* eventHandler;
void registerEventHandler(OGEventHandler* in_eventHandler) {
eventHandler = in_eventHandler;
}
void dispatchEvent(int eventType) {
if (eventHandler != NULL) {
switch (eventType) {
case OG_EVENT_CLICK: {
eventHandler->click();
break; }
}
}
}
};


The idea of course being that a client would create a subclass of OGEventHandler, implementing the appropriate methods, register it with an OGWidget object, which will dispatch as appropriate to the registered event handler class. Here's an example of usage:

Code:

// Class definition for the event handler specific to the button I will create
class Button1EventHandler : public OGEventHandler {
public:
void click() {
MBT(TEXT("click!")); // Just displays a popup
}
};

...then later on...

// pButton is a valid pointer to an object of type OGButton, a subclass of OGWidget
pButton->setText(TEXT("My First Button"));
pButton->setFont(fntVGA);
pButton->show();
Button1EventHandler* eh = new Button1EventHandler();
pButton->registerEventHandler(eh);


Ok, so now we come to the problem... Everything works exactly as expected until the event is dispatched... It in facts calls the click() method in the OGEventHandler class, NOT the click() method in the Button1EventHandler class. In other words, I'm getting the method of the parent class rather than the subclass.

It makes sense to me based on my Java experience... because the eventHandler pointer in OGWidget is of type OGEventHandler, it only knows about the click() implementation in that exact type, not the subclass type.

My question though is how to deal with this? In Java I would of course cast eventHandler to Button1EventHandler, but since the OGWidget class would never know about the subclass, I don't see how I can do that.

Am I missing something obvious, or is this not possible? Or is a refactoring of some sort required to make it work?

Thanks in advance!
are you declaring the base class function to be virtual?


take a look at http://www.cplusplus.com/doc/tutorial/tut4-4.html

i think that should sort things out, hope it helps
Argh... I don't know whether I should thank you for helping me or curse you for making me feel like an idiot! :) Big D'OH! moment here.

That was EXACTLY the problem. Declared click() in the base class to be virtual, and off I went. Ugh.

The worst part about it is that I correctly did have virtual members in a couple of other related classes.

One other related question now that THAT one is solved...

What if I want to have default implementations for those methods? In other words, I'd really like to have just an empty click() method in OGEventHandler so that a subclass doesn't have to implement what it isn't interested in. Not sure how to do that. Feel like making me bang my head on the desk one more time?!? :)

Thanks a bunch!
Basically what you have would work for default implementation:

virtual void click() { /* Do nothing. */ }

To force a derived class to implement a function;

virtual void click() = 0;


EDIT:
One more thing, be sure to specify virtual for the overridden functions in the derived class as well. ie;

Code:

class EventHandler
{
public:
virtual void click() { }
virtual void mustImplementFunc() = 0;

virtual ~EventHalder();
};

class Button: public EventHandler
{
public:
virtual void click();
virtual void mustImplementFunc();
};


Hope that helps.

EDIT2:

While I'm at it, be sure you always declare the base class destructor as virtual as well (editted code above).
Interesting... I thought I had tried that and it didn't work... It is now though... Thanks for all the help guys, I'm now exactly where I want to be!
The system your using will be cool

Say we have your base class function

void click()

this can be declared in two ways


virtual void click(){}

or

virtual void click()=0;


the first is an empty declaration so if a derived class doesn’t override this function the base class will get called

the second is an abstract declaration, this forces the derived class to implement this method or you’ll get linking errors


so if you use the first way and put the default functionality into the base class this will get called if your derived class dosnt implement the function, but if it does it will call the code in the derived class not the base.

Sorry if that’s not clear please say ill try again ;)

edit: hehe dan typing at the same time
dan.p: I'm unsure why you say to declare the method virtual in the derived class... Is it just to allow for extensibility? If so that's a good point, if not I'd like to understand! :)

Structure: Very clear, thank you!

In case anyone couldn't guess from the names, I'm working on a GUI system. So far I have a button done, thanks to the help you guys gave. I'm actually almost at the point where I just have to create all the actual widgets, the base widget class and the layout manager are probably 95% done to what I planned on for the first iteration, so I'm pretty happy right now :)
As im here,

Yes its good coding practice for future extendibility, only leave it out if you have a good reason why a possible extended class should never override the functionality
That's what I figured. Kind of frustrating sometimes... I'm quite familiar with OOP techniques, but C++ is just different enough sometimes from Java to make C++ confusing when I'm doing Java all day :) Thanks again!
Oops, spoke to soon... I guess I don't fully understand the need for declaring the virtual method in the derived class (I understand the REASON for it, but not the NEED)...

If class A has a virtual method in it (defined with an empty method body), and class B extends A but does NOT implement that method, and then class C extends class B, wouldn't class C still be able to implement that method by virtue of it's parent class (B) extending class A?

It sounds like you guys are saying the inheritance of a virtual method ends with any class that doesn't implement it or define it as virtual itself, i.e., is lost to any derived classes after that down the hierarchy. Is that the case?
I've only been coding in C++ for three months, but there's one thing I've learned the hard way:

Always apply good coding practices when programming in C or C++, otherwise you're in for trouble later on. C/C++ does whatever you tell it, even if it's blatantly fubard code.

Examples:

FLOAT fX = 1.25;
DWORD dwX = (DWORD) fX;

This one caused me quite a few problems and took me a while to figure out

#define FunMacro(x) x / 2;

// Somewhere in your code..
FunMacro(5 + 233);

Yet one reason why macros should be avoided, because errors are so easy to make with them if they aren't properly handled

So many things can happen, it's endless. Be careful. ;)

As for your particular virtual fun, I do believe the class inherited from must have virtual in front of the function if you want polymorphism to take effect. If you don't define a function as virtual in one of the derived classes, then the buck stops there, and fun things begin to happen. :P
Actually ive just been testing this cos I wasn’t sure its just something I took for granted but it looks like frank is right there’s no need to declare it a virtual as long as the base class is virtual it will still call the highest function even of the function is not declared virtual lower down in the tree or even declared.

Im assuming ive been told its good practice because you could at some stage take a derived class and remove its derivation from the base class then the inheritance tree would start there, but that sounds silly to me

What It does do I guess is make the code more readable in terms of knowing that the function is going to be over written without having to follow it back to the base, but again this doesn’t seem like a concrete reason

Id be interested if anyone could further clarify this.
Interesting! I'm glad it works that way, at least I'm not going crazy :)

For me, it makes more sense to NOT declare it in the derived class because if you think of what I'm doing, which is an event handler class that is the basis for event handling for ALL GUI widgets, the base class is going to have all sorts of methods for various events, many of which won't apply for a given widget type (like maybe doScroll() for a button, doesn't make any sense!).

To me, it would just be cluttering up the derived class if I have to declare a virtual doScroll() method, even though it doesn't apply. Better to just leave it out, knowing if someone derives a new type of button from my OGButton class, they could still implement that method if need be because it will still be inherited from the base OGWidget class.

I'm with you though... it's be cool if someone smarted than us (well, smarter than *ME* anyway :)) could give us a more definitive answer.
EDIT:
Quoted you wrong. Rephrasing what I said.

I don't find it silly to declare derived class functions virtual. If you think about it, by declaring a derived classes function virtual, you're saying "this function overrides the function in the derived class."

When programming you always want to be clear with what you're doing, even if it makes no difference if you left out a keyword or not. After all, we are dealing with a language, and you want to say what you're doing clearly. I'm reminded of a quote.. not sure exactly what it was, but something along the lines of "good code comments itself." I think that'd apply here.

Also, every compiler is different. Some compilers may treat virtual slightly different, and require it to be there. Although I find it unlikely, but you never know.
Here's a quick explanation of several of C++'s mechanisms (I think I have this right):

When you call a member function, the actual function signature called (of several overloaded functions) is chosen at compile time. This is the mechanism which knows to call click(int) or just plain click() if they are overloaded.

Now, when you have derivation, the member functions in the base class are also exposed to the derived class. So if you have click() in the base class and init() in the derived class, you can call click() on the derived class as well (even though it wasn't declared or overridden in that class).

Which brings us to the "hiding problem." If you have click() in the base class but then add click(int) to the derived class, the latter function signature "hides" the former, and the derived class doesn't "inherit" that function.

At least, you can't call it with a derived class instance (or pointer). Because, remember, the function is chosen at compile time! The base signature is simply not considered during overload resolution. Similarly, if you call through a base class instance (or pointer), the signature in the derived class is not considered. Put simply, you can't overload signatures across classes (even base and derived), hence the problem.

Overloading and overriding are two different, unrelated things.

Now, the whole "dynamic binding" mechanism is completely orthogonal to all of this. What you're doing by marking a method "virtual" is allowing derived classes to supply their own implementations, and telling the function call to do a member function pointer lookup at run time.

Again let me stress: the function SIGNATURE to call is chosen at compile time, and the function IMPLEMENTATION to call is chosen at run time (in the case of dynamic binding).

You do not need to redeclare those overridden derived implementations as virtual: they will be virtual no matter what. Because remember, the function signature you are calling is in the base class (where it is already declared virtual) and the compiler knows this already. Still, it's considered good practice to do so.

Yes you should have a virtual destructor if you have virtual methods. Otherwise, the compiler will generate a destructor for you (all classes have destructors) but it won't be virtual. This could lead to incorrect behaviour.
Thanks mlepage but


Still, it's good practice to do so.


Im not really seeing why so much?
Structure wrote:Thanks mlepage but


Still, it's good practice to do so.


Im not really seeing why so much?


I don't personally buy in to the argument that it allows you to sever an inheritance hierarchy without unexpectedly overridden member functions from virtual to non-virtual, because I believe you'd have to be incompetent or negligent to make such a deep change to your code without investigating all possible implications and verifying the changes.

It's one of those things where it doesn't hurt to have it there (the language standard allows it) and it acts as a reminder.

In that respect it's like naming your parameters in a function's declaration. This isn't necessary (names are required in the function's definition; the declaration requires only the types) but it's universally done.
dan.p wrote:
#define FunMacro(x) x / 2;

// Somewhere in your code..
FunMacro(5 + 233);


Macros have their appropriate uses, although they are few and for the rest, more appropriate mechanisms exist and should be used.

Macros are tricky to write correctly, due to their inherent nature as a text replacement mechanism. Therefore, there exist quite a few "guidelines" to writing them which should be understood and followed (in most cases).

One such guideline is that all macro arguments are enclosed in parentheses. Another is that the entire macro be enclosed in parentheses.

This would eliminate the problem quoted, hence the value of these guidelines.

The core issue is that even the most trivial programming language (that can do real work) is really quite complex, and humans can't just write code haphazardly and achieve the results they expected. Like any difficult human endeavour, it helps to know your tools, practice, and get help if necessary.