开发者

Question on Virtual Methods

开发者 https://www.devze.com 2022-12-29 13:36 出处:网络
IF both methods are declared as virtual, shouldn\'t both instances of Method1() that are called be the derived class\'s M开发者_如何学Pythonethod1()?

IF both methods are declared as virtual, shouldn't both instances of Method1() that are called be the derived class's M开发者_如何学Pythonethod1()?

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


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.


What you are seeing here is called "slicing". Casting an object of the derived class to the base class "slices off" everything that is not in the base class.

In C++ virtual functions work correctly only for pointers or references. For your example to work right, you have to do the following:


DerClass myClass;
((BaseClass *) &myClass)->Method1();

Or you could do


BaseClass *pBase = new DerClass;
pBase->Method1();


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


((BaseClass)myClass).Method1(); --> object slicing hence always base class method will get called. Real polymorphic behaviour is achieved through base class pointer which can contain any objects of derived classes. Hence to achieve what you want you need to do pass address of derived class object and typecase it to base class pointer. as below: ((BaseClass *) &myClass)->Method1();

0

精彩评论

暂无评论...
验证码 换一张
取 消