For working professionals
For fresh graduates
More
4. C++ Variable
10. C++ for Loop
12. C++ Lambda
13. Loop in C++
15. Array in C++
16. Strings in C++
17. Substring in C++
29. Vector in C++
30. Map in C++
31. Pair in C++
33. Iterators in C++
34. Queue in C++
36. Stack in C++
37. ifstream in C++
40. Templates in C++
43. Namespace in C++
46. Recursion in C++
48. C++ Shell
49. Setw in C++
51. Atoi in C++
54. C# vs C++
55. C++ GUI
56. C++ Game Code
57. Class in C++
58. C++ Header Files
63. Cin in C++
64. Printf in C++
65. Struct in C++
66. C++ List
68. C++ Comments
72. Sorting in C++
Constructors are an important component of object-oriented programming in C++. They are special member functions within a class playing a crucial role in the creation and initialization of objects. They are blueprints for how an object should be constructed, ensuring that it starts its life in a valid and usable state.
I will teach you how to use a constructor in C++ in this tutorial and we will explore the different types of constructors we have available to us. Let us dive in and learn everything you need to know about constructors.
In the world of C++, a constructor is a special kind of member function that shares the same name as its class. It is automatically called whenever a new object of that class is created. The primary responsibility of a constructor in C++ is to initialize the object's data members, i.e., the variables that define the object's attributes and state.
Constructors are indispensable for several reasons:
This is the C++ constructor syntax:
class ClassName {
public:
// Constructor declaration (name same as constructor)
ClassName(parameter1, parameter2, ...); // Parameterized constructor (optional)
// ... other members (data and functions) ...
};
In the above C++ constructor syntax:
Here is the implementation of a constructor in C++:
// Constructor definition
ClassName::ClassName(parameter1, parameter2, ...)
: memberInitializerList (optional)
{
// Constructor body (for additional initialization)
}
In the above snippet:
Real-world example:
class Person {
public:
Person(std::string n, int a) : name(n), age(a) {} // Constructor
private:
std::string name;
int age;
};
int main() {
Person alice("Alice", 30); // Constructor called automatically
// ...
}
In this constructor in C++ example, the Person constructor initializes the name and age members when a Person object is created.
C++ offers various types of constructors, each serving a specific purpose in object creation and initialization.
A C++ default constructor is a constructor that takes no arguments. Its main purpose is to provide a basic way to create objects without explicitly setting initial values. If we do not define any constructor in a class, the compiler automatically generates a default constructor for you.
Example:
class Point {
public:
Point() : x(0), y(0) {} // Default constructor
private:
int x;
int y;
};
In the above example, the default constructor Point() initializes the x and y coordinates to zero.
A parameterized constructor in C++ accepts one or more arguments, allowing us to customize how an object is initialized when created. The arguments passed to the cpp constructor are used to set the initial values of the object's data members.
Example:
class Rectangle {
public:
Rectangle(double w, double h) : width(w), height(h) {} // Parameterized constructor
private:
double width;
double height;
};
Here, the Rectangle constructor takes two arguments (w and h) to set the width and height of the rectangle object.
A copy constructor is a special constructor used to create a new object as an exact copy of an existing object of the same class. It is essential for situations where we need to duplicate an object, such as when passing objects by value to functions or returning objects from functions.
Example:
class Person {
public:
Person(const Person& other) : name(other.name), age(other.age) {} // Copy constructor
// ...
};
In this example, the copy constructor of Person takes a reference to another Person object (other) and copies its name and age.
Introduced in C++11, move constructors are designed to efficiently transfer ownership of resources (like dynamically allocated memory) from one object to another. This is done without creating a full copy, making it much faster in scenarios where copying would be expensive.
Example:
class MyString {
public:
MyString(MyString&& other) noexcept
: data(std::move(other.data)), size(other.size)
{
other.data = nullptr;
other.size = 0;
}
// ...
};
In the MyString move constructor, the data pointer and size from other are transferred, and then other's data is set to nullptr to avoid potential double-free errors.
If you wish to learn how to code in C++, you can check out upGrad’s software engineering courses.
Here is a cpp constructor program that you can run and try out yourself:
Code:
#include <iostream>
#include <string>
class Car {
private:
std::string brand;
std::string model;
int year;
double price;
public:
// Default constructor
Car() {
brand = "Unknown";
model = "Unknown";
year = 0;
price = 0.0;
std::cout << "Default constructor called.\n";
}
// Parameterized constructor
Car(std::string b, std::string m, int y, double p) : brand(b), model(m), year(y), price(p) {
std::cout << "Parameterized constructor called.\n";
}
// Copy constructor
Car(const Car& other) {
brand = other.brand;
model = other.model;
year = other.year;
price = other.price;
std::cout << "Copy constructor called.\n";
}
// Display car information
void displayInfo() {
std::cout << "Brand: " << brand << "\nModel: " << model
<< "\nYear: " << year << "\nPrice: $" << price << std::endl;
}
};
int main() {
// Using the default constructor
Car car1;
car1.displayInfo();
// Using the parameterized constructor
Car car2("Toyota", "Camry", 2023, 25000.0);
car2.displayInfo();
// Using the copy constructor
Car car3(car2);
car3.displayInfo();
return 0;
}
In the above constructor in C++ example, we define a Car class to represent cars. The class includes four private data members: brand, model, year, and price.
We have implemented these constructors in the program:
In the main function, we create three Car objects: one using the default constructor, one using the parameterized constructor, and one using the copy constructor. We then call the displayInfo member function for each car to print its details to the console. The output will demonstrate how each constructor initializes the objects differently, showcasing the flexibility and utility of constructors in object creation and initialization.
In C++, just like we can overload functions (have multiple functions with the same name but different parameters), we can also overload constructors. This means that we can have multiple constructors within the same class, each with a distinct parameter list. The compiler intelligently selects the appropriate constructor to call based on the arguments you provide when creating an object.
Constructor in C++ overloading offers flexibility and convenience. It allows us to create objects in different ways, tailored to the specific needs of your program. Here are a few reasons why you might want to overload constructors:
When we create an object, the C++ compiler analyzes the arguments we pass and selects the most suitable constructor based on:
Example:
class Box {
public:
Box() {
length = 1.0;
width = 1.0;
height = 1.0;
}
Box(double side) : length(side), width(side), height(side) {}
Box(double l, double w, double h) : length(l), width(w), height(h) {}
private:
double length;
double width;
double height;
};
int main() {
Box box1; // Calls the default constructor (all sides = 1.0)
Box box2(5.0); // Calls the constructor with one argument (cube)
Box box3(2.0, 3.0, 4.0); // Calls the constructor with three arguments
}
In this constructor in C++ example, the Box class has three overloaded constructors:
Let us now look at some special considerations that will help you write more robust and efficient code when designing classes and using constructors.
In C++, a single-argument constructor can sometimes lead to implicit conversions, which might not always be desirable.
Example:
class MyString {
public:
MyString(int size) { /* ... */ } // Single-argument constructor
// ...
};
MyString str = 10; // Implicit conversion: int 10 is used to create a MyString object
In this code, the single-argument constructor MyString(int size) can be called implicitly when we assign an integer value (10) to a MyString object. This might not be what we intended, as it can lead to unexpected behavior.
To prevent such implicit conversions, we can declare a single-argument constructor as explicit.
Example:
class MyString {
public:
explicit MyString(int size) { /* ... */ } // Explicit constructor
// ...
};
MyString str = 10; // Error! Explicit constructor cannot be called implicitly
MyString str2(10); // Correct way to call the explicit constructor
The explicit keyword forces us to explicitly call the constructor with the correct type, preventing unintended conversions.
When we have multiple constructors, we might find that they share some common initialization logic. To avoid code duplication, C++11 introduced constructor delegation, which allows one constructor to call another constructor within the same class.
Example:
class Person {
public:
Person() : Person("", 0) {} // Delegates to the parameterized constructor
Person(std::string n, int a) : name(n), age(a) {}
private:
std::string name;
int age;
};
In this case, the default constructor in C++ delegates to the parameterized constructor, effectively reusing the initialization code.
C++ allows us to provide default values for your class's member variables directly in the class definition. This is useful when we want members to have certain initial values even if a constructor does not explicitly set them.
Example:
class Product {
public:
Product() {} // No initialization in the constructor
private:
std::string name = "Unnamed";
double price = 0.0;
};
In this example, even though the constructor is empty, the name and price members will have default values when a Product object is created.
In C++, when we create a derived class (a class that inherits from a base class), constructor interactions play a crucial role in properly initializing both base and derived class members.
Here is how it works:
Here is the constructor in C++ delegation in derived classes:
The use of constructors streamlines object creation, ensures proper initialization, and makes the code more organized and maintainable. Finally, I would also like to mention that constructors can be much more elaborate, handling complex initialization logic and resource management. To gain a solid foundation in C++ programming, I would definitely recommend you practice using constructors in your programs.
If you wish to learn programming languages such as C++, you can check out upGrad’s computer science programs such as the Master’s in Computer Science Program.
A constructor in C++ is a special member function of a class that shares its name with the class and is automatically called when an object of that class is created.
The primary purpose of a constructor in C++ is to initialize the object's data members and put the object in a valid state before it's used.
Unlike regular member functions, constructors have no return type (not even void) and are invoked automatically during object creation.
Yes, a class can have multiple constructors with different parameter lists, a concept known as constructor overloading.
A default constructor in C++ is a constructor that takes no arguments or has default values for all its parameters.
Yes, constructors can be overloaded just like regular member functions, allowing us to create objects in different ways.
A copy constructor in C++ creates a new object as an exact copy of an existing object of the same class.
No, constructors cannot be virtual in C++.
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.