class BaseClass { public: virtual void method1(){ method2(); }; virtual void method2(){ std::cout << "Base Method" << std::endl; }; } class DerivedClass : public BaseClass { virtual void method2(){ std::cout << "Derived Method" << std::endl; }; } int main() { DerivedClass derived; derived.method1(); }
In the above example, I get the "Derived Method" as the output. Why is this happening?
I understand what DerivedClassinherits from BaseClass, and therefore derivedcan cause method1, but I do not understand why method2from DerivedClasshides method2from BassClasswhen it is called from BaseClass.
DerivedClass
BaseClass
derived
method1
method2
BassClass
Apologies for any bad code / errors - still new to C ++.
Because method2- virtual.
virtual
virtual, , , , , ( , ), , .
, , . , , . method2 , method2. , , , , .
, virtual - .
, , , :
class BaseClass { public: virtual void method1(){ BaseCLass::method2(); };
, - .
derived.method1() BaseClass::method1(), method2(). DerivedClass::method2() BaseClass::method2().
derived.method1()
BaseClass::method1()
method2()
DerivedClass::method2()
BaseClass::method2()
BaseClass::method2() BaseClass::method1(), :
class BaseClass { public: virtual void method1(){ BaseClass::method2(); //explicit class scope prevents dynamic binding } virtual void method2(){ std::cout << "Base Method" << std::endl; } };
. , . - . . 12 " ++ ( )" .
virtual method2() BaseClass. " ". method1 of BaseClass, method2 of BaseClass.
, - ( ). - ( ) . , DerivedClass method2 , " ".
Source: https://habr.com/ru/post/1535792/More articles:Why was the Java For condition expression ignored? - javaDjango + AjaxHow to develop an application using the Tor network? - apiDjango JQuery AJAX Request Form - ajaxparseFloat () vs parseDouble () - javahttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1535793/copy-c-datatable-and-convert-all-values-to-string&usg=ALkJrhiKcQw2-5Yg3rUq-pRd8G4It7dRQAJQuery DataTables - Refresh table data after Post ColdFusion - jqueryGet all subsequences of a numpy array - pythonHow to use centos doc file with ubuntu host? - dockerXcode Server bot could not read property lists using default command - command-lineAll Articles