PocketMatrix forums

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

upcast virtual function

I need to upcast a virtual class member function (to call a base class implementation of that function), but I don't want to slice the object (create a new copy of the object as the base class type) because of performance reasons.

How is this done?

Example:
Code:

class base {
virtual void foo();
};

class derived : base {
virtual void foo();
}

derived a;
a.foo(); //Want to call base::foo here, not derived::foo


Dan East
You can't. I would suggest moving the content of base::foo() to a non-virtual method base::foo2() or base::fooimpl and have base::foo() call that. Then you can directly call base::foo2.

But to be honest, that just sounds like bad design. Share more context and I'll be able to help more.
i think if you got the vtable directly you should be able to call it.
Yes. And you can also call any address in memory using assembly too.
It has to do with a GUI library I have, where the bass class implementation does something simple, like set the position of an item. A derived class has a catch-all implementation for containers of objects, that has some undesirable behavior with positioning child objects. Basically I wanted to position the container, but not have its generic routine try to reposition any children.

The correct solution is for me to derive another layer on top of the container class.

Dan East
Dan East wrote:How is this done?

Maybe my C++ is getting rusty, but couldn't you just say a.base::foo();

Look Stroustrup, C++, 3rd ed., p. 311.

- HM
We have a winner! I tried several different methods of casting, but just sticking the base:: in there looks strange to me.

Thanks.

Dan East