Syntax of Constructors in C++
To use constructors in C++, you need to know how to write them in your code. Constructors look a bit like functions, but they have specific rules.
Writing a Constructor Inside the Class:
When you write a constructor inside your class, it looks like this:
class MyClass {
public:
MyClass() {
// What the constructor does
}
};
In this example, MyClass() is the constructor. It has the same name as the class and doesn't need a return type, not even void.
Writing the Constructor Within the Class
In C++, constructors are special member functions used to initialize objects of a class. Writing a constructor within the class allows you to define the constructor’s behavior directly in the class declaration. This approach is often used when the constructor is simple and concise. Here's an example:
#include <iostream>
using namespace std;
class MyClass {
public:
int x;
// Constructor defined within the class
MyClass(int value) : x(value) {
cout << "Constructor called. Value initialized to " << x << endl;
}
};
int main() {
MyClass obj(10); // Object creation
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
Output:
Constructor called. Value initialized to 10
Writing a Constructor Outside the Class
Sometimes, you might want to write the constructor outside the class. Here's how:
class MyClass {
public:
MyClass(); // Declaration inside the class
};
MyClass::MyClass() {
// Definition outside the class
// What the constructor does
}
Here, you first tell the class there will be a constructor (MyClass();), and then you define what it does outside the class (MyClass::MyClass() { ... }).
Example
Let's look at a simple example using a Book class.
Creating a Book Class with a Constructor:
Imagine we have a class named Book. We want each book to have a title and an author. Here's how we can do it:
C++
#include <iostream>
#include <string>
using namespace std;
class Book {
public:
string title;
string author;
// Constructor for Book
Book(string bookTitle, string bookAuthor) {
title = bookTitle;
author = bookAuthor;
}
};
int main() {
// Creating a Book object
Book myBook("The Little Prince", "Antoine de Saint-Exupéry");
cout << "Book: " << myBook.title << "\n";
cout << "Author: " << myBook.author << "\n";
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
Output
Book: The Little Prince
Author: Antoine de Saint-Exupéry
In this example, Book(string bookTitle, string bookAuthor) is the constructor. It sets up a new Book object with a title and an author.
When we create myBook, we give it a title and an author. The constructor uses these to set up myBook.
Characteristics of Constructors in C++
- Automatic Call-: Constructors are called automatically when you create an object. You don't need to call them yourself like other functions.
- No Return Type-:Constructors don't have a return type, not even void. This is because their job is to set up the object, not to give something back.
- Same Name as the Class-:The constructor's name is always the same as the class name. This is how C++ knows it's a constructor.
- Can't be Called Directly-:You can't call a constructor on an object that's already created. They're only for setting up new objects.
- Default Constructor-:If you don't write any constructor for your class, C++ will give you a default one. This default constructor doesn't do much, just creates the object.
Types of Constructors in C++
There are four types of Constructors in C++
- Default Constructor
- Parameterized Constructor
- Copy Constructor
- Move Constructor
1. Default Constructor
A default constructor doesn't take any arguments. It's used to create an object when you don't need to give it any initial values.
class Box {
public:
int size;
// Default constructor
Box() {
size = 10; // Giving a default size
}
};
In this Box class, the default constructor sets every new Box object's size to 10.
Example
Here's an example to illustrate the concept of a default constructor in C++:
C++
#include <iostream>
using namespace std;
class Box {
public:
int size;
// Default constructor
Box() {
size = 10; // Giving a default size
}
// Function to display the size
void displaySize() {
cout << "Box size: " << size << endl;
}
};
int main() {
// Creating an object of Box using the default constructor
Box box1;
box1.displaySize();
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
Output
Box size: 10
2. Parameterized Constructor
A parameterized constructor takes arguments and uses them to set the object's initial state. This is useful when you want your object to start with specific values.
class Rectangle {
public:
int width, height;
// Parameterized constructor
Rectangle(int w, int h) {
width = w;
height = h;
}
};
Here, the Rectangle class has a constructor that takes width and height as parameters to set up new Rectangle objects.
Example
Here's an example to illustrate the concept of a parameterized constructor in C++:
C++
#include <iostream>
using namespace std;
class Rectangle {
public:
int width, height;
// Parameterized constructor
Rectangle(int w, int h) {
width = w;
height = h;
}
// Function to display the area of the rectangle
void displayArea() {
cout << "Area of the rectangle: " << width * height << endl;
}
};
int main() {
Rectangle rect1(5, 10); // Creating an object of Rectangle with width 5 and height 10
Rectangle rect2(7, 3); // Creating another object of Rectangle with width 7 and height 3
rect1.displayArea();
rect2.displayArea();
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
Output
Area of the rectangle: 50
Area of the rectangle: 21
3. Copy Constructor
A copy constructor creates a new object as a copy of an existing object. This is useful when you want two objects with the same state.
class Circle {
public:
int radius;
// Copy constructor
Circle(const Circle &oldCircle) {
radius = oldCircle.radius;
}
};
This Circle class's copy constructor takes an existing Circle object and makes a new one with the same radius.
Example
Here's an example to illustrate the concept of a copy constructor in C++:
C++
#include <iostream>
using namespace std;
class Circle {
public:
int radius;
// Parameterized constructor
Circle(int r) {
radius = r;
}
// Copy constructor
Circle(const Circle &oldCircle) {
radius = oldCircle.radius;
}
// Function to display the radius of the circle
void displayRadius() {
cout << "Radius of the circle: " << radius << endl;
}
};
int main() {
Circle circle1(5); // Creating an object of Circle with radius 5
Circle circle2 = circle1; // Creating a new object using the copy constructor
circle1.displayRadius();
circle2.displayRadius();
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
Output
Radius of the circle: 5
Radius of the circle: 5
4. Move Constructor
A move constructor transfers resources from a temporary object to a new object. It's used to improve performance by avoiding unnecessary copying.
class Vector {
public:
int size;
int* data;
// Move constructor
Vector(Vector &&tempVector) : size(tempVector.size), data(tempVector.data) {
tempVector.data = nullptr; // Prevents deleting data in the temporary object
}
};
In the Vector class, the move constructor takes a temporary Vector object, takes over its data, and then ensures the temporary object doesn't delete the data when it's destroyed.
Example
Here's an example to illustrate the concept of a move constructor in C++:
C++
#include <iostream>
using namespace std;
class Vector {
public:
int size;
int* data;
// Parameterized constructor
Vector(int s) : size(s) {
data = new int[s];
for (int i = 0; i < s; ++i) {
data[i] = i; // Initialize the vector with some values
}
}
// Move constructor
Vector(Vector&& tempVector) : size(tempVector.size), data(tempVector.data) {
tempVector.data = nullptr; // Prevents deleting data in the temporary object
}
// Destructor
~Vector() {
delete[] data;
}
// Function to display the vector elements
void display() const {
for (int i = 0; i < size; ++i) {
cout << data[i] << " ";
}
cout << endl;
}
};
int main() {
Vector vec1(5);
cout << "vec1: ";
vec1.display();
Vector vec2 = move(vec1);
cout << "After move, vec1: ";
if (vec1.data != nullptr) {
vec1.display();
} else {
cout << "vec1 is empty" << endl;
}
cout << "vec2: ";
vec2.display();
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
Output
vec1: 0 1 2 3 4
After move, vec1: vec1 is empty
vec2: 0 1 2 3 4
Frequently Asked Questions
What is constructor in C++ with an example?
In C++, a constructor is a special member function that initializes objects of a class. It has the same name as the class and is automatically called when an object is created. Constructors can set initial values for class members.
What is the difference between a default constructor and a parameterized constructor?
A default constructor takes no arguments and initializes an object with default values. A parameterized constructor, however, accepts arguments to initialize an object with specific values. Both constructors serve to initialize objects in a class but differ in flexibility.
Can constructors be virtual in C++?
No, constructors in C++ cannot be virtual because virtual functions rely on a vtable, which is only accessible after an object is fully constructed. Since constructors are responsible for creating objects, making them virtual would contradict their purpose.
Which constructor is called first in C++?
In C++, the constructor of the base class is called first before any derived class constructors. This ensures that the base part of an object is fully constructed before initializing derived class members.
Can a class have more than one constructor?
Yes, a class in C++ can have multiple constructors, including default, parameterized, and copy constructors, to initialize objects in different ways.
Conclusion
Constructors in C++ are fundamental to the object-oriented programming paradigm, playing a crucial role in initializing objects and ensuring that they start with a valid state. Understanding the different types of constructors—default, parameterized, copy, and move—provides valuable insight into how objects are created, copied, and transferred efficiently in C++.