Main menu

Pages

C++ Overriding functions - Learn CPP

C++ Overriding functions - Learn CPPThe C++ programming language allows programmers to use the concept of (overriding) like other programming languages, which means defining the same function that the Derived class inherited from the main class (Super Class) again, and this new function is similar to the inherited function In terms of form only, in other words, they have the same name, type and number of parameters, but their content is different in order to be more proportional to the derived class.

The main objective of using the concept of (overriding) is to provide the opportunity for the derived class to define functions according to its needs.


C++ Overriding functions - Learn CPP



Conditions for using the concept of overriding in the C++ programming language


There are a set of conditions that must be met in order for the programmer to be able to use the concept of (overriding) in the programming language (C++), which are:


Overriding functions in C++


  • The programmer must use the same Modifier with the new function, that is, the same that was used with the old function, and it must be of type (public) or (protected).
  • The number and type of parameters in the new function must match the number and type of parameters in the old function.
  • The return type of the new function must be the same as the return type of the old function.
  • The function that has been declared of type (private) cannot be used by the programmer with the concept of (Override), since the word (private) prevents direct access to the function from the derived class.
  • A function that has been defined of type (final) cannot be used by the programmer with the concept of (overriding), since the word (final) prevents changing the function's content after it has been defined.
  • The function defined is of type (static). The programmer cannot use the concept of (overriding) with it, but he can define it again anywhere, as the word (static) makes the function common to all classes.
  • The programmer cannot use the concept of (overriding) with the constructor.

The following is an example showing how the concept of (overriding) works in the C++ programming language:


// C++ program to demonstrate function overriding

#include <iostream>

using namespace std;

class Base {

public:

void print() {


cout << "Base Function" << endl;

} 
};


class Derived : public Base {

public:

void print() {

cout << "Derived Function" << endl;

} 
};

int main() {

Derived derived1;

derived1.print();

return 0;

}