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();
Virtual function trouble
Hi,
I have problem with virtual functions. This is what I want to do:
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.
But why wouldn't you not be able to call DrawImpl directly?
I'm doing that for the OS abstraction layer in my projects.
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?
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.
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.
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:
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:
Enigma
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
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement