Overriding Member Function in C++





Overriding member function

We can define data member and member function with the same name in both base and derived class. When the function with same name exists in both class and derived class, the function in the derived class will get executed. This means, the derived class will get executed. This means, the derived class function overrides the base class function.

E.g.

 

Class base A

{

Public:

Void getdata ()

{

————-

————–

}

};

Class derived B: public base A

{

Public:

Void getdata ()

{

—————-

—————-

}

};

Void main ()

{

Derived B obj;

Obj. getdata ();

getdata ();

}

 

When the statement obj. getdata (); get executed, the function getdata () of the derived class i.e. of derived B get executed. This means, the derived class function overrides the base class function.

The scope resolution (:: ) operator can be used to access base class function through an object of the derived class.

E.g.

 

Derived B obj;

Obj. Base A:: getdata ();

The above statements specify that the getdata () of base A is to be called.

A base class function can be accessed from within the derived class by as follows also:

Class derived B: public base A

{

Public:

Void getdata ()

{

Base A:: getdata ();   // call getdata () of base A

}

};



Related posts:

  1. Defining Member Function In C++ Class methods definitions  (Defining the member functions) Member functions can...
  2. Array of class objects Array of class objects and single inheritance A program consisting...
  3. Class Hierarchies Class Hierarchies The relationship between a base ad derived classes...
  4. Derivation in C++ Types of derivation Inheritance is a process of creating a...
  5. C++ Base Class Type of base classes in C++ A base class can...