Inherited members

A Child class inherits members of the Parent according to the Access Specifiers: public, private, protected

 

The Child can also call the constructor of the Parent in its initialisation list, as per line 3 (any required values should be included within the parentheses - if the Parent constructor requires these values):

class Child : public Parent {
	public :
		Child() : Parent()
		{
		}
} ;

 

Similarly, the Child inherits the attribute identifiers, but not the values, of the Parent and can then utilise its own methods upon these attributes, say, to set its own values for these inherited fields.

 

This example shows the Child utilising the Parent's protected string name, which it then uses within its own method on line 26, which can be called as per line 37:

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

class Parent {
	protected :
		string name ;
	public :
		Parent(string parentName) : name(parentName) {
			cout << "Constructing Parent attributes for " << parentName << endl ;
		}
		~Parent(){
			cout << "Destroying Parent attributes for " << name << endl << endl ;
		}
};

class Child : public Parent {
	public :
		Child(string childName) : Parent(childName) {
			cout << "Constructing Child attributes for " << childName << endl ;
		}
		~Child(){
			cout << "Destroying Child attributes for " << name << endl ;
		}

		string getName(){return name ;}
};

int main(){

	cout << "Instantiating Parent" << endl ;
	Parent parentObject("Bill") ;

	cout << endl << "Instantiating Child" << endl ;
	Child childObject("Ted") ;

	cout <<	childObject.getName() << " had its Parent's attributes constructed before its own" << endl ;

	cout << endl << "Objects will now be destroyed" << endl ;
	return 0 ;
}

Compile & Run:

Instantiating Parent
Constructing Parent attributes for Bill 

 

Instantiating Child
Constructing Parent attributes for Ted
Constructing Child attributes for Ted
Ted had its Parent's attributes constructed before its own

 

Objects will now be destroyed
Destroying Child attributes for Ted
Destroying Parent attributes for Ted

 

Destroying Parent attributes for Bill

 

 

Leave a Reply