Virtual function woes

Started by
2 comments, last by Endurion 16 years, 9 months ago
I have a base window class that has a function Create that gets called when the window is created. I declare a virtual function OnCreate in this class which is called at the end of Create which is supposed to be overridden in derived classes so they can add their own initialization code there. The problem is that even though I've overridden OnCreate in my derived class the version from the base class is being called. I thought this was a pretty straight-forward thing I was doing here but I can't for the life of me figure out what's wrong. Is it that I'm calling the function from a function in the base class? Any ideas anyone? Thanks for taking a look and for any suggestions. Edit: I tried declaring OnCreate as pure virtual (which I'm pretty sure I shouldn't have to do) and the program crashes "pure virtual call" when I run it. It's really doing its best to call that original function. Edit2: Found this http://www.3dsoftware.com/Programming/OpenGL/ on Google and I swear they're describing exactly what I'm doing. [Edited by - My_Mind_Is_Going on July 22, 2007 11:15:41 PM]
Advertisement
Are you calling Create from the base class constructor? If yes, this is the cause. Virtual functions cannot call the overriden versions if the class is not completely constructed yet.

If no, then how do you store the window class handle? In an array/STL container of base class instances? If yes, you've got shearing happening.
You're creating a derived class but upon storing the derived part gets clipped off. In that case you need to change the storage type from base class to a pointer to the base class. Otherwise polymorphism doesn't work.

Fruny: Ftagn! Ia! Ia! std::time_put_byname! Mglui naflftagn std::codecvt eY'ha-nthlei!,char,mbstate_t>

I'm calling Create from the WndProc WM_CREATE handler. WndProc is getting a pointer to the window object and then calling windowObject->Create so it's using a base class pointer. This is happening with pretty much all the OnEvent functions I declared in the base class which I have the WndProc calling for various messages, the base class versions are always being called.

Edit: Oh I'm an idiot, the WM_CREATE message is being sent from CreateWindowEx which is being called in the constructor so that would be the reason. I like this chain of events though so should I just move the window creation to a separate function?, because doing it during the constructor is obviously not an option.
Yes, that would solve the problem. Just make an Initialise or Create method in your class.

You'll have to call the method separately, but then you know it'll work.

Fruny: Ftagn! Ia! Ia! std::time_put_byname! Mglui naflftagn std::codecvt eY'ha-nthlei!,char,mbstate_t>

This topic is closed to new replies.

Advertisement