What is a constructor in C++?
A constructor in C++ is a special type of function that is automatically called when an object of a class is created. The main purpose of a constructor is to initialize the member variables of the class. Constructors have the same name as the class and do not have a return type.
Key Features of Constructors:
- Automatic Invocation: Constructors are called automatically when an object is created.
- No Return Type: Constructors do not have a return type, not even
void
. - Same Name as Class: The name of the constructor must be the same as the class name.
Types of Constructors in C++:
1. Default Constructor
A default constructor is a constructor that either has no parameters or has parameters with default values. If no constructor is provided by the user, C++ provides an implicit default constructor.
class MyClass { public: MyClass() { // Default constructor std::cout << "Object created!" << std::endl; } };
2. Parameterized Constructor
A constructor that takes arguments to initialize objects with specific values is known as a parameterized constructor.
class MyClass { private: int x; public: MyClass(int a) { // Parameterized constructor x = a; } };
3. Copy Constructor
A copy constructor is used to initialize a new object as a copy of an existing object. The default copy constructor performs a shallow copy, but you can define your own to perform deep copying.
class MyClass { private: int x; public: MyClass(const MyClass &obj) { // Copy constructor x = obj.x; } };
Use Cases of Constructors:
- Initialization: Constructors are primarily used to initialize object data when they are created.
- Resource Allocation: In more complex applications, constructors may allocate resources such as dynamic memory.
Example:
#include <iostream> using namespace std; class Car { public: string brand; int year; // Parameterized constructor Car(string b, int y) { brand = b; year = y; } // Display function void display() { cout << "Brand: " << brand << ", Year: " << year << endl; } }; int main() { Car car1("Toyota", 2020); car1.display(); // Outputs: Brand: Toyota, Year: 2020 return 0; }
Sources:
GET YOUR FREE
Coding Questions Catalog