Child Initialisation

A child class inherits members from its parent which it needs to initialise, as per any other class.

 

The preferred style of setting the attributes is to use an initialisation list, as can be seen in the parent class on line 11 in the example below.

 

The child also utilises an initialisation list, as per line 25. In this case, the first four attributes of the child object are of the same (inherited) type as the parent and therefore the parent class is utilised to initialise these values. This can be seen in the first parameter of the initialisation list: Motorbike(a,b,c,d), the remaining attributes for the child class are then initialised in the usual manner:

#include <iostream>
#include <string>
using namespace std;
class Motorbike {
	protected:
		string make, model ;
		int speed, cc ;
	public:
		//constructor
		Motorbike(string a, string b, int c, int d) :
				  make(a), model(b), speed(c), cc(d) {}  //initialisation list

	void showMotorbike() {
			cout << "Make: " << make << ", Model: " << model << \
			", Speed: " << speed << "mph, cc: " << cc << endl ;
		}
};

class Sports : public Motorbike {
	private:
		string track;
		int position ;
	public:
		//constructor
		Sports(string a, string b, int c, int d, string e, int f) :
						Motorbike(a,b,c,d), track(e), position(f) {}  //initialisation list

	void showSports() {
		cout << "Make: " << make << ", Model: " << model << \
		", Speed: " << speed << "mph, cc: " << cc << ", Track: " << \
		track << ", Position: " << position << endl ;
	}
};

int main() {

	Motorbike street("Honda", "Fireblade", 190, 1000) ;
	Sports racer("Ducati", "Panigale", 185, 1198, "Silverstone", 2) ;

	street.showMotorbike() ;

	racer.showSports() ;

	return 0;
}

Compile & Run:

Make: Honda, Model: Fireblade, Speed: 190mph, cc: 1000
Make: Ducati, Model: Panigale, Speed: 185mph, cc: 1198, Track: Silverstone, Position: 2

Leave a Reply