0% found this document useful (0 votes)
20 views32 pages

Constructors and Destructors in C++

The document explains the concept of constructors in C++ programming, focusing on three main types: default, parameterized, and copy constructors. It provides definitions, examples, and practice questions for each type, illustrating how they initialize objects and manage memory. Key points include the automatic execution of constructors upon object creation and the distinction between shallow and deep copies in the context of copy constructors.

Uploaded by

ramkumarkln
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views32 pages

Constructors and Destructors in C++

The document explains the concept of constructors in C++ programming, focusing on three main types: default, parameterized, and copy constructors. It provides definitions, examples, and practice questions for each type, illustrating how they initialize objects and manage memory. Key points include the automatic execution of constructors upon object creation and the distinction between shallow and deep copies in the context of copy constructors.

Uploaded by

ramkumarkln
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

C++ Programming

Language using
OOPS

Vaka Vamsi Krishna


1. What is a Constructor?
Imagine you buy a toy robot. When you take it out of the box, it needs to be set up
before you can play with it — like giving it batteries or a name. A constructor in
programming does the same thing: it helps set up an object when it's created.
In simple words:
A constructor is a special function in a class that runs automatically when you make a
new object from that class.

• It initializes the object.


• It has the same name as the class.
• It does not return any value (not even void).
• It can be overloaded (you can write many versions of it).

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.

1. What is a Default Constructor?

A default constructor is a constructor that takes no parameters (or arguments).


It sets the initial values of the object when it is created.
You can think of it like when a toy comes with batteries already installed – you
don't need to add anything, it just works!

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:

A new student object is created!

Example with Default Values

#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:

Notebook created with 100 pages.

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;
}

Q2. Fill in the blanks to create a default constructor:


cpp
CopyEdit
class Animal {
public:
________() {
cout << "Animal created!" << endl;
}
};

Q3. Write a class Pen with a default constructor that sets the color to
"Blue".

Q4. What is a default constructor?


a) A function with the same name as the class
b) A function that runs when object is created
c) A function with no parameters
d) All of the above

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.

Q9. True or False:


The default constructor can initialize variables in the class.
If false, explain why.

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

Q11. Can you overload a default constructor? Try this:


class Robot {
public:
Robot() {
cout << "Default Robot created!" << endl;
}

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.

Q14. Write a class Account that uses a default constructor to set:


• Account number = 0
• Balance = 1000
• Then, use a method to print these values.

Q15. Explain what will happen in this case:

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.

You can think of it like this:


“When you make a new toy, you get to choose its color and size.”
Similarly, when you create an object, you can give it custom values using a
parameterized constructor.

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:

The toy color is: Red

.
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?

Q2. Fill in the blanks:

class Ball {
public:
string type;

Ball(_________) {
type = t;
}
};

Q3. Create a class Pen with a parameterized constructor to set color.

Q4. What will this print?

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.

Q6. Predict the output:

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;
}

Robot(string name, int id) {


cout << "Name: " << name << ", ID: " << id << endl;
}
};

Q8. Write a class Mobile with a parameterized constructor to set:


• Brand
• Price
Then create two objects with different brands and prices.
3. What is a Copy Constructor?
A copy constructor is used to make a copy of an object.
Imagine:
• You made a robot named Robo1.
• Now you want to make another robot Robo2 that is exactly the same as
Robo1.
• Instead of building Robo2 from scratch, you just copy everything from
Robo1.
That's what a copy constructor does — it copies one object into another.

Syntax of Copy Constructor in C++

ClassName (const ClassName &old_object);

Example with Explanation


Let’s make a simple class for a Book:

#include <iostream>
using namespace std;

class Book {
public:
string title;

// Constructor to set title


Book(string t) {
title = t;
}

// 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;
}

Explanation in Simple Words


• We made book1 with the title "Harry Potter".
• Then we created book2 by copying book1.
• Now both book1 and book2 have the same title.
• This is done automatically using the copy constructor.

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!

Example 1: Class with Multiple Data Members


Code:

#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!

Example 2: Deep Copy (with Pointers)


Now we go a bit deeper into memory. This one introduces pointers — it’s more
advanced but cool!
Code:

#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);
}

// Deep Copy Constructor


Note(const Note &n) {
text = new char[strlen(n.text) + 1];
strcpy(text, n.text);
}
void display() {
cout << "Note: " << text << endl;
}

~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.

Example 3: Copy Constructor inside a Class with Object Members


Let’s see what happens when one class contains another class!
Code:

#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.

Example 4: Modifying After Copy


To show why copy constructor is useful, let’s change values in one object and see if
it affects the other.

#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.setLength(20); // change only b1

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

Problem 1: When is the Copy Constructor Called?

#include <iostream>
using namespace std;

class Test {
public:
Test() {
cout << "Default constructor" << endl;
}

Test(const Test &t) {


cout << "Copy 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?

Problem 2: Shallow Copy Risk

#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);
}

Demo(const Demo &d) {


data = d.data;
}

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?

Problem 3: Multiple Copies

#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?

Problem 4: Self-Copy Check

#include <iostream>
using namespace std;

class Item {
public:
int x;
Item(int val) : x(val) {}

Item(const Item &i) {


cout << "Copy constructor called for " << i.x << endl;
x = i.x;
}

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?

Problem 5: Const Reference Return


#include <iostream>
using namespace std;

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?

Problem 1: Copy Basic Object


Level: Easy
Create a class Pen with:
• A string for brand
• An int for price
Create a copy constructor and display both original and copied object's data.
Goal: Practice syntax and basic copying of simple data types.

Problem 2: Class with Array of Integers


Level: Intermediate
Create a class Marks that:
• Stores 5 subject marks in an int marks[5] array
• Has a constructor to take 5 inputs
• Has a copy constructor
Test:
1. Create object m1 with 5 marks.
2. Copy into m2 using the copy constructor.
3. Change marks in m1 and show that m2 is not affected.
Goal: Understand how arrays behave in copy constructors.

Problem 3: Deep Copy with Dynamic Memory


Level: Intermediate
Create a class Note that:
• Stores char* message (use new and strcpy)
• Has a copy constructor with deep copy
• Use delete[] in destructor
Create 2 objects and ensure:
• Modifying one doesn’t affect the other.
Goal: Practice deep copying using dynamic memory.

Problem 4: Object as a Member


Level: Intermediate
Create a class Tyre with:
• An int size
Create a class Bike that:
• Has a string model
• Has a Tyre object inside it
Add copy constructor to both.
Create a Bike object, copy it, and display both.
Goal: Understand how to write copy constructors when one class is inside another.

Problem 5: Copy Constructor vs Assignment


Level: Tricky
Create a class Book with a title (string), and:
• Show the difference between copy constructor and assignment operator by
printing messages when each is called.
Hint:
Book(const Book &b) {
cout << "Copy constructor called!" << endl;
}
Book& operator=(const Book &b) {
cout << "Assignment operator called!" << endl;
return *this;
}
Test:
Book b1("Harry");
Book b2 = b1; // Copy constructor
Book b3("Dummy");
b3 = b1; // Assignment operator
Goal: Learn difference between copy constructor and assignment operator.
What is a Destructor?
Imagine you have a robot toy - that you build using building blocks.
• When you build it, you use a constructor.
• When you're done playing and want to clean up and put the blocks back in
the box, you use a destructor.
In programming:
• Constructor creates (or builds) the object.
• Destructor destroys (or cleans up) the object when it is no longer needed.

🛠 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

Simple Code Example in C++

#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!"

Practice Questions (with increasing difficulty)


Question 1: Basic Destructor
Create a class Pen with a constructor and destructor. Print messages inside both and
create one object in main().

Question 2: Destructor with Multiple Objects


Create a class Book with constructor and destructor. Create three objects and watch in
which order destructors are called.

Question 3: Destructor with Dynamic Memory


Create a class Note that allocates memory using new in constructor. Free it using delete
in destructor. Show that memory is cleaned up.

Question 4: Destructor Inside a Function


Create a class Box with destructor. Create the object inside a function, and observe
when destructor is called.

Question 5: Destructor with Array of Objects


Create a class Car with constructor and destructor. Create an array of 5 Car objects. See
how destructors are called for each.

Question 1: Basic Destructor


Code:
#include <iostream>
using namespace std;

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().

Question 2: Destructor with Multiple Objects


Code:
#include <iostream>
using namespace std;

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.

Question 4: Destructor Inside a Function


Code:
#include <iostream>
using namespace std;

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()!

Question 5: Destructor with Array of Objects


Code:
#include <iostream>
using namespace std;

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.

Problem 1: Destructor in Function Scope


#include <iostream>
using namespace std;

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?

Problem 2: Copy Constructor and Destructor


#include <iostream>
using namespace std;
class Beta {
public:
Beta() {
cout << "Constructor\n";
}

Beta(const Beta &b) {


cout << "Copy Constructor\n";
}

~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?

Problem 3: Return by Value

#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?

Problem 4: Array of Objects


#include <iostream>
using namespace std;

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?

Problem 5: Constructor + Destructor with Static Object

#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

Why Are They Important?


• Constructors help to set things up.
• Destructors help to clean things up.
Just like when you play with toys:
• You take them out and set them up = Constructor
• You put them back in the box when done = Destructor
Our greatest glory is
not in never failing,
but in rising every
time we fail.
- Confucius

You might also like