Saturday, December 6, 2008

C++ Code Example: Reference variable and its usage as class member

Sphere: Related Content /*
* In one of the interviews I had attended very recently, I had been asked to use
* reference variable as a class member. At that moment I was not able to answer.
* But later I found the answer and here it is
*/

#include <iostream>
using namespace std;

class RefVar
{
   int i;
   int &ra;
   public:

      //RefVar(a) : ra(i) { i = a;} // OK
      RefVar(a) : ra(i), i(a) {}; // OK
/*
      RefVar(a) {
         i = a;
         ra = i;
      } */
      // NOT OK
      /*
      RefVar(a) {
         ra = i;
         i = a;
      } */
      // NOT OK

      //RefVar(a) { ra = a ;} // NOT OK

      void getRefVar();
};

void RefVar :: getRefVar()
{
    cout << "value of ra " << ra << endl;
}

int main()
{

    int a = 7, b = 6;
    RefVar r(a);
    r.getRefVar();

    int& p = a;
    p = b;
    cout << "value of p " << p << " value of a " << a << endl;

    p = 9;

    cout << "value of p " << p << " value of a " << a << endl;

    return 0;
}

No comments: