0

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::moos, 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.)

nada
  • 2,109
  • 2
  • 16
  • 23
  • @TheUndeadFish Using the namespace resolve thing - No that's only possible from inside the derived object. – nada Feb 16 '21 at 08:03
  • `a_ptr->A::moo();`. – songyuanyao Feb 16 '21 at 08:04
  • @songyuanyao Really? I was not aware of that. – nada Feb 16 '21 at 08:04
  • If you wants to call base class' overridden function using derived class' object then here is the [answer](https://stackoverflow.com/a/15853092/1468487) – masterop Feb 16 '21 at 08:05
  • @nada The syntax was shown in [this answer](https://stackoverflow.com/a/6319619/5538420) under the linked question. – dxiv Feb 16 '21 at 08:05
  • Or another if you prefer - https://stackoverflow.com/questions/15853031/call-base-class-method-from-derived-class-object (note that googling "c++ call base class method" led me to these pretty fast). – TheUndeadFish Feb 16 '21 at 08:06
  • @TheUndeadFish I'm duckduckgoing, and that led to nothing. Wouldn't get back to googling though. And yes that last question includes the needed syntax. – nada Feb 16 '21 at 08:08

1 Answers1

2

You can by using the calling syntax used when calling member function pointers.

(a_ptr->A::moo)();

Or by simply stating where the function comes from (which scope it contains; from which parent class).

a_ptr->A::moo();
D-RAJ
  • 3,263
  • 2
  • 6
  • 24