This question is similar, but is about calling the function from inside the class: Can I call a base class's virtual function if I'm overriding it?
In that case, you'd specify Base::function()
instead of function()
, which will call the overridden definition.
But is there a way to do this outside of the class? My class doesn't define a copy constructor, so I couldn't figure out how to cast as the base class:
Base( derived_object ).function()
Is the appropriate thing to do here to cast & derived_object
as Base*
and then call ->function()
?
Thanks for your insight.
But if we plan to define the member function outside the class definition then we must declare the function inside class definition and then define it outside. The main function for both the function definition will be same. Inside main() we will create object of class, and will call the member function using dot .
Yeap. You definitely shouldn't do this in production code, but in this case you can call class method using empty pointer and it will work. Technically you don't create a class instance.
Using a qualified-id to call a base class' function works irrespectively of what happens to that function in the derived class - it can be hidden, it can be overridden, it can be made private (by using a using-declaration), you're directly accessing the base class' function when using a qualified-id.
Try derived_object.Base::function();
I believe the syntax:
derived_ptr->Base::function();
works just fine. Though I really question why you would want to do this in a function that's not part of your class. Especially if function
happens to be a virtual function.
The reason why it's a questionable idea is that you're making whatever it is that uses that notation depend on the inheritance hierarchy of your class. Also, functions are usually overridden for a reason. And you're getting around that by using this syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With