0

Is it possible to make a local copy of 'this' pointer in a class function? The purpose is to then modify the copy and return it, without modifying 'this' itself.

The function looks like this:

classA classA::function() {
   classA newObject = //where I need help; 
   //modification of newObject
   return newObject;
}
avi1234
  • 63
  • 2
  • 8
  • 5
    `classA newObject = *this;`? – melpomene Jan 17 '18 at 00:18
  • 2
    Do you mean a copy of the pointer, or a copy of the object that the pointer points to? – Austin Brunkhorst Jan 17 '18 at 00:18
  • 1
    Just use `this`. Since `this` can never be modified anyway, there's no need to make a copy of it. `this = ;` will never work. – David Schwartz Jan 17 '18 at 00:19
  • @melpomene Wow I forgot all my C++. I was trying to do &this for some reason, and totally forgot that * is how you dereference a pointer. Thank you and forgive a beginner C++ programmer! – avi1234 Jan 17 '18 at 00:21
  • Try this: `classA newObject(this);` But check if don't override the default constructor. – Jorge Omar Medra Jan 17 '18 at 00:22
  • 3
    @Jorge Copy construction rarely should be provided through a pointer. –  Jan 17 '18 at 00:29
  • @user9212993 I'm agree with you. I tested my suggestion with a class of QT (`QMainWindow`) and it implements this construction but as you said: rarely should be provided through a pointer. Thanks by your comment. – Jorge Omar Medra Jan 17 '18 at 00:45

1 Answers1

6

You can create copies from this as long your class provides a copy constructor by simply dereferencing the this pointer as needed:

classA classA::function() {       
   return *this;
       // ^^^^^ Simply dereference and let the compiler do the copying
}

Ensure your class declaration follows the Rule of 3/5/zero!