📘 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

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

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.
← Back to C++ Tutorial
🔗

Share this topic with a friend

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

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

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

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.