Index
Types of Constructors:
- Default Constructor
- Parameterized Constructor
- Copy Constructor
- Deep Copy Constructor
Default Constructor
A default constructor is a special type of constructor in a class that is automatically called when an object of that class is created, and it doesn’t require any arguments.
For example:
#include <iostream>
#include <string>
using namespace std;
class Gamer {
public:
string username;
int level;
int score;
// Default Constructor
Gamer() {
username = "Guest"; // Initialize username with "Guest"
level = 1; // Initialize level with 1
score = 0; // Initialize score with 0
}
// Method to display gamer details
void displayDetails() {
cout << "Username: " << username << endl;
cout << "Level: " << level << endl;
cout << "Score: " << score << endl;
}
};
int main() {
// Create an object of the Gamer class
Gamer gamer1;
// Display details of gamer1
gamer1.displayDetails();
return 0;
}
Output:
Username: Guest
Level: 1
Score: 0
Explanation:
- The default constructor is called when a new
Gamer
object is created without any arguments. - It initializes the object’s attributes (
username
,level
,score
) with default values.
Parameterized Constructor
A parameterized constructor in C++ is a special type of constructor that allows you to pass arguments when creating an object.
For Example: “Designing Your Own Pizza”
Imagine you walk into a pizza shop. You have the option to order a “default” pizza, which might be a plain cheese pizza with a standard crust and a fixed size. But what if you want to customize your pizza? You might want extra cheese, a specific size, or a different type of crust. This is where the concept of a parameterized constructor comes into play.
#include <iostream>
#include <string>
using namespace std;
class Pizza {
public:
string crustType;
string size;
int cheeseAmount;
// Parameterized Constructor
Pizza(string cType, string pSize, int cheese) {
crustType = cType;
size = pSize;
cheeseAmount = cheese;
}
void displayDetails() {
cout << "Crust Type: " << crustType << endl;
cout << "Size: " << size << endl;
cout << "Cheese Amount: " << cheeseAmount << " grams" << endl;
}
};
int main() {
// Creating a custom pizza
Pizza pizza1("Thin", "Large", 200); // Thin crust, Large size, 200 grams of cheese
Pizza pizza2("Thick", "Medium", 150); // Thick crust, Medium size, 150 grams of cheese
// Display details of the pizzas
cout << "Pizza 1 Details:" << endl;
pizza1.displayDetails();
cout << "Pizza 2 Details:" << endl;
pizza2.displayDetails();
return 0;
}
Output:
Pizza 1 Details:
Crust Type: Thin
Size: Large
Cheese Amount: 200 grams
Pizza 2 Details:
Crust Type: Thick
Size: Medium
Cheese Amount: 150 grams
Explanation:
Step 1: Define the Parameterized Constructor
The parameterized constructor allows us to create a Pizza
object with specific values for crustType
, size
, and cheeseAmount
.
// Parameterized Constructor
Pizza(string cType, string pSize, int cheese) {
crustType = cType; // Initialize crustType with the value of cType
size = pSize; // Initialize size with the value of pSize
cheeseAmount = cheese; // Initialize cheeseAmount with the value of cheese
}
Explanation:
Pizza(string cType, string pSize, int cheese) { ... }
is a constructor that takes three parameters:cType
: The type of crust (e.g., “Thin”, “Thick”).pSize
: The size of the pizza (e.g., “Small”, “Medium”, “Large”).cheese
: The amount of cheese in grams.
- Inside the constructor:
crustType
is initialized withcType
.size
is initialized withpSize
.cheeseAmount
is initialized withcheese
.
- This allows us to create a pizza with specific characteristics.
Step 2: Create Objects Using the Parameterized Constructor
In the main()
function, we create two pizza objects using the parameterized constructor and then display their details.
int main() {
// Creating a custom pizza
Pizza pizza1("Thin", "Large", 200); // Thin crust, Large size, 200 grams of cheese
Pizza pizza2("Thick", "Medium", 150); // Thick crust, Medium size, 150 grams of cheese
// Display details of the pizzas
cout << "Pizza 1 Details:" << endl;
pizza1.displayDetails();
cout << "Pizza 2 Details:" << endl;
pizza2.displayDetails();
return 0;
}
Explanation:
Pizza pizza1("Thin", "Large", 200);
creates aPizza
object namedpizza1
with:crustType = "Thin"
size = "Large"
cheeseAmount = 200
grams
Pizza pizza2("Thick", "Medium", 150);
creates anotherPizza
object namedpizza2
with:crustType = "Thick"
size = "Medium"
cheeseAmount = 150
grams
pizza1.displayDetails();
andpizza2.displayDetails();
are called to display the details of each pizza.
In this example, the Pizza
class uses a parameterized constructor to initialize the crustType
, size
, and cheeseAmount
of each pizza when the objects are created..
Copy Constructor
A copy constructor in C++ is a special type of constructor used to create a new object as a copy of an existing object. This is particularly useful when you want to create a duplicate of an object, ensuring that all its attributes are copied accurately.
Scenario: Copying a Drawing
Imagine you have a drawing on a piece of paper, and you want to make an exact copy of it. In programming terms, the drawing can be thought of as an object with certain properties like color, size, and shape. A copy constructor in C++ can be used to create an exact duplicate of this drawing.
For example:
#include <iostream>
#include <string>
using namespace std;
class Drawing {
public:
string color;
string size;
string shape;
// Parameterized Constructor
Drawing(string c, string s, string sh) {
color = c;
size = s;
shape = sh;
}
// Copy Constructor
Drawing(const Drawing &originalDrawing) {
color = originalDrawing.color;
size = originalDrawing.size;
shape = originalDrawing.shape;
cout << "Copy Constructor: A copy of the drawing has been created!" << endl;
}
// Method to display drawing details
void displayDetails() {
cout << "Drawing Details:" << endl;
cout << "Color: " << color << endl;
cout << "Size: " << size << endl;
cout << "Shape: " << shape << endl;
}
};
int main() {
// Create an original drawing object
Drawing drawing1("Red", "A4", "Circle");
// Display details of the original drawing
drawing1.displayDetails();
// Create a copy of the original drawing using the copy constructor
Drawing drawing2 = drawing1;
// Display details of the copied drawing
drawing2.displayDetails();
return 0;
}
Output:
Drawing Details:
Color: Red
Size: A4
Shape: Circle
Copy Constructor: A copy of the drawing has been created!
Drawing Details:
Color: Red
Size: A4
Shape: Circle
Explanation:
Step 1: Define the Copy Constructor
// Copy Constructor
Drawing(const Drawing &originalDrawing) {
color = originalDrawing.color;
size = originalDrawing.size;
shape = originalDrawing.shape;
cout << "Copy Constructor: A copy of the drawing has been created!" << endl;
}
Explanation:
- Purpose:
- A copy constructor creates a new object as a copy of an existing object. It takes a reference to another
Drawing
object and duplicates its attributes.
- A copy constructor creates a new object as a copy of an existing object. It takes a reference to another
- Copying Process:
color = originalDrawing.color;
,size = originalDrawing.size;
, andshape = originalDrawing.shape;
copy the values of thecolor
,size
, andshape
attributes from the original object (originalDrawing
) to the new object.
- Message:
cout << "Copy Constructor: A copy of the drawing has been created!" << endl;
prints a message to the console whenever the copy constructor is called, indicating that a new copy has been created.
Step 2: Main Function
int main() {
// Create an original drawing object
Drawing drawing1("Red", "A4", "Circle");
// Display details of the original drawing
drawing1.displayDetails();
// Create a copy of the original drawing using the copy constructor
Drawing drawing2 = drawing1;
// Display details of the copied drawing
drawing2.displayDetails();
return 0;
}
Explanation:
- Creating the Original Object:
Drawing drawing1("Red", "A4", "Circle");
creates an object nameddrawing1
using the parameterized constructor. The drawing has a color of “Red”, size “A4”, and shape “Circle”.
- Displaying the Original Drawing’s Details:
drawing1.displayDetails();
calls thedisplayDetails()
method ondrawing1
to print its attributes.
- Creating a Copy of the Original Object:
Drawing drawing2 = drawing1;
creates a new objectdrawing2
as a copy ofdrawing1
using the copy constructor. This line triggers the copy constructor, and you see the message “Copy Constructor: A copy of the drawing has been created!” printed to the console.
- Displaying the Copied Drawing’s Details:
drawing2.displayDetails();
calls thedisplayDetails()
method ondrawing2
to print its attributes, which are identical todrawing1
.
Deep Copy Constructor
A deep copy constructor is a special type of constructor used to create a new object as a copy of an existing object. However, unlike a shallow copy like above example , which copies the values of the data members, a deep copy duplicates everything, including any dynamically allocated memory. This ensures that the copied object has its own separate copy of resources .
Why is Deep Copy Important?
Deep copy is important when your class involves dynamic memory allocation (e.g., using pointers). Without a deep copy, two objects might share the same memory space, leading to problems like data corruption, unexpected behavior, or crashes.
For example:
#include <iostream>
#include <cstring> // Needed for string handling functions
using namespace std;
class Book {
private:
char* title; // Pointer to hold the title of the book
public:
// Parameterized constructor
Book(const char* bookTitle) {
// Allocate memory for the title and copy the book title into it
title = new char[strlen(bookTitle) + 1];
strcpy(title, bookTitle);
}
// Deep copy constructor
Book(const Book& other) {
// Allocate new memory for the title in the new object
title = new char[strlen(other.title) + 1];
// Copy the title from the other object to this object
strcpy(title, other.title);
}
// Method to display the book title
void display() const {
cout << "Book Title: " << title << endl;
}
};
int main() {
// Create a Book object with the title "The Great Gatsby"
Book book1("The Great Gatsby");
// Use the deep copy constructor to create another Book object
Book book2 = book1;
// Display the titles of both books
cout << "Original Book: ";
book1.display();
cout << "Copied Book (Deep Copy): ";
book2.display();
return 0;
}
Output:
Original Book: Book Title: The Great Gatsby
Copied Book (Deep Copy): Book Title: The Great Gatsby
Explanation:
Step 1: Parameterized Constructor:
Book(const char* bookTitle) {
title = new char[strlen(bookTitle) + 1];
strcpy(title, bookTitle);
}
- The constructor allocates memory for the
title
based on the length ofbookTitle
.
- It then copies the content of
bookTitle
into the newly allocated memory.
Step 2: Deep Copy Constructor:
Book(const Book& other) {
title = new char[strlen(other.title) + 1];
strcpy(title, other.title);
}
- The deep copy constructor is invoked when a new
Book
object is created as a copy of an existing object. - It allocates new memory for the
title
and copies the content from theother
object’s title to ensure both objects have independent copies of the title.
Step 3: Main Function:
int main() {
Book book1("The Great Gatsby");
Book book2 = book1;
cout << "Original Book: ";
book1.display();
cout << "Copied Book (Deep Copy): ";
book2.display();
return 0;
}
- In
main()
, we create aBook
objectbook1
with the title “The Great Gatsby”. - We then create another
Book
objectbook2
by copyingbook1
. - The deep copy constructor ensures that
book2
has its own independent copy of the title. - Finally, we display the titles of both books.