Home > Backend Development > C++ > How Can I Call a Parent Class Function from a Derived Class in C ?

How Can I Call a Parent Class Function from a Derived Class in C ?

Mary-Kate Olsen
Release: 2024-12-19 07:58:33
Original
267 people have browsed it

How Can I Call a Parent Class Function from a Derived Class in C  ?

Invoking the Parent Function from a Derived Class Function in C

In object-oriented programming, a derived class inherits the attributes and methods of its parent class. When executing within the derived class, there may arise situations where you need to invoke the parent class function. Implementing this feature in C requires the understanding of inheritance and method resolution.

Calling the Parent Function Without Overriding

If the derived class does not define a method with the same signature as the parent class, you can directly call the parent's method by its name. The syntax for this is:

<parent_class_name>::<method_name>(<arguments>);
Copy after login
Copy after login

For example, in the provided scenario with classes parent and child, you can access the parent class's print function from within the child class's print function using:

class child : public parent {
public:
    void print() {
        parent::print(); // Calls the parent's print function
    }
};
Copy after login

Calling the Parent Function When Overriding

If the derived class has its own implementation of the method, you can still invoke the parent's method. However, in this case, you must use the scope resolution operator, denoted by two colons (::). The syntax for this is:

<parent_class_name>::<method_name>(<arguments>);
Copy after login
Copy after login

Using the same example from before, suppose the child class has its own print function. To call the parent class's print function, you would use:

class child : public parent {
public:
    void print() {
        // Call the parent's print function
        parent::print();

        // Call the derived class's print function
        // Implement your own functionality here
    }
};
Copy after login

By utilizing this technique, you can leverage the functionality of both the parent and derived classes, ensuring flexibility and code maintainability in your C applications.

The above is the detailed content of How Can I Call a Parent Class Function from a Derived Class 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