some_math_guy
some_math_guy

Reputation: 333

copy constructor and shallow copy

I wrote the following code to see shallow copy. I was expecting v2 to be a shallow copy of v1 since no copy construtor is defined , so I was hoping that changing v1.n would also cause v2.n to change, but it didn't. What I am doing wrong?

#include<iostream>
using namespace std;
class Vector
{
  public:
  int n;
  float *v;

  Vector();

};
Vector::Vector()
{
  v = new float[100];
  n = 100;
  cout<<"Constructor called"<<endl;
}


int main()
{
  Vector v1;
  v1.n=5;
  Vector v2=v1;
  v1.n=6;
  cout <<"Vector v1 has n value: "<<v1.n<<endl;
  cout <<"Vector v2 has n value: "<<v2.n<<endl;

  return 0;
}

Upvotes: 0

Views: 62

Answers (1)

cigien
cigien

Reputation: 60238

You are not doing anything wrong, it's just that a shallow copy of an int is still a copy.

v1, and v2 have their own copies of n, and changing one won't change the other.

If you want to see the shallow copy behavior that you expect, use the pointer v. This copy only copies the pointer, not the memory it's pointing to, i.e. changing one of the values pointed at by v1.v will change the values pointed at by v2.v.

Upvotes: 1

Related Questions