Table of Contents
ToggleConstructors and Destructors
A constructor is a special member function of a class that has the same name as the class itself. It is automatically called by the compiler whenever an object of the class is created. The constructor allocates memory for the object and initializes the class data members either with default values or with the values provided by the user during object creation. Constructors do not have any return type because their main purpose is to create and initialize an object.
.Basic Syntax of a Constructor
class class_name
{
private:
// Private data members
public:
// Declaring constructor
class_name(parameters)
{
// Constructor body
}
};Explanation:
A constructor is declared inside the public section of a class and has the same name as the class. It may contain parameters to receive values during object creation. The constructor body is used to initialize the data members of the class automatically when an object is created. Example
#include <iostream>
using namespace std;
class Student
{
private:
int id;
string name;
public:
// Constructor
Student(int i, string n)
{
id = i;
name = n;
}
// Member function to display data
void display()
{
cout << "Student ID: " << id << endl;
cout << "Student Name: " << name << endl;
}
};
int main()
{
// Creating object and calling constructor
Student s1(101, "Basant");
s1.display();
return 0;
}In this example, Student is a class that contains data members and a constructor with parameters. The constructor is automatically called when the object s1 is created in the main() function. It initializes the student’s ID and name with the values provided during object creation. The display() function is then used to show the stored information on the screen.
Rules for Creating a Constructor in C++
- The constructor name must be the same as the class name.
- A constructor has no return type (not even
void). - It is called automatically when an object is created.
- It is usually declared in the public section of the class.
- A constructor can take parameters.
- A class can have multiple constructors (overloading).
- A constructor cannot be static.
- It runs only once per object at the time of creation.
- Constructors are not inherited by derived classes.
- The compiler provides a default constructor if none is defined.
Classification of a Constructor

- Default Constructor
Default constructor is also known as a zero-argument constructor, as it doesn’t take any parameter. It can be defined by the user; if not, then the compiler creates it on its own. Default constructor always initializes data members of the class with the same value they were defined.#include <iostream> using namespace std;
class Demo {
public:
Demo() {
cout << “Default Constructor Called” << endl;
}
};int main() {
Demo obj;
return 0;
}2. Parameterized Constructor:
A Parameterized Constructor in C++ is a type of constructor that takes one or more parameters. It allows you to initialize the data members of a class with specific values provided at the time of object creation.A parameterized constructor is a constructor that accepts arguments to initialize an object with user-defined values.
Syntax:
class ClassName {
public:
ClassName(parameter1, parameter2, ...) {
// initialization code
}
};
Example of parameterized constructor:
#include <iostream> using namespace std;
class Student {
public:
string name;
int age;
// Parameterized Constructor
Student(string n, int a) {
name = n;
age = a;
}
};
int main() {
Student s1(“Ram”, 20); // Passing values to constructor
cout << “Name: ” << s1.name << endl;
cout << “Age: ” << s1.age << endl;
return 0;
}
Properties of Parameterized Constructor in C++
- A parameterized constructor is a constructor that accepts arguments.
- It is used to initialize objects with specific values at the time of creation.
- It is automatically called when an object is created with parameters.
- It supports constructor overloading.
- It improves flexibility and avoids separate initialization.
- If defined, the compiler does not create a default constructor automatically.
3. Copy Constructor
A copy constructor initializes an object using another object of the same class.It’s used for deep copying if an object contains pointers or dynamically allocated memory
resources.
Syntax of Copy Constructor in C++
ClassName(const ClassName &obj) {
// copy data members from obj to this object
}Example of Copy Constructor
#include <iostream>
using namespace std;
class Student {
public:
string name;
int age;
// Parameterized Constructor
Student(string n, int a) {
name = n;
age = a;
}
// Copy Constructor
Student(const Student &s) {
name = s.name;
age = s.age;
}
};
int main() {
Student s1("Ram", 20); // Original object
Student s2 = s1; // Copy constructor called
cout << "Student 1: " << s1.name << " " << s1.age << endl;
cout << "Student 2: " << s2.name << " " << s2.age << endl;
return 0;
}Default Constructor vs Parameterized Constructor
| Default Constructor | Parameterized Constructor |
|---|---|
| None (no parameters) | One or more parameters |
| Initializes object with default values | Initializes object with user-defined values |
Example: Student s1; | Example: Student s1("Ram", 20); |
| Provided by compiler if none defined | Not provided by compiler |
| Low flexibility | High flexibility |
| Called automatically | Called automatically with arguments |
| Uses fixed or default values | Uses custom values provided at creation |
Parameterized Constructor vs Copy Constructor
| Parameterized Constructor | Copy Constructor |
|---|---|
| Takes one or more arguments | Takes a reference to an object of the same class |
| Initializes object with user-defined values | Creates a new object as a copy of an existing object |
Example: Student s1("Ram", 20); | Example: Student s2 = s1; |
| Not provided by compiler automatically | Compiler provides a default shallow copy if none defined |
| High flexibility | Medium flexibility (shallow copy may share memory) |
| Called automatically when object created with arguments | Called automatically when object is copied or passed by value |
| Initializes new data directly | Copies data from another object |
Destructor
A Destructor is a special member function of a class that is automatically called when an object goes out of scope or is deleted.It is used to release resources (like memory, files, or network connections) that the object may have acquired during its lifetime.
Properties of Destructor
- It has the same name as the class but is preceded by a tilde (~).
- It does not take any parameters.
- It cannot return a value.
- Each class has only one destructor.
- Called automatically; no need to call it explicitly.
Syntax of Destructor
~ClassName() {
// code to release resources
}
Example:
#include <iostream>
using namespace std;
class Student {
public:
string* name;
// Constructor
Student(string n) {
name = new string(n);
cout << “Constructor called for ” << *name << endl;
}
// Destructor
~Student() {
cout << “Destructor called for ” << *name << endl;
delete name; // release memory
}
};
int main() {
Student s1(“Ram”); // Constructor called
{
Student s2(“Shyam”); // Constructor called
} // Destructor called for s2 as it goes out of scope
// Destructor called for s1 at the end of main
return 0;
}
Constructor vs Destructor
| Constructor | Destructor |
|---|---|
| Special member function called when an object is created | Special member function called when an object is destroyed |
| Has the same name as the class | Has the same name as the class with a ~ (tilde) prefix |
| Can be parameterized or default | Cannot take parameters (no-argument only) |
| Can return values indirectly (by initializing objects) but has no return type | Cannot return any value |
| Used to initialize data members or allocate resources | Used to release resources or perform cleanup |
| May be overloaded (multiple constructors) | Cannot be overloaded (only one destructor per class) |
| Called automatically at object creation | Called automatically at object destruction or when it goes out of scope |
Write a program that adds two numbers using a constructor.
#include <iostream>
using namespace std;
class Add {
private:
int a, b;
public:
Add(int x, int y) {
a = x;
b = y;
}
void showSum() {
cout << "Sum = " << a + b;
}
};
int main() {
Add obj(5, 7);
obj.showSum();
return 0;
}
Write a program to copy data from one object to another using a copy constructor.
#include <iostream>
using namespace std;
class Sample {
private:
int value;
public:
Sample(int v) {
value = v;
}
Sample(const Sample &s) { // Copy Constructor
value = s.value;
}
void display() {
cout << "Value = " << value << endl;
}
};
int main() {
Sample s1(20);
Sample s2 = s1; // Copy constructor called
s1.display();
s2.display();
return 0;
}
Write a C++ program to create a class Teacher that displays “Welcome to Class” using a default constructor.
#include <iostream>
using namespace std;
// Creating class Teacher
class Teacher
{
public:
// Default constructor
Teacher()
{
cout << "Welcome to Class" << endl;
}
};
int main()
{
// Creating object of Teacher class
Teacher t;
return 0;
}
Create a class Rectangle with a constructor that initializes length and breadth and calculates the area.
#include <iostream>
using namespace std;
class Rectangle
{
private:
float length, breadth;
public:
// Constructor to initialize values
Rectangle(float l, float b)
{
length = l;
breadth = b;
}
// Function to calculate and display area
void displayArea()
{
float area = length * breadth;
cout << "Area of Rectangle = " << area << endl;
}
};
int main()
{
// Creating object and passing values
Rectangle r(10, 5);
// Calling member function
r.displayArea();
return 0;
}
Write a program using a constructor to input two numbers and display their sum.
#include <iostream>
using namespace std;
class Sum
{
private:
int num1, num2;
public:
// Constructor to input numbers
Sum()
{
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
cout << "Sum = " << num1 + num2 << endl;
}
};
int main()
{
// Object creation automatically calls constructor
Sum s;
return 0;
}
