Inheritance lets a derived class reuse and extend a base class (an is-a relationship). Exam focus: the five types, C++ public/protected/private derivation and its access table, what is not inherited, the diamond problem and virtual base classes, and Java's extends/implements, super, final and interfaces.
High-yield 65 minSyllabus: “Inheritance”
Mark as
The idea in one minute
A family business: the son inherits the shop, its stock and its customers (the base class's members) and adds an online store of his own (new members). Some things do not pass down — the father's signature (constructors) — and his private diary stays locked even though it is part of the estate (private members). And if a grandchild inherits from two parents who both inherited from the same grandfather, should there be two copies of grandfather's house? C++ answers: one, if you declare the inheritance virtual.
Key points — the night-before list
Inheritance derives a new class from an existing one (is-a): base/parent/superclass → derived/child/subclass. C++ class D : public B; Java class D extends B.
Five types: single, multilevel, multiple, hierarchical, hybrid (multipath). Java classes allow single, multilevel and hierarchical; multiple only through interfaces.
C++ public derivation keeps public/protected as they are; protected derivation makes both protected; private derivation makes both private. Base private members are never accessible.
Default derivation mode: class D : B is private; struct D : B is public.
Not inherited in C++: constructors, destructor, copy assignment operator, friend functions. A base constructor is invoked from the derived initializer list.
Diamond problem: D gets two copies of A through B and C. Fix with class B : virtual public A — one shared A, constructed by the most-derived class.
Java: every class extends Object; super reaches parent members and constructors; a final class cannot be extended and a final method cannot be overridden.
Static methods and fields are hidden, not overridden. Interfaces (Java 8+) hold abstract, default and static methods plus public static final constants.
01Inheritance: reuse plus extension
Inheritance is the mechanism by which a new class — the derived class (child, subclass) — is built from an existing class — the base class (parent, superclass). The derived class automatically acquires the base class's data members and member functions, may add members of its own, and may redefine (override) inherited behaviour.
The relationship it models is is-a: a savings account is an account, a manager is an employee. A derived object physically contains a complete base-class sub-object plus its own extra members, which is why a derived object can be used wherever a base object is expected.
C++C++ — Savings reuses Account and adds interest (prints: 1040)
#include <iostream>#include <string>
using namespace std;
class Account { // base class
protected:
string owner;
double balance = 0;
public:
Account(string o) : owner(o) {}
void deposit(double a) { balance += a; }
double getBalance() const { return balance; }
};
class Savings : public Account { // derived class: Savings IS-A Account
double rate;
public:
Savings(string o, double r) : Account(o), rate(r) {} // base constructor first
void addInterest() { balance += balance * rate / 100; } // uses a protected member
};
int main() {
Savings s("Anu", 4);
s.deposit(1000); // inherited member function
s.addInterest(); // new member function
cout << s.getBalance() << "\n";
}
JavaJava — the same hierarchy (prints: 1040.0)
class Account {
protected String owner;
protected double balance;
Account(String owner) { this.owner = owner; }
void deposit(double a) { balance += a; }
double getBalance() { return balance; }
}
class Savings extends Account {
private final double rate;
Savings(String owner, double rate) {
super(owner); // parent constructor first
this.rate = rate;
}
void addInterest() { balance += balance * rate / 100; }
}
public class Bank {
public static void main(String[] args) {
Savings s = new Savings("Anu", 4);
s.deposit(1000);
s.addInterest();
System.out.println(s.getBalance());
}
}
Reusability — tested base code is used again without copying it.
Extensibility — new features are added in a subclass without touching the base.
Hierarchical classification — Shape → Polygon → Triangle mirrors how we think about the domain.
Polymorphism — a base pointer or reference can refer to any derived object (next topic).
02Types of inheritance
Type
Shape
Example
C++
Java classes
Single
A → B
Person → Student
Yes
Yes
Multilevel
A → B → C
Person → Employee → Manager
Yes
Yes
Multiple
A, B → C
Teacher + Researcher → Professor
Yes
No — only through interfaces
Hierarchical
A → B, A → C, A → D
Shape → Circle, Square, Triangle
Yes
Yes
Hybrid (multipath)
A mix, e.g. A → B, A → C, then B + C → D
Person → Student, Employee → TeachingAssistant
Yes (with virtual base classes)
Only through interfaces
C++The five shapes in C++ syntax
class A { };
class B : public A { }; // single
class C : public B { }; // multilevel (A -> B -> C)
class D { };
class E : public A, public D { }; // multiple (A, D -> E)
class F : public A { }; // hierarchical (A -> B, A -> F)
class G : public B, public F { }; // hybrid: B and F both come from A
JavaJava: one superclass, but any number of interfaces
class A { }
class B extends A { } // single
class C extends B { } // multilevel
class F extends A { } // hierarchical
interface Printable { void print(); }
interface Storable { void save(); }
class Report extends A implements Printable, Storable { // multiple inheritance of TYPE
public void print() { }
public void save() { }
}
// class X extends B, F { } // compile error: a class extends only one class
PSC favourite
Multipath inheritance is Balagurusamy's name for a class inheriting the same grandparent along two paths — the diamond. Hybrid inheritance is any combination of two or more types. Java supports multiple and hybrid inheritance only through interfaces.
Interactive · Inheritance & dispatch explorer Full page
Loading interactive tool…
03Visibility modes in C++: public, protected and private derivation
In C++ the keyword in class D : public B is the derivation (visibility) mode. It sets the highest visibility that inherited members may have inside the derived class. Base private members are a special case: they are inherited — they occupy space in every derived object and base member functions still use them — but code in the derived class can never name them.
Base-class member
public derivation
protected derivation
private derivation
public
public
protected
private
protected
protected
protected
private
private
not accessible
not accessible
not accessible
How base members appear in the derived class
C++Each marked line was checked with a compiler
class A {
private: int pri = 1;
protected: int pro = 2;
public: int pub = 3;
};
class PubD : public A { // public stays public, protected stays protected
public:
void f() {
// pri = 0; // (1) error: private members of A are never accessible
pro = 0; // (2) OK
pub = 0; // (3) OK
}
};
class ProD : protected A { // public and protected both become protected
public:
void f() { pro = 0; pub = 0; } // OK inside the class
};
class PriD : private A { // everything inherited becomes private
public:
void f() { pro = 0; pub = 0; } // OK inside the class
};
class GrandChild : public PriD {
public:
void g() {
// pub = 0; // (4) error: pub is private in PriD
}
};
int main() {
PubD d1; d1.pub = 5; // (5) OK: still public
ProD d2; // d2.pub = 5; // (6) error: pub is protected in ProD
PriD d3; // d3.pub = 5; // (7) error: pub is private in PriD
}
Defaults matter: class D : B means private derivation, struct D : B means public. Public derivation is the normal choice for is-a. Private derivation means 'implemented in terms of' — reusing code without exposing the base's interface — and composition usually does that job more clearly. Protected derivation is rare. A hidden member can be re-exposed with a using-declaration, e.g. public: using A::pub; inside PriD.
Tip
Mnemonic: the mode is a ceiling. Inherited members can never be more visible than the mode — and base private members sit behind a locked door whatever the mode.
04Constructors, destructors and what is not inherited
Constructors — a derived class has its own; it calls a base constructor rather than inheriting it (C++11 can opt in with using Base::Base;).
Destructor — each class has its own; the derived destructor automatically calls the base destructor afterwards.
Copy assignment operator — the derived class's implicitly declared one hides the base's (and calls it internally).
Friend functions — friendship is never inherited.
A base constructor is chosen in the derived class's member initializer list: Rect(int w, int h) : Shape("rect"), w(w), h(h) {}. If the list does not mention the base, its default constructor is used — and if the base has none, the derived constructor does not compile. Construction runs base → members → derived body; destruction runs exactly backwards.
C++Arguments flowing up a multilevel hierarchy (prints: Shape(rect) / Rect 4x4 / Square area 16)
#include <iostream>#include <string>
using namespace std;
class Shape {
protected:
string name;
public:
Shape(string n) : name(n) { cout << "Shape(" << n << ")\n"; }
};
class Rect : public Shape {
protected:
int w, h;
public:
Rect(int w, int h) : Shape("rect"), w(w), h(h) { cout << "Rect " << w << "x" << h << "\n"; }
};
class Square : public Rect {
public:
Square(int s) : Rect(s, s) { cout << "Square area " << w * h << "\n"; }
};
int main() { Square sq(4); }
In Java, constructors are likewise not inherited: a subclass constructor starts with super(args) (or the compiler inserts super()). Private fields of the parent exist in the child object but are not accessible by name; static members are inherited and can even be reached through the subclass name.
Name hiding in C++
If a derived class declares a function with the same name as a base function — even with different parameters — every base overload of that name is hidden. With Base::f(int) and Der::f(double), the call d.f(5) runs Der::f(double). Add using Base::f; to the derived class to bring the base overloads back.
05Multiple inheritance, the diamond problem and virtual base classes
With multiple inheritance a class can receive two members with the same name from different bases. The compiler then refuses an unqualified use as ambiguous; the programmer resolves it with the scope resolution operator.
C++Name ambiguity and its resolution (prints: scanning / printing)
#include <iostream>
using namespace std;
class Printer { public: void start() { cout << "printing\n"; } };
class Scanner { public: void start() { cout << "scanning\n"; } };
class Copier : public Printer, public Scanner { };
int main() {
Copier c;
// c.start(); // error: member 'start' found in multiple base classes
c.Scanner::start(); // OK
c.Printer::start(); // OK
}
The diamond problem is the worse case. Student and Employee both derive from Person, and TA derives from both. A TA object then contains two Person sub-objects — two id fields — so t.id = 7; is ambiguous, the object is larger than it should be, and even converting a TA* to a Person* is ambiguous.
The cure is a virtual base class: write class Student : virtual public Person and class Employee : virtual public Person. Every class that names Person as a virtual base then shares one Person sub-object. Because that shared part belongs to no single path, the most-derived class (TA) constructs it directly, and virtual bases are built before all non-virtual bases. Any Person(...) initialisers written in Student or Employee are ignored when a TA is created.
C++One shared Person (prints: Person(99) / Student / Employee / TA / 7 7 7)
#include <iostream>
using namespace std;
class Person {
public:
int id;
Person(int i = 0) : id(i) { cout << "Person(" << i << ")\n"; }
};
class Student : virtual public Person {
public:
Student() : Person(1) { cout << "Student\n"; } // ignored when building a TA
};
class Employee : virtual public Person {
public:
Employee() : Person(2) { cout << "Employee\n"; } // ignored when building a TA
};
class TA : public Student, public Employee {
public:
TA() : Person(99) { cout << "TA\n"; } // the most-derived class builds the virtual base
};
int main() {
TA t;
t.id = 7; // no ambiguity: only one Person inside TA
cout << t.id << " " << t.Student::id << " " << t.Employee::id << "\n";
}
Java side-steps the diamond by allowing only one superclass. Interfaces can still collide since Java 8, when two of them provide the same default method; the implementing class must then override the method, and it may call a particular parent with InterfaceName.super.method().
JavaResolving a default-method conflict
interface Camera { default String start() { return "camera on"; } }
interface Phone { default String start() { return "phone on"; } }
class SmartPhone implements Camera, Phone {
@Override
public String start() { // mandatory: the two defaults conflict
return Camera.super.start() + ", " + Phone.super.start();
}
}
// new SmartPhone().start() returns "camera on, phone on"
06Inheritance in Java: super, overriding vs hiding, final and Object
The keyword super has three uses: super(args) calls a parent constructor (first statement only); super.method() calls the parent's version of an overridden method; super.field reaches a parent field hidden by a child field of the same name.
Javasuper.method() and super.field
class Vehicle {
protected int wheels = 4;
void describe() { System.out.println("Vehicle with " + wheels + " wheels"); }
}
class Bike extends Vehicle {
protected int wheels = 2; // HIDES Vehicle.wheels: a separate field
@Override
void describe() {
super.describe(); // run the parent's version first
System.out.println("Bike with " + wheels + " wheels, parent field " + super.wheels);
}
}
/* new Bike().describe() prints:
Vehicle with 4 wheels
Bike with 2 wheels, parent field 4 */
Only instance methods are overridden and dispatched on the object's run-time type. A static method with the same signature in a subclass merely hides the parent's — the call is chosen from the reference type at compile time. Fields are never polymorphic either: a same-named field hides the parent's, and the reference type decides which one is read.
JavaOverriding vs hiding
class P {
static String s() { return "P.s"; }
String i() { return "P.i"; }
String name = "P";
}
class C extends P {
static String s() { return "C.s"; } // hides P.s()
@Override String i() { return "C.i"; } // overrides P.i()
String name = "C"; // hides P.name
}
// P r = new C();// r.s() -> "P.s" static: chosen by the reference type P// r.i() -> "C.i" instance: chosen by the object's type C// r.name -> "P" fields are not polymorphic
final closes the hierarchy: a final class cannot be extended (String, Integer and the other wrappers, Math, System), and a final method cannot be overridden. Every class without an extends clause implicitly extends java.lang.Object, so every object has toString(), equals(Object), hashCode(), getClass(), clone() (protected), finalize() (deprecated) and the thread methods wait(), notify() and notifyAll().
Point
Abstract class
Interface
Declared with
abstract class X
interface X
How many per class
A class extends only one
A class implements any number; an interface may extend many
Methods
Abstract and concrete
Abstract, plus default and static (Java 8) and private (Java 9)
Fields
Any: instance or static, final or not
Only public static final constants
Constructors
Yes (run through super from subclasses)
No
Method access
Any modifier
Implicitly public (except private helpers)
Instantiation
Not allowed
Not allowed
Use when
Related classes share code and state
Unrelated classes share a capability (Comparable, Runnable)
Abstract class vs interface (Java)
07is-a or has-a: inheritance vs composition
Composition builds a class by containing objects of other classes as members: a Car has an Engine. In UML, a filled diamond marks composition (the parts live and die with the whole — a House and its Rooms) and a hollow diamond marks aggregation (the parts can exist independently — a Department and its Professors). A hollow-triangle arrow marks inheritance (generalisation).
Use inheritance only for a genuine is-a, where a subclass object can stand in anywhere the base is expected without surprising its users (the Liskov Substitution Principle). Otherwise prefer composition — the Gang of Four's advice is 'favour object composition over class inheritance'. Java's own library shows why: java.util.Stack extends Vector, so any stack also offers add(index, x) and get(i), which break the LIFO rule.
JavaA has-a stack exposes only what a stack should do
import java.util.ArrayDeque;
import java.util.Deque;
class SafeStack<E> { // has-a: the deque is a private part
private final Deque<E> items = new ArrayDeque<>();
void push(E e) { items.push(e); }
E pop() { return items.pop(); }
boolean isEmpty() { return items.isEmpty(); }
// no add(index, e) and no get(i): callers cannot break LIFO
}
Inheritance (is-a)
The subclass is a kind of the base
Reuse by extending; the whole base interface is exposed
Fixed at compile time
Tight coupling — base changes ripple downwards
Example: Savings is an Account
Composition (has-a)
An object contains another as a part
Reuse by delegation; only chosen operations are exposed
Parts can be swapped at run time
Loose coupling
Example: Car has an Engine
Tip
Explore base and derived members, and which version of a method a derived object reaches, in the Inheritance & dispatch explorer on this page.
Worked examples
Try the problem first, then reveal the working one step at a time.
EX 1Applying the access table through two levels
class A { private: int a; protected: int b; public: int c; };, class B : protected A { … };, class C : public B { … };. Which of these are legal: (1) a inside B, (2) b inside B, (3) c inside B, (4) b and c inside C, (5) obj.c and obj.b in main for B obj;?
EX 2The diamond with and without virtual
Person has int id; Student and Employee derive from Person; TA derives from both. What happens to t.id = 7; with ordinary inheritance? With virtual public Person in Student and Employee, and constructors as in Section 5 (TA calls Person(99), Student calls Person(1), Employee calls Person(2)), what is printed?
EX 3Java: which method, which field?
With classes P and C from Section 6 (static s(), instance i() and field name in both), predict P r = new C(); System.out.println(r.s() + " " + r.i() + " " + r.name);.
EX 4Inheritance or composition?
Choose and justify for each pair: (a) Manager–Employee, (b) Car–Engine, (c) Stack–Vector, (d) Square–Rectangle in a program where rectangles have setWidth() and setHeight().
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
Name the type of inheritance: (i) Shape → Circle, Shape → Square, Shape → Triangle; (ii) Vehicle → Car → SportsCar; (iii) Professor derived from both Teacher and Researcher; (iv) Account → Savings; (v) Person → Student, Person → Employee, and TA derived from Student and Employee.
Q2
class Base { public: int x; protected: int y; private: int z; }; and class D : private Base { };. What is the access of x, y, z inside D, and can a class E : public D use x?
Q3
Why does Java not allow a class to extend two classes, and how does it resolve two interfaces that both provide a default method void log()?
Q4
Using the virtual Person / Student / Employee / TA classes, but with TA() { cout << "TA\n"; } (TA no longer calls any Person constructor), what is printed by TA t; cout << t.id;?
Q5
Predict the output and explain: class Base { public: void f(int) { cout << "Base::f(int)"; } }; class Der : public Base { public: void f(double) { cout << "Der::f(double)"; } }; then Der d; d.f(5);
Exam traps
Private base members are inherited (they occupy space in the derived object) — they are just not accessible to derived-class code. Balagurusamy words it as 'private members are not inherited'; both mean derived code cannot use them.
class D : B defaults to private inheritance (and struct D : B to public) — a common source of 'inaccessible base' errors.
'Java has no multiple inheritance' refers to classes only; a class can implement many interfaces, and interfaces can extend several interfaces.
Static methods and fields are hidden, not overridden — resolved by the reference type. Only instance methods take part in dynamic dispatch.
In a virtual-base diamond the most-derived class constructs the virtual base; initialisers for it in intermediate classes are ignored.
In C++ a derived function with the same name hides every base overload of that name — overloading does not work across class scopes without using Base::name;.
Quiz — KPSC style
12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Inheritance · Question 1 of 12✓ 0 · ✗ 0
Which keyword does a Java class use to inherit from another class?
Past-paper questions on this topic
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.
Past papers · Question 1 of 20✓ 0 · ✗ 0
Modelled on QP 050/2026 · Deputy Manager (IT) / Assistant Programmer / Computer Programmer etc (20 May 2026), Q.49 (reworded)original paper (PDF)
A Java class may extend only one class but can implement any number of interfaces. Which kind of multiple inheritance does Java therefore support?