Overriding

Allows inherited methods to be redefined.

 

Prototype of the Child must have the same signature as the Parent.

 

In this example the Parent and the Child have the same method theFunc() (on lines 12 and 22 respectively) which is being implemented differently in the Child, on line 23:

#include<iostream>
#include <string>
using namespace std ;

class Parent {
	protected :
		string name ;
	public :
		Parent(string parentName) : name(parentName) {
			cout << "Initialising " << parentName << "'s Parent attributes" << endl ;
		}
		void theFunc(){
			cout << "Using Parent method! " << name << " has " << name.length() << " letters" << endl ;
		}
};

class Child : public Parent {
	public :
		Child(string childName) : Parent(childName) {
			cout << "Initialising " << childName << "'s Child attributes" << endl ;
		}
		void theFunc(){
			cout << "Using Child method! " << "The are " << name.length() << " letters in " << name << endl ;
		}
};

int main(){

	Parent parentObject("Bill") ;
	parentObject.theFunc() ;
	cout << endl ;

	Child childObject("Ted") ;
	childObject.theFunc() ;

	return 0 ;
}

Compile & Run:

Initialising Bill's Parent attributes
Using Parent method! Bill has 4 letters 

 

Initialising Ted's Parent attributes
Initialising Ted's Child attributes
Using Child method! The are 3 letters in Ted

 

 

Alternatively, you can simply add to the Parent's method (called on line 23), and adding to, as per line 24:

#include<iostream>
#include <string>
using namespace std ;

class Parent {
	protected :
		string name ;
	public :
		Parent(string parentName) : name(parentName) {
			cout << "Initialising " << parentName << "'s Parent attributes" << endl ;
		}
		void theFunc(){
			cout << "Using Parent method! " << name << " has " << name.length() << " letters" << endl ;
		}
};

class Child : public Parent {
	public :
		Child(string childName) : Parent(childName) {
			cout << "Initialising " << childName << "'s Child attributes" << endl ;
		}
		void theFunc(){
			Parent::theFunc() ;
			cout << "Using Child method! " << "If you squared the number of letters in " \
					<< name << " you'd get " << name.length() * name.length() << " letters!" ;
		}
};

int main(){

	Parent parentObject("Bill") ;
	parentObject.theFunc() ;
	cout << endl ;

	Child childObject("Ted") ;
	childObject.theFunc() ;

	return 0 ;
}

Compile & Run:

Initialising Bill's Parent attributes
Using Parent method! Bill has 4 letters 

 

Initialising Ted's Parent attributes
Initialising Ted's Child attributes
Using Parent method! Ted has 3 letters
Using Child method! If you squared the number of letters in Ted you'd get 9 letters!

Leave a Reply