Re: reference...
Shraddha wrote:
As references are behaving like a constant pointer...And we can not
change the value of reference once set...then how is following program
works...This program gives the output as 10 and 20....Actually I was
expecting an error....
#include<stdio.h>
In C++, you should prefer <cstdio> over <stdio.h>. Also, you haven't used
anything from <stdio.h>
#include<iostream.h>
This should be <iostream>. <iostream.h> is a pre-standard header.
#include<conio.h>
<conio.h> is not a standard C++ header. I assume it declares the nonstandard
functions getch() and clrscr() you are using? Remark that my computer
doesn't have <conio.h>, getch() or clrscr(), so if I want to compile your
code, I have to remove these. Try to avoid using these when posting to this
list.
class abc
{
public:
int x;
public:
abc()
{
}
abc(int y)
{
x=y;
}
Prefer:
abc(int y) : x(y) {}
This calls the constructor of x with the argument y.
/*void assign(int y)
{
x=y;
} */
};
int main()
{
abc o1(10),o2(20);
abc &r=o1;
clrscr();
cout<<r.x<<"\n\n";
change this to:
std::cout << r.x << "\n\n";
r=o2;
And this is what you are asking about. As you didn't do it yourself, the
compiler will create something like
abc& abc::operator=(const abc& rhs) {
x = rhs.x;
return *this;
}
for you. r=o2 will then call this r.operator=(o2), which sets r.x = o2.x.
cout<<r.x;
This should be:
std::cout << r.x;
You should now be aware of:
&r == &o1 is still true
o1.x is also set to the same value as o2.x.
getch();
return 0;
}
--
Robert Bauck Hamar