Some object-based programming languages have the “super” keyword, which enables a subclass to invoke functions and members of the base or parent class. Some programming languages determine how the “super” keyword should be used specifically. But in the case of C++, the super keyword is not used in the same manner as in Java and Python. In this tutorial, we will study and demonstrate the emulation of super keywords in C++.
How to Emulate the super Keyword In C++
The keyword known as “super” is not predefined in the C++ compiler. The inheritance and function override are used to develop a subclass that takes its superclass’s members and methods. Just provide the identifier of the “superclass” and the member or method you wish to access with the operator (::).
Syntax
You can access a method in a superclass named “parent_class” that has a name like “parent_function()” in a subclass by using the syntax shown below:
Example
Using C++ to emulate the super keyword functionality to access the properties of a parent class, use the scope resolution operator(::).
The scope resolution operator (::) can be employed to obtain the members of a parent class whenever a class inherits from it. Consider the following code as an example:
using namespace std;
class base_Class {
public:
void baseFunction() {
cout<< "This is the outout of baseFunction from the base class" << endl;
}
};
class derieved_Class: public base_Class {
public:
void dFunction() {
base_Class::baseFunction();
cout << "This is derived class that accessing baseFunction from the base class " << endl;
}
};
int main() {
derieved_Class d;
d.dFunction();
return 0;
}
The above program is having a function from the base or parent class baseFunction(). Another derived class is defined which is accessing the baseFunction() in the dFunction(). The main method is first creating an instance of the derived_class and calling the dFunction() which is printing the output of both baseFunction() and dFunction().
Conclusion
Although the “super” keyword does not directly exist in C++, its behavior can be mimicked by combining inheritance and function overrides. We can successfully call and use methods or members of the superclass by calling the functions of the superclass first before moving on to the implementation of the subclass. This post also provided an instance of C++ code for your better understanding.