📘 Lesson · Lesson 69
Copy Constructor
What is a Copy Constructor?
💡 Note
A copy constructor creates a new object as a copy of an existing object.
Example
C++
#include <iostream>
using namespace std;
class Point {
public:
int x;
Point(int x) { this->x = x; }
Point(const Point &p) { x = p.x; } // copy constructor
};
int main() {
Point a(5);
Point b = a; // copy constructor called
cout << b.x; // 5
return 0;
}Output:
5
5
Types of Constructors
- Default — no parameters.
- Parameterized — takes arguments.
- Copy — copies another object.
Summary
- A copy constructor takes a reference to the same class and copies its data.
- Three types: default, parameterized, copy.
a Copy Constructor क्या है?
💡 Note
A copy constructor creates a new object as a copy of an existing object.
Example
C++
#include <iostream>
using namespace std;
class Point {
public:
int x;
Point(int x) { this->x = x; }
Point(const Point &p) { x = p.x; } // copy constructor
};
int main() {
Point a(5);
Point b = a; // copy constructor called
cout << b.x; // 5
return 0;
}Output:
5
5
Types of Constructors
- Default — no parameters.
- Parameterized — takes arguments.
- Copy — copies another object.
सारांश
- A copy constructor takes a reference to the same class and copies its data.
- Three types: default, parameterized, copy.
💻 लाइव कोड एडिटर
इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.