Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagecpp
class MyClass {
public:
    MyClass();                      // Default constructor
    MyClass(const MyClass& other);  // Copy constructor
    MyClass& operator=(MyClass rhspObj); // Copy assignment operator
    ~MyClass();                     // Destructor
private:
    int* data;
    int size;
};

MyClass::MyClass() {
    size = 10;
    data = new int[size];
}

MyClass::MyClass(const MyClass& other) {
    size = other.size;
    data = new int[size];
    for (int i = 0; i < size; i++) {
        data[i] = other.data[i];
    }
}

MyClass& MyClass::operator=(MyClass rhs) {
    swap(size, rhs.size);
    swap(data, rhs.data);
    return *this;
}

MyClass::~MyClass() {
    delete[] data;
}

int main() {
    MyClass obj1;
    MyClass obj2 = obj1; // Use copy constructor
    MyClass obj3;
    obj3 = obj2;         // Use copy assignment operator
    return 0;
}

...