Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question on Virtual Methods

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

like image 992
bobber205 Avatar asked Nov 28 '22 01:11

bobber205


1 Answers

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).

like image 108
CB Bailey Avatar answered Dec 13 '22 11:12

CB Bailey