Given a pointer to a derived object, which has overridden some method virtual void moo()
, is there a way to call the base's moo()
method?
One way is to create a sliced base class object from the derived object, but that would involve copying:
#include <iostream>
class A {
public: virtual void moo() { std::cout << "moo from A\n"; }
};
class B final : public A {
public: void moo() override final { std::cout << "moo from B\n"; };
};
int main() {
A* a_ptr = new B; // could point to any A or A-derived object.
A a(*a_ptr); // is there a way to get A::moo without doing this?
a.moo(); // moo from A of course, but would be cooler without the copy above
}
Why would I wanna do that you ask?
So glad that you ask... not, because now I have to explain everything to you. Well A's virtual void moo()
is actually more like std::string serialize()
, which gives A's data members serialized into a std::string
. Now when you have a big std::vector<A*>
pointing to all sorts of derived objects and only the data from the base objects are needed (to be sent over network), it'd be nice to get only A::moo
s, although those pointers in that vector point to all sorts of moos.
(I'm aware of the possibility to 'simply' put a second void moo2()
into A, that does not get overridden. But I'd also like to know if there's a third or fourth alternative.)