Inheritance

Inheritance

Class can inherit from another class. Class can be derived from another class. Example:

class BaseClass{

};

class DerivedClass : public BaseClass{

};

DerivedClass inherits / is derived from a BaseClass. Example:

#include <iostream>
class BaseClass{
public:
	int x;
	void printX(){
		std::cout << x << std::endl;
	}
};

class DerivedClass : public BaseClass{
// everything from a BaseClass is accessible in here
};

int main(){
	DerivedClass o;
	o.x = 123;
	o.printX();
}

Derived class can see the public and protected parts of the BaseClass. The object of the DerivedClass can only access the public parts:

#include <iostream>
class BaseClass{
public:
	int x;
	void printX(){
		std::cout << x << std::endl;
	}
protected:
	int y;
};

class DerivedClass : public BaseClass{
	// everything from a BaseClass is accessible in here	
};

int main(){
	DerivedClass o;
	o.x = 123;
	o.printX();
}

Derived class can implement additional data members and functions. Example:

#include <iostream>
class BaseClass{
public:
	int x;
	void printX(){
		std::cout << x << std::endl;
	}
};

class DerivedClass : public BaseClass{
public:
	int y;
	void printY(){
		std::cout << y << std::endl;
	}
};

int main(){
	DerivedClass o;
	// inherited from a BaseClass
	o.x = 123;
	o.printX();
	// added in a DerivedClass
	o.y = 456;
	o.printY();
}