Skip to the page

Object-oriented programming · core

Overloading, overriding and constructor order

Overloading is chosen by the compiler from argument types. Overriding is chosen at runtime from the real object.

The notes

What you must know

  • Overloading: same name, different parameters. The compiler picks the version from the declared types of the arguments (compile-time polymorphism).
  • Overriding: a child gives its own body to a parent method with the same signature. The JVM picks the version from the actual object at runtime (runtime polymorphism).
  • Example: Parent p = new Child(); p.show(5) runs the Child override of show(int); p.show(5.0) runs Parent show(double) because Child did not override it; p.show('A') widens the char to int and runs Child show(int).
  • A char widens to int, the closest match, before it widens to double.
  • Return type alone cannot overload a method.
  • C++ construction order: base constructor first, then derived. Destruction goes in reverse: derived destructor, then base.
  • Deleting a derived object through a base pointer when the base destructor is not virtual is undefined behaviour. Often only the base part is cleaned. Fix: virtual ~Base().
  • Any class used through base pointers needs a virtual destructor.

The red pen

Common traps: mistake → fix

  • Mistake: Overloading is decided at runtime

    Fix: the compiler decides it.

  • Mistake: Derived constructor runs first

    Fix: the base constructor runs first.

  • Mistake: Child overrides every method with the same name

    Fix: only a method with the same signature is overridden.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the difference between overloading and overriding?
  2. What does this code print? (Parent p = new Child(); calls with 5, 5.0 and a char.)
  3. In what order do constructors and destructors run in C++ inheritance?
  4. Why do we need a virtual destructor?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview