0
#include<queue>
using namespace std;

class node {
    public:
    int data;
    node* left;
    node* right;
    // node(){}
    node(int d) {
        this -> data = d;
         this -> left = NULL;
         this -> right = NULL;
    }
  
};
node buildTree() {
     cout << "Enter the data: " << endl;
     int data = 2;
    //  cin >> data;
     node r(data);
     node left(4);
    cout<<&r<<endl;
    return r;
}

int main()
{
    cout<<"print";
    node root = buildTree();
    cout<<&root<<endl;
    return 0;
}

in c++ why local variable address r and main function variable root address are same?

and when i comment left and right data member of node class then it print different!why?

enter image description here

it is output of example why local object (r) of buildtree function and main function object root address are same

it should be different.

273K
  • 29,503
  • 10
  • 41
  • 64
  • Named return value optimization is being implemented here. That optimization allows `buildTree` to directly initialize `root` and avoid making a copy. – Miles Budnek Mar 27 '23 at 05:25
  • Read [C++ copy elision](https://en.cppreference.com/w/cpp/language/copy_elision) (specially _NRVO_, which is happening in your case). If you are using `g++` or `clang++` compiler, compile your program with `-fno-elide-constructors` option and run and check output. – H.S. Mar 27 '23 at 05:33
  • can anyone explain me how it works? – Niravkumar Butani Mar 27 '23 at 14:18
  • The root variable in main and the r variable in buildTree never exist at the same time, so their memory is reused. – Raymond Chen Mar 27 '23 at 14:55
  • no, its becuse of NRVO in c++ – Niravkumar Butani Mar 27 '23 at 19:14

0 Answers0