views:

145

answers:

4

IF both methods are declared as virtual, shouldn't both instances of Method1() that are called be the derived class's Method1()?

I am seeing BASE then DERIVED called each time. I am doing some review for an interview and I want to make sure I have this straight. xD

class BaseClass
{
public:
    virtual void Method1()  { cout << "Method 1 BASE" << endl; }
};

class DerClass: public BaseClass
{
public:
    virtual void Method1() { cout << "Method 1 DERVIED" << endl; }
};


DerClass myClass;
    ((BaseClass)myClass).Method1();
    myClass.Method1();

Method 1 BASE
Method 1 DERVIED

+12  A: 

No, because the virtual function mechanism only works if a function is called via a pointer or a reference. Otherwise the static type of the object is used to determine which function to call.

anon
Ah. Thanks everyone for the explanation! :D
bobber205
+4  A: 

Because the cast ((BaseClass)myClass) slices the myClass object from DerClass to BaseClass, so only the BaseClass's implementation of Method1() is called.

For polymorphism to work properly, you must call the methods via pointers:

DerClass myClass; 
BaseClass* ptrToMyClass = &myClass;
ptrToMyClass->Method1(); // Calls the DerClass implementation of Method1()

or references:

DerClass myClass; 
BaseClass& refToMyClass = myClass;
refToMyClass.Method1();  // Calls the DerClass implementation of Method1()
In silico
+12  A: 

No, the "C-style" cast ((BaseClass)myClass) creates a temporary BaseClass object by slicing myClass. It's dynamic type is BaseClass, it isn't a DerClass at all so the Method1 being called is the base class method.

myClass.Method1() is a direct call. As myClass is an object, not a reference there is no virtual dispatch (there would be no need).

Charles Bailey
Good call on the slice. It's always frames a good question to ask candidates to see if they have a clear distinction between C++ and say Java or C#.
Nathan Ernst
+5  A: 
Dima