Using the Shape / Circle program of Section 4 (name() non-virtual, draw() virtual, render(Shape s) by value), predict the five lines printed by p->name(); p->draw(); r.draw(); render(c); c.name(); where Shape* p = &c; Shape& r = c;.
Polymorphism lets one name or interface take many forms. Compile-time polymorphism (function and operator overloading) is resolved by the compiler; run-time polymorphism (virtual functions in C++, overriding in Java) is resolved through the vtable from the object's actual type.
:: . .* ?: sizeof typeid. = () [] -> must be members; stream << and >> must be non-members (usually friends).++ takes a dummy int: T operator++(int).virtual void f() = 0; makes the class abstract — no objects. C++11 override checks overriding; final blocks further overriding or derivation.Polymorphism (Greek poly = many, morph = form) is the ability of one name — a function name, an operator, a base-class pointer — to stand for different behaviours. Its practical value is that client code can be written once against a general interface and keep working as new types are added.
| Compile-time polymorphism | Run-time polymorphism | |
|---|---|---|
| Also called | Static / early binding | Dynamic / late binding |
| Mechanisms | Function overloading, operator overloading, templates | Virtual functions (C++), method overriding (Java) |
| Decided from | The declared types of the arguments | The actual type of the object |
| Decided when | During compilation | During execution (vtable lookup) |
| Cost | None; calls can be inlined | One indirect call per invocation |
| Flexibility | Fixed set of versions known to the compiler | Subclasses written later work with old code |
Computer scientists also name three flavours: ad hoc polymorphism (overloading — unrelated versions that share a name), parametric polymorphism (templates and generics — one body for many types) and subtype polymorphism (inheritance plus overriding). Exams mostly use the compile-time / run-time split.
Function overloading means several functions in the same scope share a name but differ in their parameter lists — the number, types or order of parameters. The return type is not part of the decision: int f(int) and double f(int) cannot coexist. For member functions, a const and a non-const version may coexist (get() and get() const).
... parameter matches anything, as a last resort.#include <iostream>
using namespace std;
void show(int x) { cout << "int " << x << "\n"; }
void show(double x) { cout << "double " << x << "\n"; }
void show(const char* s) { cout << "text " << s << "\n"; }
int main() {
show(5); // exact match -> int 5
show(5.5); // exact match -> double 5.5
show('A'); // promotion char -> int -> int 65
show(5.5f); // promotion float -> double -> double 5.5
show("hi"); // exact match (array -> pointer) -> text hi
// show(5L); // long -> int and long -> double are both conversions: ambiguous
}void f(int) {}
void f(float) {}
void g(long) {}
void g(double) {}
void h(int a, int b = 0) {}
void h(int a) {}
int main() {
f(3.14); // 3.14 is a DOUBLE: double->int and double->float are both conversions
g(10); // int->long and int->double are both standard conversions
h(5); // both h's accept one argument because of the default argument
}Java resolves overloads in three phases: first without boxing or varargs (primitive widening allowed), then with boxing/unboxing, and only then with varargs. So widening beats boxing, and boxing beats varargs.
public class Pick {
static void m(long x) { System.out.println("long"); }
static void m(Integer x) { System.out.println("Integer"); }
static void m(int... x) { System.out.println("varargs"); }
static void n(double x) { System.out.println("double"); }
static void n(Object x) { System.out.println("Object"); }
public static void main(String[] args) {
m(5); // int -> long widening wins over boxing to Integer
m(5, 6); // only the varargs version accepts two ints
n(5); // int -> double widening (phase 1)
n("five"); // a String is an Object
char c = 'A';
n(c); // char widens to double before any boxing is tried
}
}Operator overloading gives an existing operator a meaning for user-defined types, so a + b can add two Complex numbers. An overloaded operator is simply a function named operator+, operator<< and so on; the compiler rewrites a + b as a.operator+(b) (member) or operator+(a, b) (non-member).
@ or a power operator.int + int cannot be redefined.&& and || lose short-circuit evaluation (both operands are always evaluated).| Operators | Rule |
|---|---|
:: . .* ?: sizeof typeid | Cannot be overloaded at all |
= () [] -> and conversion operators | Must be non-static member functions |
<< >> used with streams | Must be non-members (usually friends): the left operand is a stream |
Arithmetic, relational, compound assignment, ++, --, !, ,, new, delete | May be either member or non-member |
| Operator kind | As a member function | As a friend (non-member) |
|---|---|---|
| Unary: -a, ++a | 0 explicit arguments — the operand is *this | 1 argument |
| Binary: a + b | 1 explicit argument — the left operand is *this | 2 arguments |
| Left operand | Must be an object of the class | Any type; conversions apply to both sides |
#include <iostream>
using namespace std;
class Complex {
double re, im;
public:
Complex(double r = 0, double i = 0) : re(r), im(i) {}
Complex operator+(const Complex& b) const { // member: left operand is *this
return Complex(re + b.re, im + b.im);
}
friend Complex operator-(const Complex& a, const Complex& b); // friend: two arguments
friend ostream& operator<<(ostream& out, const Complex& c); // must be a non-member
Complex& operator++() { // prefix ++c: change, then return the object itself
++re;
return *this;
}
Complex operator++(int) { // postfix c++: dummy int; return the OLD value
Complex old = *this;
++re;
return old;
}
};
Complex operator-(const Complex& a, const Complex& b) {
return Complex(a.re - b.re, a.im - b.im);
}
ostream& operator<<(ostream& out, const Complex& c) {
out << c.re << (c.im < 0 ? " - " : " + ") << (c.im < 0 ? -c.im : c.im) << "i";
return out; // returning the stream allows cout << a << b
}
int main() {
Complex a(2, 3), b(1, -1);
cout << a + b << " | " << a - b << "\n"; // 3 + 2i | 1 + 4i
Complex c(5, 0);
Complex x = c++; // x gets the old value 5, c becomes 6
Complex y = ++c; // c becomes 7, y gets 7
cout << x << " | " << y << " | " << c << "\n"; // 5 + 0i | 7 + 0i | 7 + 0i
Complex z = a + 10; // 10 -> Complex(10) through the constructor
// Complex w = 10 + a; // error: member operator+ needs a Complex on the left
Complex w = 10 - a; // fine: the friend converts either operand
cout << z << " | " << w << "\n"; // 12 + 3i | 8 - 3i
}Two design points stand out. operator<< returns ostream& so that output can be chained, and it cannot be a member of Complex because its left operand is cout. A symmetric operator such as - written as a friend accepts a conversion on either side (10 - a), while the member operator+ accepts one only on the right (a + 10 works, 10 + a does not).
+ for String concatenation (and +=).A base-class pointer or reference may refer to a derived object (an implicit, safe upcast). When a member function is called through it, C++ normally binds the call from the pointer's declared type — early binding. Declaring the function virtual in the base class switches to late binding: the version is chosen from the object's actual type at run time.
#include <iostream>
using namespace std;
class Shape {
public:
void name() { cout << "Shape::name\n"; } // non-virtual: early binding
virtual void draw() { cout << "Shape::draw\n"; } // virtual: late binding
virtual ~Shape() {}
};
class Circle : public Shape {
public:
void name() { cout << "Circle::name\n"; } // hides Shape::name
void draw() override { cout << "Circle::draw\n"; } // overrides Shape::draw
};
void render(Shape s) { s.draw(); } // by value: the Circle part is sliced off
int main() {
Circle c;
Shape* p = &c;
Shape& r = c;
p->name(); // Shape::name (the pointer type decides)
p->draw(); // Circle::draw (the object type decides)
r.draw(); // Circle::draw
render(c); // Shape::draw (object slicing)
c.name(); // Circle::name
}Circle* for Shape* is allowed); otherwise it is a new function that hides the base one.During construction an object is only as derived as the constructor currently running. So a virtual call inside a base constructor runs the base version in C++ — in the program Base() { hello(); }, creating a Derived prints Base::hello. Java behaves differently (Section 7).
virtual keyword independently and watch which version runs.Compilers implement virtual functions with a virtual table (vtable) — one static array of function pointers per polymorphic class, one slot per virtual function. Every object of such a class carries a hidden virtual pointer (vptr), set by the constructor, that points to its class's vtable. Non-virtual functions never appear in the vtable.
| Slot | Shape's vtable | Circle's vtable |
|---|---|---|
| 0 — draw() | &Shape::draw | &Circle::draw (overridden) |
| 1 — destructor | &Shape::~Shape | &Circle::~Circle |
#include <iostream>
struct Plain { int x; void f() {} };
struct Poly { int x; virtual void f() {} };
int main() {
std::cout << sizeof(Plain) << " " << sizeof(Poly) << " " << sizeof(void*) << "\n";
}
// Poly = 8-byte vptr + 4-byte int + 4 bytes of padding = 16The costs are modest but real: one vptr per object, one vtable per class (however many objects exist), and an indirect call that the compiler usually cannot inline. Adding more virtual functions grows the vtable, not the objects. The vtable is an implementation technique, not part of the C++ standard, but every major compiler uses it. The JVM does the same for Java's invokevirtual calls, and its JIT compiler removes the indirection when only one implementation is loaded.
A pure virtual function is declared with = 0 and has no required body: virtual double area() const = 0;. A class with at least one pure virtual function is an abstract class — you cannot create its objects, but you can declare pointers and references to it, and it may still have data members, constructors and ordinary functions. A derived class that does not override every pure virtual function is abstract as well.
#include <iostream>
using namespace std;
class Shape { // abstract class
public:
virtual double area() const = 0; // pure virtual function
virtual ~Shape() = default;
};
class Rect : public Shape {
double w, h;
public:
Rect(double w, double h) : w(w), h(h) {}
double area() const override { return w * h; }
};
class Circle final : public Shape { // final: no class may derive from Circle
double r;
public:
Circle(double r) : r(r) {}
double area() const override { return 3.14159 * r * r; }
};
int main() {
// Shape s; // error: 'Shape' is an abstract class
Shape* shapes[] = { new Rect(3, 4), new Circle(1) };
double total = 0;
for (Shape* s : shapes) {
cout << s->area() << "\n"; // dynamic dispatch through the vtable
total += s->area();
}
cout << "total " << total << "\n";
for (Shape* s : shapes) delete s; // virtual destructor: correct clean-up
}C++11 added two safety keywords. override after a member function asks the compiler to confirm it really overrides a base virtual — a forgotten const or a mistyped parameter becomes a compile error instead of a silent new function. final on a virtual function forbids further overriding; on a class it forbids deriving from it.
class Base { public: virtual void show() const {} virtual ~Base() {} };
class Der : public Base {
public:
void show() override {} // error: 'const' is missing, so this does not override
};Object slicing happens when a derived object is copied into a base-class object — by value parameter, by assignment Shape s = c;, or when stored in a vector<Shape>. Only the base part is copied, and the copy's vptr points to the base vtable, so virtual calls on it run base versions. Use pointers, references or smart pointers to keep polymorphic behaviour.
In Java every instance method that is not static, final or private is virtual automatically. Dynamic method dispatch is the JVM mechanism that, for a call through a superclass reference, selects the overriding method of the object's run-time class.
abstract class Shape {
abstract double area();
public String toString() { return getClass().getSimpleName() + " " + area(); }
}
class Circle extends Shape {
private final double r;
Circle(double r) { this.r = r; }
@Override double area() { return Math.PI * r * r; }
}
class Rect extends Shape {
private final double w, h;
Rect(double w, double h) { this.w = w; this.h = h; }
@Override double area() { return w * h; }
}
public class Dispatch {
public static void main(String[] args) {
Shape[] shapes = { new Rect(3, 4), new Circle(1) };
for (Shape s : shapes)
System.out.println(s); // area() is chosen at run time for each object
}
}| Point | Overloading | Overriding |
|---|---|---|
| Where | Within a class (including inherited methods) | A subclass redefines a superclass method |
| Parameter list | Must differ | Must be identical |
| Return type | May differ freely | Same, or a subtype (covariant return, Java 5+) |
| Access modifier | Any | Same or wider — never narrower |
| Checked exceptions | Any | No new or broader checked exceptions |
| static / private / final methods | Can be overloaded | Cannot be overridden (a static one is hidden) |
| Resolved | At compile time | At run time — dynamic method dispatch |
The @Override annotation asks the compiler to verify that a method really overrides something. Its classic catch is public boolean equals(Point p), which overloads rather than overrides Object.equals(Object) — with @Override it fails to compile instead of being silently ignored by collections.
class Base {
Base() { show(); } // calls the OVERRIDDEN version
void show() { System.out.println("Base.show"); }
}
class Derived extends Base {
private int value = 42;
@Override void show() { System.out.println("Derived.show, value = " + value); }
}
// new Derived() prints: Derived.show, value = 0
// value is still 0 because Derived's field initialisers run only after Base() returns.Try the problem first, then reveal the working one step at a time.
Using the Shape / Circle program of Section 4 (name() non-virtual, draw() virtual, render(Shape s) by value), predict the five lines printed by p->name(); p->draw(); r.draw(); render(c); c.name(); where Shape* p = &c; Shape& r = c;.
With show(int), show(double) and show(const char*), classify the calls show(5), show(5.5), show('A'), show(5.5f), show("hi") and show(5L). Separately, with f(int) and f(float), what happens to f(3.14)?
class A { void show(A a) { System.out.println("A.show(A)"); } } and class B extends A { @Override void show(A a) { System.out.println("B.show(A)"); } void show(B b) { System.out.println("B.show(B)"); } }. With A x = new B(); B y = new B();, predict x.show(y); y.show(y); y.show(x);.
With the Complex class of Section 3 and Complex a(2, 3), b(1, -1), c(5, 0);, evaluate a + b, a - b, Complex x = c++;, Complex y = ++c;, a + 10 and 10 - a.
From +, [], ::, ->, ?:, sizeof, <<, . and (), list the operators that cannot be overloaded, and those that can be overloaded only as member functions.
Write the prototypes for class Money of: (a) binary minus as a member, (b) binary minus as a friend, (c) unary minus as a member, (d) prefix and postfix -- as members.
On a typical 64-bit compiler, give sizeof for: N { int i; char c; }, A { int i; char c; virtual void f(); }, B — like A but with two virtual functions — and C : B adding one more virtual function.
Predict the output: class A { int x = 10; int get() { return x; } } class B extends A { int x = 20; @Override int get() { return x; } } and A a = new B(); System.out.println(a.x + " " + a.get() + " " + ((B) a).x);
Base has protected Number value() throws IOException. Which subclass versions compile? (a) public Integer value() (b) private Number value() (c) protected Number value() throws Exception (d) protected Object value() (e) protected Number value() throws FileNotFoundException (f) protected Number value() throws RuntimeException
int f(int) and double f(int) clash in both C++ and Java.B* p = new D; p->f(); runs D's body with B's default argument.private methods are not overridden — a same-signature method in a subclass is a brand-new method. equals(Point) overloads, not overrides, equals(Object).12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.