📘 Lesson · Lesson 69
Copy Constructor
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.
💻 Live Code Editor
Is page ke program yahan ready hain — chalाएं, badlें aur seekhें. Bina kuch install kiye.
Powered by OneCompiler. Editor mein code apne aap aa jata hai — Run dabaakर output dekhें.
Agar load na ho to naye tab mein kholें.