Home > Back-end >  Copy constructor throws null value error in C
Copy constructor throws null value error in C

Time:12-01

(Been out of touch from cpp too long, wanted to brush up for the interview tomorrow).
Was revising Deep Copy v/s Shallow Copy. Wrote the code:


#include <iostream>

class MyClass {
public:
    unsigned int* uivar = nullptr;

    MyClass() : uivar(new unsigned int) {
        *(this->uivar) = 3;
    }

    ~MyClass() { delete uivar; }

    MyClass(const MyClass& mCopy) {
        *(uivar) = *(mCopy.uivar);
    }
};

void function(MyClass m) {
    *(m.uivar) = 4;
}

int main() {
    MyClass myClass;
    MyClass myClassCopy = myClass;
    std::cout << *(myClass.uivar) << "\n";
    std::cout << *(myClassCopy.uivar) << "\n";
    function(myClass);
    std::cout << *(myClass.uivar) << "\n";
    std::cout << "hhhh" << "\n";
    *(myClassCopy.uivar) = 5;
    std::cout << *(myClass.uivar) << "\n";
    return 0;
}

Error(-Warn): Dereferencing NULL pointer uivar at *(uivar) = *(mCopy.uivar);.
What am I missing?

CodePudding user response:

Your copy constructor is not correct, it would need to allocate its own pointer

MyClass(const MyClass& mCopy) {
    uivar = new unsigned int(*mCopy.uivar);
}
  • Related