user1599964
user1599964

Reputation: 890

scope of class variable defined in a function in C++

Consider the following C++ code:

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

class CRectangle {
  int width, height;
 public:
  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/

Upvotes: 0

Views: 84

Answers (2)

Mats Petersson
Mats Petersson

Reputation: 129524

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.

Upvotes: 1

Zagatho
Zagatho

Reputation: 523

  1. Yes, it is a local variable.
  2. If you return a copy of rectres

Upvotes: 1

Related Questions