Frion3L
Frion3L

Reputation: 1522

Pointers and copies

I'm starting with C++ and I'm having some doubts about pointers and it's copy.

I'm going to write an example:

class Abc{
  Qwe q;
}

Abc* a = new Abc();
Abc* b = new Abc();
b->q = a->q; //??

What happen in that assignment? Is 'a' giving a copy of the 'q' to 'b'?

The problem is I would like to have diferents 'q' for both pointers and I don't know how to copy it. Is like in the example?

Thanks

Upvotes: 0

Views: 94

Answers (3)

rerun
rerun

Reputation: 25505

in this case you are accessing an unallocated pointer so the results are not defined

class Abc{
  Qwe q;
}

Abc* a = new Abc();
Abc* b = new Abc();

b->q = a->q; //This would now invoke the copy assignment or the copy constructor (depending
             // on what the compiler want to do) of class Qwe

If you wanted to control what happens you should define a copy constructor and a copy assignment operator for Abc

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727087

The answer depends on the type of Qwe. If it is a normal type, then its assignment operator will be invoked, which will do a copy in a way that is specific to your class (by default, that's a simple copy for primitives followed by copy constructors for non-primitives).

If Qwe is a typedef-ed pointer type, then a copy of that pointer will be made.

P.S. I am assuming that you assigned a and b some valid pointers to objects before dereferencing them.

Upvotes: 2

Joseph Mansfield
Joseph Mansfield

Reputation: 110768

You have undefined behaviour because you are dereferencing an uninitialized pointer. Those pointers don't actually point anywhere yet. You need to create some Abc objects for them to point at. One way to do that is:

Abc a_object;
Abc b_object;
Abc* a = &a_object;
Abc* b = &b_object;

Once you have done this, your assignment expression will copy a->q to b->q. Exactly what happens depends on the definition of Qwe (it may simply copy the value of a->q or call a copy assignment operator).

If instead, you had had a Qwe* inside your class, you would just be copying that pointer and not the object it pointed to. C++ defaults to value semantics, which means that things are copied. Even when you copy a pointer so that you get another pointer to the same object as the original, you are still copying the pointer. All you need to do to identify what is being copied is look at what is on the right hand side of the assignment. Here we can see it is a->q and we know a->q is a Qwe so the Qwe object is copied.

Upvotes: 6

Related Questions