0

Why do I get different results for the following two cases? I am passing by value in both cases.

Case1: using public member function: (output: 2:1)

#include <iostream>
using namespace std;

class one {
  int hrs; int mins;
public:
  void in(int h, int m)
  { hrs = h; mins = m; }
  friend void dis(one);
};

void dis(one objone)
{ cout << objone.hrs <<":"<< objone.mins << endl; }

int main ()
{
  one obj1;
  obj1.in(2, 1);
  dis(obj1);
  return 0;
}

Case2: using friend function. (output:-20704:32763)

#include <iostream>
using namespace std;

class one
{
  int hrs; int mins;
  friend void in(one);
  friend void dis(one);
};

void in(one objone)
{ objone.hrs = 2; objone.mins=1; }

void dis(one objone)
{ cout << objone.hrs <<":"<< objone.mins << endl; }

int main ()
{
  one obj1;
  in(obj1);
  dis(obj1);
  return 0;
}
Walter
  • 44,150
  • 20
  • 113
  • 196
Saideep
  • 61
  • 1
  • 6
  • Because when you pass `obj1` to `in()` you are sending a copy of the object as parameter, not the actual `obj1`, so your objects' internal fields do not get modified. Try to pass `obj1` by reference. – Polb Nov 27 '16 at 22:24
  • fair point, but even in the first case, I am passing by value and thereby it shall be working on copies only right? – Saideep Nov 27 '16 at 22:40
  • 1
    True, in the first case you are passing by value too, but the integers 1 and 2 are passed by value, whose values get caught and assigned to the internal fields of the `obj1` object. However, in the seconds case, the one passed by value is `obj1`. So this time the internal fields of the copy of `obj1` get modified, not those of the actual object. Changing the method prototype to `friend void in(one&)` and `void in(one& one)` should get it working right. – Polb Nov 27 '16 at 22:45
  • yes, I do agree if i pass by ref I should get it right, but I was just curious why I had different results.Thanks, +1. – Saideep Nov 27 '16 at 22:54

1 Answers1

1

Like the comments say, because you pass by value you are not passing the same object to the function

In(one obj) 

Will call the constructor of object one and hence will not have its internal members initialised. Pass by reference to solve your problem

In(one & obj)
TomJ
  • 424
  • 3
  • 14