Frion3L
Frion3L

Reputation: 1522

Copy and pointers

I have a doubt about the copy assignment and pointers.

I will show it as an example:

class Abc 
{      
public:
  Abc() { q = new Qwe;}
  Qwe* GetQwe() { return q; }

private:

  Qwe* q;
};

Abc* a = new Abc();
Qwe* aux = a->GetQwe();
aux->Modify();

I don't know if when I call GetQwe, it is returning a copy of the value of q but not in the same memory position as q.

So my question is, would the q from Abc be modified?

Upvotes: 1

Views: 104

Answers (3)

ForEveR
ForEveR

Reputation: 55887

It returns a copy of the pointer. This copy points to the same object in memory to which the original pointer q points. So, pointer q will not be modified, BUT pointee will.

Upvotes: 3

alexrider
alexrider

Reputation: 4463

So my question is, would the q from Abc be modified?

No q itself will not be modified, GetQwe() will return copy of pointer that still points to the same memory location as q, but object both q and aux are pointing is the same and can be modified by Modify() call. Althru you need to initialize Abc::q prior to calls its member functions.

Upvotes: 4

noelicus
noelicus

Reputation: 15055

GetQwe() returns a pointer (address) to the Qwe object. Therefore your pointer aux is pointing to the same object as p and so the call to Modify will change that single object. To have a copy then lose the * like this:

Qwe GetQweCopy() { return *p; }

Upvotes: 1

Related Questions