Take the 2-minute tour ×

Consider the following C++ code:

// friend functions
#include <iostream>
using namespace std;

class CRectangle {
  int width, height;
  void set_values (int, int);
  int area () {return (width * height);}
  friend CRectangle duplicate (CRectangle);

void CRectangle::set_values (int a, int b) {
 width = a;
 height = b;

CRectangle duplicate (CRectangle rectparam)
   CRectangle rectres; // Defined without using new keyword. This means scope of this variable of in this function, right ?
   rectres.width = rectparam.width*2;
   rectres.height = rectparam.height*2;
   return (rectres);

int main () {
  CRectangle rect, rectb;
  rect.set_values (2,3);
  rectb = duplicate (rect);
  cout << rectb.area();
  return 0;

The variable "CRectangle rectres" is defined in the function "CRectangle duplicate".

  1. Does this mean that the scope of the variable "CRectangle rectres" is limited to the function only ? (since it has been defined without using new keyword)

  2. If answer to above question is yes, then how can it be returned (since it is a local variable) ?

Credits : Code take from : http://www.cplusplus.com/doc/tutorial/inheritance/

share|improve this question
1. Yes 2. A copy of it is returned. Note that scope and lifetime are different things. –  jrok Aug 12 '13 at 9:23

2 Answers 2

up vote 1 down vote accepted

Your question as to 1 & 2 has been adequately answered by Patrick, but I thought I could expand a bit:

The way MOST compilers work [1] when you return a struct or class object is that the calling function passes in a pointer argument (that is hidden from view) for the "return here" value. So the called function will copy the result into the place supplied by the calling code - the actual copy is done by the copy constructor of the class.

note 1: that the C++ standard doesn't say how the compiler should do this, and if the compiler can produce magical code that just moves the bits by using "The Force" from Star Wars then that is also allowed according to the standard.

share|improve this answer
  1. Yes, it is a local variable.
  2. If you return a copy of rectres
share|improve this answer

Your Answer


