Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is copy constructor not called here?

I'm on a fast track C++ revision course. Trying to brush up some basic concepts. When I run the below program, I see two issues : 1. Copy CC is not called for some reason. 2. Program is crashing for some reason after the function testCC() exits.

Any help is appreciated !

class A
{
public:
    A() 
    {
        this->ptr = new int[10];
    }
    ~A()
    {
        delete[] ptr;
    }
    A(const A &obj)
    {
        std::cout << "Copy CC called\n";
        for (int i = 0; i < 10; i++)
        {
            ptr[i] = obj.ptr[i];
        }
    }
    void set()
    {
        for (int i = 0; i < 10; i++)
        {
            ptr[i] = rand() % 10;
        }
    }
    void print()
    {
        for (int i = 0; i < 10; i++)
        {
            std::cout << ptr[i] << " ";
        }
        std::cout << "\n";
    }
private:
    int *ptr;

};

void testCC()
{
    A a1,a2;
    a1.set();
    std::cout << "Contents of a1\n";
    a1.print();
    a2 = a1;
    std::cout << "Contents of a2\n";
    a2.print();
}
like image 805
vinit Avatar asked Sep 28 '26 08:09

vinit


1 Answers

Copy-assignment and copy-construction are not the same thing.

a2 = a1 is calling a2.operator=(a1) (copy assignment), not the copy constructor. You can define the copy-assignment operator like this, within the A class:

A & operator=(A const & obj)
{
    // Perform copy...

    return *this;
}

And either way, your copy constructor is bad (you don't initialize ptr before using it) so even if your copy constructor were being used, you would be invoking undefined behavior and probably crash.

like image 86
cdhowie Avatar answered Oct 04 '26 09:10

cdhowie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!