Constructors and Destructors in C++
Constructors and Destructors in C++
Language using
OOPS
Types of Constructors
There are 3 main types of constructors:
Type Description
1. Default Constructor No parameters, gives default values.
2. Parameterized Constructor Takes parameters and assigns custom values.
3. Copy Constructor Copies values from another object.
Example in C++
#include <iostream>
using namespace std;
class Student
{
public:
// Default constructor
Student() {
cout << "A new student object is created!" << endl;
}
};
int main()
{
Student s1; // This will call the default constructor
return 0;
}
Output:
#include <iostream>
using namespace std;
class Notebook {
public:
int pages;
// Default constructor
Notebook() {
pages = 100;
cout << "Notebook created with " << pages << " pages." << endl;
}
};
int main() {
Notebook n1;
return 0;
}
Output:
Practice Questions
Q1. What will the following program output?
#include <iostream>
using namespace std;
class Car
{
public:
Car() {
cout << "Car is ready to drive!" << endl;
}
};
int main() {
Car myCar;
return 0;
}
Q3. Write a class Pen with a default constructor that sets the color to
"Blue".
Q5. Create a class Book with a default constructor that sets title =
"Unknown" and price = 0.
Q6. Modify this class so that it shows the message: "Book has 200 pages"
using a default constructor.
class Book {
public:
int pages;
Book() {
// Write your code here
}
void display() {
cout << "Book has " << pages << " pages" << endl;
}
};
Q7. Predict the output:
class Lamp {
public:
int brightness;
Lamp() {
brightness = 100;
cout << "Brightness: " << brightness << endl;
}
};
int main() {
Lamp l;
return 0;
}
Q8. Create a class Fan with a default constructor that sets speed = 3 and
type = "Ceiling". Display the values using a method.
Q10. What will happen if you do not write any constructor in your class?
a) Compiler gives an error
b) Compiler automatically creates a default constructor
c) Object cannot be created
d) You must write your own constructor
Robot(int id) {
cout << "Robot ID: " << id << endl;
}
};
int main() {
Robot r1;
Robot r2(101);
return 0;
}
What will be the output?
Q12. Create a class Clock that has three variables – hours, minutes,
seconds – initialized to 12:00:00 using the default constructor.
Also, add a displayTime() function.
Q13. Can you have multiple default constructors in one class? If not,
explain why.
class Sample {
int x;
public:
Sample() {
cout << "Constructor called" << endl;
}
};
int main() {
Sample* ptr = new Sample();
delete ptr;
return 0;
}
What will be the output? Will memory be freed properly?
Summary
• A constructor runs automatically when an object is created.
• A default constructor has no parameters.
• It gives default values to the object.
• It's useful for setting up objects quickly!
2. What is a Parameterized Constructor?
A parameterized constructor is a constructor that takes inputs
(parameters) to set values in your object.
Example 1:
Let’s say we are creating a Toy:
#include <iostream>
using namespace std;
class Toy {
public:
string color;
// Parameterized constructor
Toy(string c) {
color = c;
}
void showColor() {
cout << "The toy color is: " << color << endl;
}
};
int main() {
Toy myToy("Red");
myToy.showColor();
return 0;
}
Output:
.
Example 2: Constructor With Default Parameters
class Box {
public:
Box(int length = 5, int width = 10) {
cout << "Length: " << length << ", Width: " << width << endl;
}
};
int main() {
Box b1;
Box b2(7);
Box b3(7, 3);
}
Concepts Tested: Default values in parameterized constructors.
Key Points
• A parameterized constructor lets you pass values.
• It helps you set custom values when creating objects.
• It makes your class more flexible and useful.
Practice Questions
Beginner
Q1. What is a parameterized constructor?
class Ball {
public:
string type;
Ball(_________) {
type = t;
}
};
class Animal {
public:
Animal(string name) {
cout << "This is a " << name << endl;
}
};
int main() {
Animal a("Tiger");
}
Intermediate
Q5. Create a class Book that takes two parameters: title (string) and pages (int).
Write a method to display the details.
class Hero {
public:
Hero(string name, int power) {
cout << name << " has power level " << power << endl;
}
};
int main() {
Hero h("Ironman", 9000);
}
Advanced
Q7. Can we have more than one parameterized constructor with different numbers of
parameters? Try it out!
class Robot {
public:
Robot(string name) {
cout << "Name: " << name << endl;
}
#include <iostream>
using namespace std;
class Book {
public:
string title;
// Copy Constructor
Book(const Book &b) {
title = b.title;
}
void show() {
cout << "Book title: " << title << endl;
}
};
int main() {
Book book1("Harry Potter"); // create book1
Book book2 = book1; // copy book1 into book2 using copy constructor
book1.show(); // Output: Book title: Harry Potter
book2.show(); // Output: Book title: Harry Potter
return 0;
}
Real-Life Analogy
Imagine you wrote a message on a paper.
Now you want your friend to have the same message.
So, you take a photocopy of your paper and give it to your friend.
That photocopy is what the copy constructor does — it copies all the information
from one object to another!
#include <iostream>
using namespace std;
class Student {
string name;
int age;
float marks;
public:
// Parameterized constructor
Student(string n, int a, float m) {
name = n;
age = a;
marks = m;
}
// Copy constructor
Student(const Student &s) {
name = s.name;
age = s.age;
marks = s.marks;
}
void display() {
cout << "Name: " << name << ", Age: " << age << ", Marks: " << marks << endl;
}
};
int main() {
Student s1("Ravi", 14, 92.5);
Student s2 = s1; // copy constructor in action
s1.display();
s2.display();
return 0;
}
What’s New Here?
We added more details to the object: name, age, marks. Still, the copy constructor
copies all values perfectly into a new student!
#include <iostream>
#include <cstring>
using namespace std;
class Note {
char *text;
public:
// Constructor
Note(const char *t) {
text = new char[strlen(t) + 1];
strcpy(text, t);
}
~Note() {
delete[] text; // Freeing memory
}
};
int main() {
Note n1("Don't forget homework!");
Note n2 = n1; // Uses copy constructor
n1.display();
n2.display();
return 0;
}
What’s Happening?
• We're using char* (pointer) to store text.
• We allocate new memory in the copy constructor so that each object has its
own copy (not shared).
• This is called a deep copy, which is very important when using dynamic
memory.
#include <iostream>
using namespace std;
class Engine {
public:
int power;
Engine(int p) : power(p) {}
};
class Car {
string model;
Engine engine;
public:
// Constructor
Car(string m, int p) : model(m), engine(p) {}
// Copy Constructor
Car(const Car &c) : model(c.model), engine(c.engine) {}
void show() {
cout << "Car Model: " << model << ", Engine Power: " << engine.power << "HP"
<< endl;
}
};
int main() {
Car c1("BMW", 300);
Car c2 = c1;
c1.show();
c2.show();
return 0;
}
What’s Cool?
• The Car class contains another class object Engine.
• The copy constructor copies everything, including the object inside it.
#include <iostream>
using namespace std;
class Box {
int length;
public:
Box(int l) : length(l) {}
// Copy constructor
Box(const Box &b) {
length = b.length;
}
void setLength(int l) {
length = l;
}
void show() {
cout << "Length: " << length << endl;
}
};
int main() {
Box b1(10);
Box b2 = b1; // copy
b1.show(); // Output: 20
b2.show(); // Output: 10 (not affected!)
return 0;
}
Why Important?
• b2 stays unchanged when b1 changes.
• This proves the copy constructor made an independent copy, not just a
reference.
Summary Table:
Feature Shallow Copy Deep Copy
Memory Shared Separate
Safe? Risky (crash if freed twice) Safe
Use pointer? No Yes
Uses Simple objects Dynamic memory objects
#include <iostream>
using namespace std;
class Test {
public:
Test() {
cout << "Default constructor" << endl;
}
Test fun(Test t) {
return t;
}
int main() {
Test a;
fun(a);
return 0;
}
Think: How many times will copy constructor run? What about default constructor?
#include <iostream>
#include <cstring>
using namespace std;
class Demo {
char *data;
public:
Demo(const char *s) {
data = new char[strlen(s) + 1];
strcpy(data, s);
}
void display() {
cout << data << endl;
}
~Demo() {
delete[] data;
}
};
int main() {
Demo d1("Hello");
Demo d2 = d1;
d2.display();
d1.display(); // What's happening here?
return 0;
}
Think: Is this a deep or shallow copy? What will happen at runtime?
#include <iostream>
using namespace std;
class Sample {
public:
Sample() {
cout << "Default" << endl;
}
Sample(const Sample &s) {
cout << "Copied" << endl;
}
};
Sample get() {
Sample s;
return s;
}
int main() {
Sample obj = get();
return 0;
}
Think: How many times is the copy constructor called? Any optimizations by
compiler?
#include <iostream>
using namespace std;
class Item {
public:
int x;
Item(int val) : x(val) {}
void show() {
cout << x << endl;
}
};
int main() {
Item i1(5);
i1 = i1;
i1.show();
return 0;
}
Think: Will the copy constructor be called in i1 = i1;? Why or why not?
class Box {
public:
int val;
Box(int v) : val(v) {}
Box(const Box &b) {
cout << "Copy constructor: " << b.val << endl;
val = b.val;
}
};
Box fun() {
Box b(10);
return b;
}
int main() {
const Box &b2 = fun();
cout << b2.val << endl;
return 0;
}
Think: Will the copy constructor be called here? When? How many times?
🛠 Real-Life Examples:
1. Water Bottle
• When you fill a water bottle: Constructor
• When you empty and clean it: Destructor
2. Toy Building Blocks
• You build a Lego house: Constructor
• You take it apart and put back in the box: Destructor
3. Opening and Closing a File on Computer
• You open a file: Constructor
• You close and delete temp files: Destructor
#include <iostream>
using namespace std;
class Robot {
public:
Robot() {
cout << "Robot is built! " << endl;
}
~Robot() {
cout << "Robot is destroyed and cleaned up! " << endl;
}
};
int main() {
Robot r1;
return 0;
}
When you run this:
• It will first say "Robot is built!"
• Then at the end of the program, it says "Robot is destroyed!"
class Pen {
public:
Pen() {
cout << "Pen created " << endl;
}
~Pen() {
cout << "Pen destroyed " << endl;
}
};
int main() {
Pen myPen;
return 0;
}
Output:
Pen created
Pen destroyed
Explanation:
The constructor is called when myPen is created.
The destructor is called automatically at the end of main().
class Book {
public:
Book() {
cout << "Book created " << endl;
}
~Book() {
cout << "Book destroyed " << endl;
}
};
int main() {
Book b1, b2, b3;
return 0;
}
Output:
nginx
CopyEdit
Book created
Book created
Book created
Book destroyed
Book destroyed
Book destroyed
Explanation:
Constructors are called in order of creation (b1 → b2 → b3),
but destructors are called in reverse order (b3 → b2 → b1) — like stacking books
and unstacking them!
Question 3: Destructor with Dynamic Memory
Code:
#include <iostream>
#include <cstring>
using namespace std;
class Note {
char* text;
public:
Note(const char* t) {
text = new char[strlen(t) + 1];
strcpy(text, t);
cout << "Note created with message: " << text << endl;
}
~Note() {
cout << "Note destroyed and memory freed: " << text << endl;
delete[] text;
}
};
int main() {
Note myNote("Hello world!");
return 0;
}
Output:
Note created with message: Hello world!
Note destroyed and memory freed: Hello world!
Explanation:
We used new for memory and delete[] in the destructor to avoid memory leaks.
class Box {
public:
Box() {
cout << "Box created " << endl;
}
~Box() {
cout << "Box destroyed " << endl;
}
};
void createBox() {
Box b;
cout << "Inside the function!" << endl;
}
int main() {
createBox();
cout << "Back in main!" << endl;
return 0;
}
Output:
Box created
Inside the function!
Box destroyed
Back in main!
Explanation:
Box was created inside createBox(), so its destructor runs when the function ends,
not at the end of main()!
class Car {
public:
Car() {
cout << "Car ready " << endl;
}
~Car() {
cout << "Car destroyed " << endl;
}
};
int main() {
Car cars[3];
return 0;
}
Output:
Car ready
Car ready
Car ready
Car destroyed
Car destroyed
Car destroyed
Explanation:
Each object in the array calls the constructor and destructor.
Again, destructors run in reverse order.
class Alpha {
public:
Alpha() {
cout << "Alpha created\n";
}
~Alpha() {
cout << "Alpha destroyed\n";
}
};
void createAlpha() {
Alpha a;
cout << "Inside function\n";
}
int main() {
createAlpha();
cout << "Back in main\n";
return 0;
}
Q: When and how many times is the destructor called?
~Beta() {
cout << "Destructor\n";
}
};
void test(Beta b) {
cout << "Inside test()\n";
}
int main() {
Beta b1;
test(b1);
cout << "Back in main\n";
return 0;
}
Q: In what order do the constructor, copy constructor, and destructor run?
#include <iostream>
using namespace std;
class Gamma {
public:
Gamma() {
cout << "Gamma Created\n";
}
~Gamma() {
cout << "Gamma Destroyed\n";
}
};
Gamma createGamma() {
Gamma g;
return g;
}
int main() {
Gamma g = createGamma();
return 0;
}
Q: How many times is the destructor called? Is the object copied or optimized?
class Delta {
public:
Delta() {
cout << "Delta Built\n";
}
~Delta() {
cout << "Delta Destroyed\n";
}
};
int main() {
Delta d[2];
return 0;
}
Q: In what order do the destructors run?
#include <iostream>
using namespace std;
class Epsilon {
public:
Epsilon() {
cout << "Epsilon Created\n";
}
~Epsilon() {
cout << "Epsilon Destroyed\n";
}
};
void createEpsilon() {
static Epsilon e;
cout << "Inside createEpsilon\n";
}
int main() {
createEpsilon();
cout << "Back in main\n";
return 0;
}
Q: Will the destructor run before or after main()?
Constructors in C++
What is a Constructor?
A constructor is a special function that is automatically called when an object is
created.
Key Points:
• Has the same name as the class.
• No return type, not even void.
• Can be overloaded (you can have many constructors).
• Used to initialize data members of a class.
Types of Constructors:
1. Default Constructor – No parameters.
2. Parameterized Constructor – Takes arguments.
3. Copy Constructor – Creates a new object as a copy of an existing one.
Destructors in C++
What is a Destructor?
A destructor is a special function that is automatically called when an object is
destroyed.
Key Points:
• Has the same name as the class, but with a tilde (~).
• No return type and cannot have parameters.
• Only one destructor per class (no overloading).
• Used to free resources like memory, files, etc.
Constructor vs Destructor
Feature Constructor Destructor
Purpose Initializes object Cleans up when object ends
Name Same as class ~ followed by class name
Return Type None None
Parameters Can have Cannot have
Overloading Yes No
Called when Object is created Object is destroyed