- 2069 Chaitra · 2+2 marks
Constructors and destructors with syntax
Short answer
A constructor is a special member function that initializes object data members; it has the same name as the class and no return type. A destructor (~ClassName) automatically releases resources. Types: default (no parameters), parameterized (with arguments), copy (from existing object via reference), and dynamic (allocates memory with new).
Define constructor and destructor. Write down different types of constructors with syntax.
A constructor is a special member function that has the same name as its class, has no return type, and is called automatically when an object is created. It initialises the data members of the object. A destructor is a special member function with the class name preceded by a tilde (~). It is called automatically when an object goes out of scope or is deleted, and it releases resources (such as memory) the object holds. A destructor takes no arguments and cannot be overloaded.
Types of constructors
1. Default constructor - takes no arguments (or all arguments have default values).
class Box {
int l, b;
public:
Box() { l = 0; b = 0; } // default constructor
};
Box b1; // calls Box()
2. Parameterized constructor - takes arguments so each object can be initialised with different values.
class Box {
int l, b;
public:
Box(int x, int y) { l = x; b = y; } // parameterized
};
Box b2(4, 5); // implicit call
Box b3 = Box(6, 7); // explicit call
3. Copy constructor - creates a new object as a copy of an existing object of the same class. The argument must be passed by reference.
class Box {
int l, b;
public:
Box(const Box &o) { l = o.l; b = o.b; } // copy constructor
};
Box b4(b2); // or Box b4 = b2;
4. Constructor with default arguments (variant of the above): Box(int x = 1, int y = 1);
5. Dynamic constructor - allocates memory with new inside the constructor.
Syntax of the destructor:
~Box() { /* clean-up code, e.g. delete[] p; */ }
General syntax: ClassName(parameter_list) { body } for constructors and ~ClassName() { body } for the destructor.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Constructor and destructor order, multilevel inheritance · Object Oriented Programming, chapter 6 · asked 2×
- Constructor/destructor order; parameterized base constructor · Object Oriented Programming, chapter 6 · asked 2×
- Department class constructor and destructor · Object Oriented Programming, chapter 4
- Constructors: need and types · Object Oriented Programming, chapter 4 · asked 2×
- Syntax of operator overloading · Object Oriented Programming, chapter 5 · asked 4×
- Class and function template with syntax · Object Oriented Programming, chapter 9 · asked 4×