Home >Backend Development >C++ >How Can I Call a Base Class's Virtual Function from a Derived Class in C ?

How Can I Call a Base Class's Virtual Function from a Derived Class in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-13 02:28:09902browse

How Can I Call a Base Class's Virtual Function from a Derived Class in C  ?

Invoking Base Class Virtual Function Despite Override in C

In object-oriented programming, it is common for derived classes to override virtual functions from their base classes. However, situations may arise where the derived class requires access to the overridden function.

Consider the following C code:

class Foo {
public:
    int x;

    virtual void printStuff() {
        std::cout << x << std::endl;
    }
};

class Bar : public Foo {
public:
    int y;

    void printStuff() {
        // I would like to call Foo.printStuff() here...
        std::cout << y << std::endl;
    }
};

In the above example, the Bar class overrides the printStuff function, but it may also need to access the base class version.

Java's super vs. C Syntax

In Java, the super.funcname() syntax allows derived classes to call base class methods. However, C requires a different approach. To call the overridden base class function, use the following syntax:

class Bar : public Foo {
  // ...

  void printStuff() override {  // help the compiler to check
    Foo::printStuff(); // calls base class' function
  }
};

In this syntax:

  • override is optional but recommended to help the compiler ensure proper overriding.
  • Foo::printStuff() explicitly calls the base class's function.

This explicit naming is necessary because C allows multiple inheritance, unlike Java. As a result, the compiler needs to know which base class method to call when overridden.

Example Usage

Returning to the original code, the following modification allows Bar::printStuff() to access both its own data member y and the base class data member x:

void printStuff() override {
    Foo::printStuff();
    std::cout << y << std::endl;
}

This improved version of printStuff outputs the base class's x value, followed by the derived class's y value, providing desired functionality.

The above is the detailed content of How Can I Call a Base Class's Virtual Function from a Derived Class in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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