Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to call a base function outside of the class in C++?

Tags:

c++

oop

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.

like image 840
user Avatar asked Jan 11 '13 23:01

user


People also ask

How do you call a function outside the class?

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 .

Can you call the base class method without creating an instance in CPP?

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.

Can we call base class function using derived class object?

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.


2 Answers

Try derived_object.Base::function();

like image 147
Eric Avatar answered Nov 13 '22 06:11

Eric


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.

like image 23
Omnifarious Avatar answered Nov 13 '22 04:11

Omnifarious