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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With