8
class Base { public: virtual void foo() const { std::cout << "Base"; } }; class Derived : public Base { public: virtual void foo() const { std::cout << "Derived"; } }; Derived d; // call Base::foo on this object 

Tried casting and function pointers but I couldn't do it. Is it possible to defeat virtual mechanism (only wondering if it's possible)?

1

2 Answers 2

24

To explicitly call the function foo() defined in Base, use:

d.Base::foo(); 
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for you too Daniel - strange how you're answer didn't show up at first for me.
@ChrisBD: After posting it, I suddenly realized that I couldn't remember ever having used this construct directly (only inside the definition of the function in the derived class). Hence, I decided to delete it for a while, until I was sure that it worked.
6
d.Base::foo(); 

Note that d.foo() would call Derived::foo regardless of whether foo was virtual or not.

2 Comments

Er... Actually a fully-qualified name defeats virtual dispath specifically. You seem to be assuming that d.foo() call is not virtual. The language says nothing like that. d.foo() call is virtual from the language point of view, i.e. it is resolved in accordance with the dynamic type of d. If your compiler dispatches it statically, it is nothing else than an optimization done by your compiler (because the dynamic type is known at compile time). From the language point of view, the only way to defeat virtual dispatch is to use a fully-qualified name.
Well it defeats both. But b->Base::foo only defeats virtual dispatch.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.