tags:

views:

113

answers:

2
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)?

+13  A: 
d.Base::foo();

May the force be with you.

Daniel Daranas
+1 for you too Daniel - strange how you're answer didn't show up at first for me.
ChrisBD
@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.
Daniel Daranas
+5  A: 
d.Base::foo();

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

Marcelo Cantos
+1 @Marcelo - you're too quick for me :)
ChrisBD
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.
AndreyT
Well it defeats both. But `b->Base::foo` *only* defeats virtual dispatch.
Johannes Schaub - litb
Good point, AndreyT.
Marcelo Cantos