Reputation:
Imagine a huge code base with many many inheritance. At some point a line comes in your way in the class you have to work with.
inherited::Load();
This is do what it says. It loads the base object into memory.
inherited is a typedef for the base class.
However the actual parent class does not have a Load method.
As a quick example:
class Base {
public:
Base() {};
void Load() {
cout << "Base ok" << endl;
}
};
class Derived : public Base {
public:
Derived() {};
};
class MostDerived : public Derived {
public:
MostDerived(){};
void Load() {
Derived::Load();
cout << "Child ok"<< endl;
}
};
Here, if we call MostDerived.Load()
it will call its parent's Load method, but the Derived class doesn't have its own Load, only Base's Load method.
What is actually going on here? Why there is no compilation issue? Is the Derived class copies all the method of the base, so it will have a Load method what is prints "Base ok"? Or does Derived simply calls forward the Base method?
I found a related question Do ALL virtual functions need to be implemented in derived classes? and the answer says
It inherits the bar implementation from its ancestor class.
For me it still miss leading that explicitly calling the Derived::Load() method works. However, there is only a Base::Load() method exists.
Upvotes: 0
Views: 45
Reputation: 122516
What is actually going on here? Why there is no compilation issue? Is the Derived class copies all the method of the base, so it will have a Load method what is prints "Base ok"?
Yes. A derived class inherits all methods from the base class. (yes really all of them, whether it can access them depends on the access specified for the methods).
For me it still miss leading that explicitly calling the Derived::Load() method works. However, there is only a Base::Load() method exists.
Sloppy speaking the Derived::
only tells the compiler to look for names accesible from Derived
. As Derived
does inherit from Base
, it does have a Load
method.
Maybe your confusion can be cleared up a bit by noting that Derived::Load
indeed does refer to Base::Load
:
#include <type_traits>
#include <iostream>
struct Base {
void Load() {}
};
struct Derived : Base {};
int main() {
std::cout << std::is_same_v< decltype(&Derived::Load), void (Derived::*) ()>;
std::cout << std::is_same_v< decltype(&Derived::Load), void (Base::*) ()>;
}
This prints 01
, because Derived::Load
is indeed a method of Base
.
I hope the example is not adding confusion ;). It uses std::is_same
to see if two types are the same. &Derived::Load
gives me a member function pointer to the Load
method in Derived
whose type I infer via decltype
. I compare that once to pointer to method of Derived
and then to pointer to method of Base
. It turns out that Derived::Load
is a method of Base
.
Upvotes: 2