I'm looking at the source code for the Godot game engine, and came across the following (some omitted for simplicity):
// popup_menu.cpp
int PopupMenu::_get_mouse_over(double x) const
{
if (x >= get_size().width)
return -1;
// ...
}
// control.cpp
Size2 Control::get_size() const
{
return data.size_cache;
}
Why is it legal to call the method get_size()
without first instantiating an object of type Control
and then invoking its member function? I tried to recreate this behavior in my own file, but it would not compile as I would normally expect:
class Control
{
public:
double get_size() const;
};
double Control::get_size() const
{
return 5.0;
}
class PopupMenu
{
public:
int _get_mouse_over(double d) const;
};
int PopupMenu::_get_mouse_over(double d) const
{
return d > get_size(); // compile error, as expected
}
What could be causing this behavior? If you are interested, the actual source code for each of these methods can be found at:
line 110: https://github.com/godotengine/godot/blob/master/scene/gui/popup_menu.cpp
line 1770: https://github.com/godotengine/godot/blob/master/scene/gui/control.cpp
I searched for this question and found C#: calling non static member function without creating object which does not answer my question, since in his case there actually was an instance that the method was being invoked through (and it's a different language).
Becuase PopupMenu
derives from Control
, every instance of PopupMenu
is also an instance of Control
.
When a member function of PopupMenu
calls get_size()
, it calls Control's get_size()
function on itself.
Or stated differently, PopupMenu
has a get_size()
function because it is derived from Control
.
In your recreation, PopupMenu
doesn't derive from Control
so this does not apply.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.