Classes, Objects, Constructors and Inheritance
Classes, Objects, Constructors and Inheritance
This section tests object lifecycle and the order in which constructors and destructors run.
Constructors and destructors
- A constructor has the same name as the class, no return type, and runs automatically when an object is created.
- Types: default (no arguments), parameterised, and copy constructor (
ClassName(const ClassName &)). - If you declare any constructor, the compiler no longer supplies a default one.
- A destructor is
~ClassName(), takes no arguments, and runs when the object's lifetime ends. - Constructors cannot be virtual; destructors in a polymorphic base should be virtual.
Inheritance
- Forms: single, multiple, multilevel, hierarchical, hybrid.
- Access modes
public,protected,privatechange how base members appear in the derived class. - Construction order: base constructor first, then derived; destruction reverses this.
- A derived constructor can pass arguments to the base using an initialiser list.
Worked example
class A { public: A(){ cout << 'A'; } ~A(){ cout << 'a'; } }; class B : public A { public: B(){ cout << 'B'; } ~B(){ cout << 'b'; } }; Creating and destroying one B object prints ABba. Reasoning: base is constructed before derived, and destruction is reverse - derived destroyed first, then base.
Traps
- Giving a constructor a return type.
- Assuming a parameterised constructor still provides a zero-argument default.
- Reversing constructor/destructor order.
- Thinking private base members become accessible under public inheritance; they remain inaccessible directly.
- Forgetting the
virtualdestructor when deleting derived objects through a base pointer.