4. Overriding, Overloading, Delegation #

Created Sunday 2 February 2022

Functions with same name as base class member #

Assume there’s a public function named run in a class Vehicle. If we inherit Vehicle publicly as Car and define a function run in it with the same signature as Vehicle::run, then calling run from main using a Car object calls Car::run and not Vehicle::run.

This is called member function overriding.

class Vehicle {
	public:
		void run()
		{
			cout << "Vehicle run called\n";
		}
};

class Car : public Vehicle {
	public:
		void run()
		{
			cout << "Derived run called\n";
		}

		void delegateRun()
		{
			Vehicle::run();
			// still availale inside, but have to be explicit
		}
};

int main()
{
	Car obj;
	obj.run(); // calls Car::run

	obj.delegateRun(); // calls Vehicle::run
}

Overloading of base member functions #

Overriding happens only if signature matches. If it doesn’t, public members of the base class are available as usual.

Delegation of duty #

class Vehicle
{
	Vehicle(); // assume constructor defined
	~Vehicle(); // assume destructor defined
};

class Car
{
	Car()
	{
		Vehicle(); // initializes inherited data members
		// logic for Car initialization
	}

	~Car()
	{
		// logic to de-allocate Car first - as inherited stuff is coupled with this
		~Vehicle(); // de-allocate the inherited members now
	}
}

Order for constructor and destructor #

BaseConstructor before DerivedConstructor #
DerivedDestructor before BaseDestructor #