sdaau
sdaau

Reputation: 38681

Printing address of temporary?

In the example below, test.cpp:

#include <iostream>
using namespace std;

class Rectangle {
  public:
    int w, h;
    Rectangle() : w(7), h(0) {} // constructor definition.
    Rectangle(int x, int y) : w(x), h(y) {} // constructor definition.
};


class MyClass {
  public:
    Rectangle trec;
    MyClass() {
    }
    Rectangle getRect() {
      return trec;
    }
};

int main() {
  MyClass a = MyClass();
  cout << &a.getRect() << endl;
}

... I get this error when compiling with gcc test.cpp -o test.exe:

test.cpp: In function ‘int main()’:
test.cpp:32:22: error: taking address of temporary [-fpermissive]
   cout << &a.getRect() << endl;

I really don't get what is temporary here - a is instantiated when the cout runs, and so a.trec should be instantiated too and have an address, and that is exactly what getRect() returns? (or does a copy get created implicitly upon return, because the return type is defined as Rectangle and not Rectangle*?)

In any case, I'm trying to inspect code originally written like this, and where a.trec is private, and so getRect() is the only thing I can use from my code - any chance to print the address of a.trec in such a context?

Upvotes: 1

Views: 72

Answers (2)

Hatted Rooster
Hatted Rooster

Reputation: 36513

Rectangle getRect() {
      return trec;
    }

Returns a copy of trec. You don't save this copy and try to take the address of a temporary, that's illegal.

You can instead return a reference(or a pointer and just don't derefence) and then print out that address:

Rectangle& getRect() {
      return trec;
    }

Upvotes: 2

NathanOliver
NathanOliver

Reputation: 181027

getRect() is defined as

Rectangle getRect() {
  return trec;
}

Even though trec is not a temporary trec is not actually what you are returning. Since you return by value you make a copy of trec and put it into the functions return. That copy is a temporary and you cannot take the address of it.

If you change the code to

Rectangle& getRect() {
  return trec;
}

or

const Rectangle& getRect() {
  return trec;
}

Now we refer to the member of a and we can take the address of that reference.

Upvotes: 7

Related Questions