Using the Vehicle / Engine / Car program (Car publicly inherits Vehicle and has an Engine member; every constructor and destructor prints its name), write the output of int main() { Car c; cout << "-- using car"; } and justify the order.
Constructors initialise an object the moment it is created; destructors clean up the moment it dies. Exams test the kinds (default, parameterized, copy), initializer lists, explicit, call order in inheritance, virtual destructors and Java's this()/super() chaining.
X(const X&) runs on initialisation from another object, pass by value and return by value (often elided). The parameter must be a reference.: a(x), b(y) is mandatory for const members, reference members, members without a default constructor and base classes needing arguments.~X(): no arguments, no return type, cannot be overloaded (one per class); objects die in reverse order of construction.this(...)/super(...) must be the first statement; super() is inserted if absent. No destructors — GC plus try-with-resources (AutoCloseable.close()).A freshly declared C variable holds garbage until you assign it. With objects that is dangerous: an Account whose balance is random, or a Stack whose top is not −1, is broken from birth. Asking every user to call init() first does not work — someone always forgets.
A constructor solves this. It is a special member function with the same name as its class, invoked automatically whenever an object of the class is created. Its job is to put the new object into a valid state: initialise data members, check arguments and acquire resources such as memory or files.
class Flat {
int number;
double area;
public:
Flat() { number = 0; area = 0; } // no return type, same name as the class
};
Flat f; // the constructor has already run: f.number == 0, f.area == 0void.virtual, static or const, and its address cannot be taken.void Flat() { } compiles — but it is an ordinary method that happens to share the class name, not a constructor, so new Flat() never runs it. In C++ the same line is a compile error.A default constructor can be called with no arguments: either it has no parameters, or every parameter has a default value. If a class declares no constructor at all, the compiler supplies an implicit default constructor (which leaves built-in members of automatic objects uninitialised). The moment you write any constructor, that implicit one disappears — Flat f; then fails unless you also write Flat() (or Flat() = default; in C++11).
A parameterized constructor takes arguments so that each object can start with different values. It can be called implicitly (Flat b(101, 650.5);), explicitly (Flat b = Flat(101, 650.5);) or with braces (Flat b{101, 650.5};). Several constructors with different parameter lists form constructor overloading.
#include <iostream>
using namespace std;
class Flat {
int number;
double area;
public:
Flat() : number(0), area(0) { cout << "default\n"; } // default
Flat(int n, double a) : number(n), area(a) { cout << "two-arg\n"; } // parameterized
Flat(int n) : Flat(n, 500) { cout << "one-arg\n"; } // delegates first
void show() const { cout << number << " " << area << "\n"; }
};
int main() {
Flat a; // default
Flat b(101, 650.5); // two-arg
Flat c = Flat(102); // two-arg, then one-arg
a.show(); b.show(); c.show();
}
/* Output: default / two-arg / two-arg / one-arg / 0 0 / 101 650.5 / 102 500 */Default arguments let one constructor cover several cases: Flat(int n = 0, double a = 500) can be called as Flat(), Flat(7) or Flat(7, 600) — so it is also a default constructor. Declaring both Flat() and Flat(int n = 0) makes Flat f; ambiguous, and the compiler refuses it.
Balagurusamy also names the dynamic constructor — one that allocates memory with new while constructing (for example a String class that allocates exactly as many characters as needed). It is covered in Classes & dynamic memory allocation.
| Kind | Signature | Invoked by | Remember |
|---|---|---|---|
| Default | X() | X obj; new X; X arr[5]; | Implicit one exists only if no constructor is declared |
| Parameterized | X(int, double) | X obj(1, 2.5); X obj = X(1, 2.5); | Different starting values per object |
| Default arguments | X(int a = 0, int b = 0) | X(); X(5); X(5, 6); | Doubles as the default constructor |
| Copy | X(const X&) | X b = a; X b(a); pass / return by value | Compiler's version copies member by member |
| Converting | X(int) without explicit | X obj = 5; f(5) for f(X) | Silent conversion; block it with explicit |
| Move (C++11) | X(X&&) | X b = std::move(a); | Steals resources instead of copying them |
A copy constructor initialises a new object from an existing object of the same class. Its standard form is X(const X& other). The parameter must be a reference: if it were passed by value, calling the copy constructor would first require copying the argument — which calls the copy constructor — forever. Compilers reject X(X other) outright. const lets you copy const objects and temporaries and promises the source is not modified.
X b = a;, X b(a); or X b{a};.vector::push_back(a).#include <iostream>
using namespace std;
class Box {
int w;
public:
Box(int x = 0) : w(x) { cout << "ctor(" << w << ") "; }
Box(const Box& o) : w(o.w) { cout << "copy(" << w << ") "; }
Box& operator=(const Box& o) { w = o.w; cout << "assign(" << w << ") "; return *this; }
~Box() { cout << "dtor(" << w << ") "; }
};
void byValue(Box b) { cout << "in-byValue "; }
void byRef(const Box& b) { cout << "in-byRef "; }
int main() {
Box a(5); // ctor(5)
Box b = a; // copy(5) initialisation, NOT assignment
Box c; // ctor(0)
c = a; // assign(5) c already exists
byValue(a); // copy(5) in-byValue dtor(5)
byRef(a); // in-byRef no copy at all
cout << "\nend\n";
} // dtor(5) dtor(5) dtor(5): c, b, a
/* Output:
ctor(5) copy(5) ctor(0) assign(5) copy(5) in-byValue dtor(5) in-byRef
end
dtor(5) dtor(5) dtor(5) */Box b = a; creates a new object, so it calls the copy constructor even though it contains =. c = a; changes an object that already exists, so it calls the copy assignment operator.return X(5);. So a program may print fewer 'copy' lines than the textbook rule predicts — exam questions normally assume pass by value and explicit initialisation.If you do not write a copy constructor, the compiler generates one that copies member by member. That is correct for int, double and std::string, but disastrous for a raw pointer that owns memory — both objects end up pointing to the same buffer. The fix (deep copy and the Rule of Three) is in the next topic.
A member initializer list follows the constructor's parameter list after a colon: Reading(int i, int& c, double v) : id(i), counter(c), value(v) { … }. Each member is constructed with its value before the body runs. Assigning in the body instead means default-constructing first and assigning afterwards — slower, and impossible for some members.
const int id = 0;).Derived(int x) : Base(x) { … }.#include <iostream>
using namespace std;
class Reading {
const int id; // const member: initialised once, never assigned
int& counter; // reference member: bound when the object is born
double value;
public:
Reading(int i, int& c, double v) : id(i), counter(c), value(v) {
++counter;
}
void show() const { cout << id << " " << value << " " << counter << "\n"; }
};
int main() {
int made = 0;
Reading r1(1, made, 36.6), r2(2, made, 37.1);
r1.show(); // counter is 2: both objects refer to the same 'made'
r2.show();
}
// Writing Reading(int i) { id = i; } instead is rejected:
// "constructor must explicitly initialize the const member 'id'"int a; int b; and P(int x) : b(x), a(b + 1) {}, a is initialised first — from an uninitialised b. Compilers warn with -Wreorder; always write the list in declaration order.A constructor callable with one argument is also a converting constructor: it lets the compiler turn that argument type into your class silently. With Meter(double), both Meter m = 4; and a call printM(2.5) for void printM(Meter) compile. Declaring the constructor explicit forbids such implicit conversions while still allowing SafeMeter(2.5).
#include <iostream>
using namespace std;
class Meter {
double v;
public:
Meter(double x) : v(x) {} // converting constructor
double get() const { return v; }
};
class SafeMeter {
double v;
public:
explicit SafeMeter(double x) : v(x) {} // no silent conversions
double get() const { return v; }
};
void printM(Meter m) { cout << m.get() << "\n"; }
void printS(SafeMeter s) { cout << s.get() << "\n"; }
int main() {
printM(2.5); // OK: 2.5 silently becomes Meter(2.5)
Meter m = 4; // OK
printS(SafeMeter(2.5)); // OK: conversion written explicitly
// printS(2.5); // error: no viable conversion
// SafeMeter s = 4; // error
printM(m);
}A destructor is the special member function that runs automatically when an object's lifetime ends. Its name is the class name preceded by a tilde — ~Flat() — and its job is to release what the object acquired: memory, files, locks, network connections.
delete for heap objects, after main returns for global and static objects, at the end of the full expression for temporaries.virtual (and should be in a polymorphic base class); cannot be static or const.#include <iostream>
using namespace std;
class Tag {
char c;
public:
Tag(char ch) : c(ch) { cout << "+" << c << " "; }
~Tag() { cout << "-" << c << " "; }
};
Tag g('G'); // global: built before main, destroyed after it
int main() {
Tag a('A');
{
Tag b('B');
Tag c('C');
} // -C -B : reverse order at the closing brace
Tag* d = new Tag('D');
delete d; // -D : a heap object dies only at delete
static Tag s('S'); // static local: survives until main returns
cout << "| end of main | ";
} // -A, then statics in reverse order: -S -GBecause destructors run automatically — even when an exception unwinds the stack — C++ programmers tie every resource to an object: the constructor acquires it and the destructor releases it. This idiom is called RAII (Resource Acquisition Is Initialisation), and it is why well-written C++ rarely leaks.
class C : public B, public A builds B, then A.#include <iostream>
using namespace std;
class Engine {
public:
Engine() { cout << "Engine()\n"; }
~Engine() { cout << "~Engine()\n"; }
};
class Vehicle {
public:
Vehicle() { cout << "Vehicle()\n"; }
~Vehicle() { cout << "~Vehicle()\n"; }
};
class Car : public Vehicle {
Engine e; // member object
public:
Car() { cout << "Car()\n"; }
~Car() { cout << "~Car()\n"; }
};
int main() {
Car c;
cout << "-- using car\n";
}
/* Output: Vehicle() / Engine() / Car() / -- using car / ~Car() / ~Engine() / ~Vehicle() */Destruction is the exact mirror: the destructor body of the derived class runs first (it may still need its members and base), then the members are destroyed in reverse declaration order, then the base classes in reverse order.
Virtual destructors. If a base pointer holds a derived object, delete p must run the derived destructor too. With a non-virtual base destructor the behaviour is undefined — in practice only ~Base runs and the derived part leaks. Making the base destructor virtual makes delete dispatch on the object's real type: ~Derived runs, then ~Base.
#include <iostream>
using namespace std;
class Base {
public:
virtual ~Base() { cout << "~Base\n"; }
};
class Derived : public Base {
int* buf;
public:
Derived() : buf(new int[100]) { cout << "Derived acquires buffer\n"; }
~Derived() override { delete[] buf; cout << "~Derived frees buffer\n"; }
};
int main() {
Base* p = new Derived;
delete p; // virtual destructor: ~Derived runs first, then ~Base
}Java constructors follow the same core rules — class name, no return type, overloading allowed, run on new. If a class has no constructor, the compiler adds a default no-argument constructor that simply calls super(); once you write any constructor, it is not added. Java has no default arguments, so overloading does that job.
this(args) calls another constructor of the same class (constructor chaining within a class).super(args) calls a constructor of the parent class.super(); — a compile error if the parent has no no-argument constructor.super(...). Textbooks and exams still state 'first statement'.class A {
A() { System.out.println("A()"); }
A(int x) { this(); System.out.println("A(int) " + x); }
}
class B extends A {
B() { this(5); System.out.println("B()"); }
B(int x) { super(x); System.out.println("B(int) " + x); }
}
public class Main {
public static void main(String[] args) {
new B();
}
}
/* Output:
A()
A(int) 5
B(int) 5
B() */When new runs in Java: memory is allocated and every field gets its default value; the constructor chain climbs through this(...)/super(...) all the way to Object; then, from the top class downwards, each class runs its field initialisers and instance initializer blocks in textual order, followed by the rest of its constructor body. A parent part is therefore complete before the child's body runs.
Java has no destructors. Memory is reclaimed by the garbage collector at a time of its choosing, and the old finalize() hook is deprecated (Java 9) and marked for removal (Java 18). For files, sockets and locks, implement AutoCloseable and use try-with-resources: close() is called automatically — in reverse order of declaration — even if an exception is thrown.
class Meter implements AutoCloseable {
private final String name;
Meter(String name) { this.name = name; System.out.println("open " + name); }
public void close() { System.out.println("close " + name); }
}
public class Main {
public static void main(String[] args) {
try (Meter water = new Meter("water"); Meter power = new Meter("power")) {
System.out.println("reading meters");
} // close() runs automatically, last opened first
}
}
/* Output: open water / open power / reading meters / close power / close water */| Aspect | C++ | Java |
|---|---|---|
| Copy constructor | Generated automatically (member-wise) unless deleted | None built in — write one, or use clone() |
| Calling another constructor | Delegating constructor: X() : X(0) {} | this(...) as the first statement |
| Calling the base constructor | Initializer list: D() : B(5) {} | super(...) as the first statement |
| Default arguments | Allowed | Not allowed — overload instead |
| Clean-up | ~X(), automatic and deterministic | No destructor; GC for memory, close() via try-with-resources |
| Where objects are created | Stack (X a;) or heap (new X) | Heap only (new X()) |
Try the problem first, then reveal the working one step at a time.
Using the Vehicle / Engine / Car program (Car publicly inherits Vehicle and has an Engine member; every constructor and destructor prints its name), write the output of int main() { Car c; cout << "-- using car"; } and justify the order.
For class T with T() { cout << "C"; }, T(const T&) { cout << "K"; } and ~T() { cout << "D"; }, predict the output of void f(T x) {} and int main() { T a; T b = a; f(a); T* p = new T[2]; delete[] p; }.
Predict the output of new B() for the A / B classes in Section 7 (A() and A(int) where A(int) calls this(); B() calls this(5); B(int) calls super(x)).
In the Base / Derived program of Section 6 (Derived allocates new int[100] and frees it in ~Derived), what does Base* p = new Derived; delete p; print with and without virtual on ~Base, and what is the consequence?
Explain why Box(Box b); cannot be a copy constructor, and why the usual parameter is const Box& rather than Box&.
Fix the compile errors without changing the members: class Sensor { const int id; double& reading; public: Sensor(int i, double& r) { id = i; reading = r; } };
Java: why does this fail, and give two different fixes. class A { A(int x) { } } class B extends A { B() { } }
For class C : public B, public A { M m; public: C() : A(), m(), B() { cout << "C "; } }; where A, B and M print their names in their constructors and ~X in their destructors, what does { C obj; } print?
Predict the output: class T { public: T(){cout<<"C";} T(const T&){cout<<"K";} ~T(){cout<<"D";} }; T g(T x) { return x; } int main() { T a; T b = g(a); } — assume a modern compiler, and note where textbook and compiler may differ.
void. In Java, void ClassName() silently becomes an ordinary method that new never calls.X obj; / new X() then fails unless you add one.X b = a; calls the copy constructor, not operator=; b = a; on an existing object calls operator=.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.