Virtual function trouble

Started by
6 comments, last by TrueTom 18 years, 8 months ago
Hi, I have problem with virtual functions. This is what I want to do:


class Base
{
public:
    void Draw()
    {
        DrawImpl();
    }

    virtual void DrawImpl()
    {
        // 1)
    }
}


class Special : public Base
{
public:
    virtual void DrawImpl()
    {
        // 2)
    }
}

...

Special Instance;

// This function call should call 2), but actually 1) is called !?
Instance.Draw();



Advertisement
I may not know everything, but in the first class DrawImpl is referenced to the DrawImpl in that class, it has no knowledge over the other class.

But why wouldn't you not be able to call DrawImpl directly?
I'm doing that for the OS abstraction layer in my projects.
The code is just fine and should do what you want. Check again.
Quote:Original post by TrueTom
Hi,

I have problem with virtual functions. This is what I want to do:

*** Source Snippet Removed ***


What is your problem? What do you want to do?
"C lets you shoot yourself in the foot rather easily. C++ allows you to reuse the bullet!"
mldaalder:

It's just for convience. Base::Draw does some other stuff too. Special::DrawImpl could call the base class function but that's what I wanted to avoid.


mikeman:

I'm sorry but it doesn't work. I also checked the __vfptr, the entry for the function points to the base class function.


vNistelrooy:

See the source code comments.
Ok, I'm with stupid... :)

The problem was that Base::DrawImpl is 'const' and Special::DrawImpl wasn't. This is legal and the compiler doesn't issue a error.

Thanks everyone.
Post your real code. The code you posted (when cleaned up to be valid C++) does exactly what you'd expect it to do (i.e. it calls Special::DrawImpl). I suspect you're slicing your object:
void func(Base b){	b.Draw(); // will always call Base::DrawImpl, because b is a Base}int main(){	Special s;	func(s);}

Also, for added safety you can make your virtual function private in your base class. This will prevent anyone other than Base calling it, but still allow you to override it in derived classes:
class Base{	public:		void function()		{			doFunction();		}	private:		virtual void doFunction();};class Derived	:	public Base{	private:		virtual void doFunction();};int main(){	Derived d;	d.function(); // calls Derived::doFunction();	d.doFunction(); // error, Derived::doFunction not accessible}


Enigma
Thanks Enigma.

This topic is closed to new replies.

Advertisement