Calling Parent Class Functions in Derived Classes
In C , code reusability and inheritance are achieved through the concept of derived classes inheriting methods and properties from their parent classes. This raises the question of how to invoke parent class functions from within derived classes.
Calling Parent Functions Directly
If the parent class function is not declared private, it is automatically accessible to the derived class. Therefore, you can directly call the parent function from within the derived class method without any special syntax.
For instance, consider the following code:
class Parent { public: void print() { std::cout << "Parent class print function" << std::endl; } }; class Child : public Parent { public: void printWithParent() { print(); // Inherits from Parent and can be called directly } };
Calling Parent Functions with Ambiguity Resolution
If a function with the same signature exists in both the parent and derived classes, there is a potential ambiguity. To resolve this, you can specify the parent class explicitly by using the syntax:
parent_class::function_name(...);
For example, if Child also defines a print() function, you can disambiguate it as follows:
class Child : public Parent { public: void print() { std::cout << "Child class print function" << std::endl; } void printWithParent() { Parent::print(); // Calls the Parent class print function } };
Conclusion
Calling parent class functions from derived classes in C is straightforward. By following these guidelines, you can effectively utilize inheritance and achieve code reusability and maintainability.
The above is the detailed content of How Do I Call Parent Class Functions from Derived Classes in C ?. For more information, please follow other related articles on the PHP Chinese website!