📘 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

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.

Copy Constructor क्या है?

💡 Note

Copy constructor किसी मौजूद object की copy के रूप में नया 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 call होता है
    cout << b.x;   // 5
    return 0;
}
Output:
5

Constructors के Types

  • Default — no parameters।
  • Parameterized — arguments लेता है।
  • Copy — दूसरे object को copy करता है।

सारांश

  • Copy constructor same class का reference लेकर उसका data copy करता है।
  • तीन types: default, parameterized, copy।
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

\n