Question about virtual methods

IF both methods are declared virtual, should not both instances of Method1 (), which are called the derived class Method1 ()?

I see BASE and then DERIVED every time. I am doing a review for an interview, and I want to make sure that I have it directly. 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

+4
source share
5 answers

What you see here is called "slicing" . Selecting an object of a derived class from the base class "cuts off" everything that is not in the base class.

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

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

Or you could do

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

No, listing ((BaseClass)myClass) "C-style" creates a temporary BaseClass object, slicing myClass. Its dynamic type is BaseClass , it is not DerClass at all, therefore Method1 called by the base class method.

myClass.Method1() is a direct call. Since myClass is an object, not a link, there is no virtual dispatch (would not be necessary).

+14
source

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

+12
source

Since the listing of ((BaseClass)myClass) myClass the DerClass object from DerClass to BaseClass , so only the BaseClass implementation of Method1() called.

For polymorphism to work correctly, you must call methods with pointers:

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

or links:

 DerClass myClass; BaseClass& refToMyClass = myClass; refToMyClass.Method1(); // Calls the DerClass implementation of Method1() 
+5
source

((BaseClass) MyCLASS) .Method1 (); β†’ splitting objects, so the base class method will always be called. Real polymorphic behavior is achieved using the base class pointer, which can contain any objects of derived classes. Therefore, to achieve what you want, you need to pass the address of the object of the derived class, and typecase is a pointer to the base class. as shown below: ((BaseClass *) & myClass) β†’ Method1 ();

0
source

Source: https://habr.com/ru/post/1308940/


All Articles