1. Introduction
In C++ programming, constructors are special member functions used to initialize objects. The copy constructor and parameterized constructor are two types of constructors that serve different purposes. A copy constructor initializes an object using another object of the same class, while a parameterized constructor initializes an object with specified values.
2. Key Points
1. The copy constructor creates a new object as a copy of an existing object.
2. A parameterized constructor initializes an object with given values, which can be of different types.
3. The copy constructor has only one parameter, typically a reference to the same class.
4. A parameterized constructor can have multiple parameters of various types.
3. Differences
Copy Constructor | Parameterized Constructor |
---|---|
Initializes a new object as a copy of an existing object. | Initializes a new object with specific values provided as arguments. |
Has one parameter, a reference to an object of the same class. | Can have multiple parameters of different types. |
4. Example
#include <iostream>
using namespace std;
class MyClass {
public:
int x;
// Parameterized constructor
MyClass(int val) : x(val) {}
// Copy constructor
MyClass(const MyClass &obj) {
x = obj.x;
}
};
int main() {
MyClass obj1(10); // Parameterized constructor
MyClass obj2 = obj1; // Copy constructor
cout << "obj1.x: " << obj1.x << endl;
cout << "obj2.x (copy of obj1): " << obj2.x << endl;
return 0;
}
Output:
obj1.x: 10 obj2.x (copy of obj1): 10
Explanation:
1. obj1 is created with the parameterized constructor and x is set to 10.
2. obj2 is created as a copy of obj1 using the copy constructor, so obj2.x also has the value 10.
5. When to use?
- Use the copy constructor to initialize an object as a copy of another object of the same class.
- Use a parameterized constructor to initialize an object with specific values, allowing more flexibility in object creation.
Related C++ Posts:
Difference Between Struct and Class in C++
Difference Between Pointer and Reference in C++
Difference Between null and nullptr in C++
Difference Between Array and Vector in C++
Difference Between const and constexpr in C++
Difference Between List and Vector in C++
Difference Between Function Overloading and Operator Overloading in C++
Difference Between Array and List in C++
Difference Between a While Loop and a Do-While Loop in C++
Difference Between new and malloc C++
Virtual Function vs Pure Virtual Function in C++
Compile Time Polymorphism vs Runtime Polymorphism in C++
Difference Between Shallow Copy and Deep Copy in C++
Comments
Post a Comment
Leave Comment