Home > Backend Development > C++ > How Do I Call Parent Class Functions from Derived Classes in C ?

How Do I Call Parent Class Functions from Derived Classes in C ?

Patricia Arquette
Release: 2024-12-21 10:03:11
Original
347 people have browsed it

How Do I Call Parent Class Functions from Derived Classes in C  ?

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
  }
};
Copy after login

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(...);
Copy after login

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
  }
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template