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 "Derived Method" as the output - Why does this happen?
I understand that DerivedClass
inherits from BaseClass
, and therefore derived
can call method1
, but I don't understand why method2
from DerivedClass
hides method2
from BassClass
when it is being called from BaseClass
.
Apologies for any bad code/mistakes - still new to C++.
Because method2
is virtual
.
When you declare a function as virtual
, what you're really doing is making it so that when the method is called via a pointer or reference (in other words, in a normal way) the function that is actually called is the most-derived overload.
This is a Good Thing, and usually exactly what you want. Note that it doesn't matter from what context you make the call. Your'e calling method2
from the context of the base class, which has an implementation of method2
available. Presumably, you're assuming that since your calling from the base class that the base class' implementation is the one that will be called.
That's not how virtual
s work -- and that's also a Good Thing.
You can, if you wish, call the version in the base class by being explicit about it:
class BaseClass {
public:
virtual void method1(){
BaseCLass::method2();
};
But this is usually not desirable, and in my book, a code smell.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments