Interview Q&A · C++ · 10 questions in this topic
Classes, Objects & Constructors — C++ Interview Q&A
How C++ classes are born and die — constructors, destructors, copy/move, member initialization and object lifetime. Part of Classes & OOP Pillars · 213 questions in the C++ bank.
What is a class and an object in C++?
Answer
A class is a user-defined type bundling data members and member functions with access control (private/protected/public). An object is an instance of a class with its own storage and lifetime — automatic (stack), static, thread-local or dynamic (heap).
Unlike Java, C++ objects can live directly on the stack with value semantics — no new required — and are destroyed deterministically when their scope ends.
Example
class Account { public: explicit Account(double b) : balance_(b) {} void deposit(double a) { balance_ += a; } private: double balance_ = 0; }; Account a(100.0); // stack object, value semantics a.deposit(50);
💡 Stress value semantics and deterministic destruction — that is the C++ object model's headline difference from Java/Python.
What are the special member functions (rule of 0/3/5)?
Answer
The six special members are default constructor, destructor, copy constructor, copy assignment, move constructor and move assignment. The rule of 0 says: manage no raw resources — let members handle themselves and declare nothing. The rule of 5 says: if you define any of destructor/copy/move, define (or explicitly delete/default) all five. The rule of 3 is the C++98 predecessor (destructor, copy ctor, copy assign).
Modern code aims for rule of 0 via std::string, containers and smart pointers.
Key points
- 1Rule of 0 — no custom resource management; the default members are correct.
- 2Rule of 5 — custom destructor/copy/move come as a package.
- 3Declaring a destructor suppresses implicit move generation (a classic trap).
Example
class Buffer { public: Buffer() = default; ~Buffer(); Buffer(const Buffer&); // copy ctor Buffer& operator=(const Buffer&); // copy assign Buffer(Buffer&&) noexcept; // move ctor Buffer& operator=(Buffer&&) noexcept; };
Constructor vs destructor — what runs, when, and in what order?
Answer
Constructors initialize an object (bases then members in declaration order, then the ctor body); destructors tear it down in exact reverse (body, members reversed, bases reversed). Members initialize in declaration order regardless of the initializer-list order — mismatching them compiles but may warn and surprises readers.
Destructors of base classes intended for polymorphic deletion must be virtual, or derived parts leak.
Example
struct Base { Base(); virtual ~Base() = default; }; struct Derived : Base { std::string s; Derived() : Base(), s("hi") {} // Base first, then members };
💡 Say forward-construct, reverse-destroy in one sentence — interviewers accept that as the complete ordering rule.
What is a copy constructor and when is it called?
Answer
The copy constructor T(const T&) builds a new object as a copy of an existing one. It runs on pass-by-value, return-by-value (before elision), explicit copies, and throwing/catching exceptions by value.
It must take its parameter by reference — by value would require copying the argument to call it, an infinite regress that the compiler rejects.
Example
class Vec { public: Vec(const Vec& other) : data_(other.data_) {} private: std::vector<int> data_; }; Vec a; Vec b = a; // copy ctor
What is a destructor and what must it never do?
Answer
The destructor (~T()) runs when an object dies — end of scope, delete, container cleanup, stack unwinding. It releases resources owned by the object and must be noexcept: a throwing destructor during unwinding terminates the program (std::terminate).
Base-class destructors are virtual when polymorphic deletion is possible; otherwise derived destructors never run through a base pointer.
Example
class File { public: ~File() noexcept { if (f_) std::fclose(f_); } private: std::FILE* f_ = nullptr; };
💡 The one absolute rule interviewers want: destructors must not throw.
What is a member initializer list and why is it better than assignment in the body?
Answer
The initializer list (after the colon) constructs members directly with their arguments; assignment in the body default-constructs them first and then overwrites — wasted work, and impossible for const members, references and members without default constructors.
It is the only way to initialize those three categories, and it avoids a default-plus-assign double cost for everything else.
Example
class Point { public: Point(int x, int y) : x_(x), y_(y) {} // direct construction private: int x_, y_; };
What is the `this` pointer?
Answer
this is the implicit pointer to the object a non-static member function was called on (type T* in a non-const function, const T* in a const one). It enables method chaining (return *this), disambiguation of shadowed names, and passing the object onward.
Static member functions have no this, which is why they cannot touch non-static members or be const/virtual.
Example
class Counter { public: Counter& inc() { ++n_; return *this; } // chaining via *this private: int n_ = 0; }; Counter c; c.inc().inc();
What is a friend function / friend class? When is it justified?
Answer
friend grants a non-member function or another class access to private/protected members. It is justified for tightly-coupled operations that need internals but should not be members — canonical examples are operator<< / operator>> and symmetric operators.
Friendship is granted (not taken), non-transitive and non-inherited. Overuse breaks encapsulation, so it should be narrow and documented.
Example
class Point { friend std::ostream& operator<<(std::ostream&, const Point&); private: int x_ = 0, y_ = 0; }; std::ostream& operator<<(std::ostream& os, const Point& p) { return os << '(' << p.x_ << ',' << p.y_ << ')'; }
💡 Lead with operator<< — it is the friend example every interviewer expects and accepts.
What is `explicit` for on constructors (and conversion operators)?
Answer
explicit blocks implicit conversions through that constructor — the object can still be built explicitly, but the compiler will not silently convert an argument type into your class. Single-argument constructors are implicit by default, which is how accidental conversions sneak in.
Modern guidance: make single-argument constructors explicit by default and opt out only for genuine value wrappers. C++20 extends explicit to conditionally depend on a boolean (explicit(bool)).
Example
struct String { explicit String(int n); // no silent int -> String }; // String s = 5; // error (good) String s(5); // ok, explicit construction
What is object slicing and how do you prevent it?
Answer
Slicing copies only the base subobject when a derived object is assigned to a base by value — the derived parts are sliced off and virtual dispatch degrades to the base. It happens on pass-by-value, base-typed containers and base-typed assignment.
Prevention: pass/catch by reference or pointer, store polymorphic objects via (smart) pointers, and consider making bases abstract or non-copyable so the mistake cannot compile.
Example
struct Base { virtual void f() const {} }; struct Derived : Base { int extra = 0; }; void g(Base b); // slices any Derived passed in void ok(const Base& b); // no slicing
💡 Name the three slicing sites — by-value parameter, by-value container, by-value catch — for full marks.
Recommended resourcesAffiliate links · may earn us a commission