Function overriding in c++

 Function overriding

In this article, you will learn about the function overriding in cpp programming and how to access the function of the base class.

Inheritance allows the programmer to use class (base class)to produce the derived class.


All features of the base class transfer to the derived class.

 Let suppose a member function of the base class and derived also has the same function with the same name and same argument then what will happen?



If we create the object of the derived class and call the function. The compiler calls the function of the derived class and ignores the function of the base class. This property of the inheritance is known as function overriding in C++ language.




Example of function overriding


#include <iostream>
using namespace std;
class baseclass { // ctreate the base class
public:

   void display(){ //define and declare the display function
      cout<<"Function in the  Parent Class";
   }
};


class derivedclass: public baseclass{ //create derived class
public:

   void display() { //define and declare the display function again
      cout<<"Function in the Child Class";
   }
};


int main() {
   derivedclass obj ;
   obj.display();
   return 0;
}


Output:

Function in the Child Class

How to access the override function of the base class from the child class?


For accessing the override function of the base from the child class the scope resolution operator is used.

In the child class, access the function of the base with the help of a scope resolution operator.

Scope resolution operator:
(::)

Example of how to access the function of the base:

#include <iostream>
using namespace std;

class baseclass { // ctreate the base class
public:
   void display(){ //define and declare the display function
      cout<<" in the  Parent Class";
   }
};


class derivedclass: public baseclass{ //create derived class
public:
   void display() {
//define and declare the display function again

      //call the base class display function

      baseclass::display();
   }
};


int main() {
   derivedclass obj ; //create an object of the derived class
   obj.display(); //call the display function
   return 0;
}


Output:
in the  Parent Class

In this example, note that calls the display with the base name and scope resolution operator. The compiler calls the function display of the derived because the object is a derived class. Then in the display function call the base function call.


Please write a comment,if you find anything incorrect and any problem in the above topic or you want to share more information about the above topic.

Comments

Hire a programmer

Popular posts from this blog

CSS selector

C program to convert decimal to binary number

C Program to convert binary to decimal number