Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call virtual method without polymorphic effect?

I have reference ref:

Foo &ref = ..

I would like to call a method ref.say() which is defined as virtual in Foo and I know for sure it is overridden in child classes (because I wrote them as well).

However I would like to call say as if it was not polymorphic, so the version which is defined in Foo, not in child classes.

How to do it?

One thing that comes to my mind is to take pointer of ref, than dereference it and this trick should kill polymorphism, but I am not sure if this is guaranteed to take desired effect.

Please note, I am not sitting inside Foo or any of its child, the Foo tree is external structure from my current POV.

like image 812
greenoldman Avatar asked Jul 01 '14 12:07

greenoldman


People also ask

Can you call virtual methods?

Calling virtual methods in constructor/destructor in C++ You can call a virtual function in a constructor. The Objects are constructed from the base up, “base before derived”.

Does a virtual method have to be overridden?

When a method is declared as a virtual method in a base class and that method has the same definition in a derived class then there is no need to override it in the derived class.

Can you override a private method in C++?

C++ has access control, but not visibility control. This means that private functions are visible but not accessible. A private virtual function can be overridden by derived classes, but can only be called from within the base class.

Can a virtual method be private?

A virtual function can be private as C++ has access control, but not visibility control. As mentioned virtual functions can be overridden by the derived class but under all circumstances will only be called within the base class. Example: C++


1 Answers

How about

ref.Foo::say();

This what you looking for?

like image 179
Luchian Grigore Avatar answered Sep 30 '22 12:09

Luchian Grigore