On Jun 10, 3:10 pm, Shraddha <shraddhajosh...@gmail.comwrote:
As references are behaving like a constant pointer...
The behave very, very much like a constant pointer that is
implicitly dereferenced with every use (at least in an
expression).
And we can not change the value of reference once set...
You cannot change what the reference refers to. Once
initialized, the reference IS what it refers to, the value of
the reference is the value of what it refers to, and you can
certainly change that.
then how is following program
works...This program gives the output as 10 and 20....Actually I was
expecting an error....
Let's rework it converting all of the uses of a reference into
the corresponding uses of a pointer:
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
class abc
{
public:
int x;
public:
abc()
{}
abc(int y)
{
x=y;}
/*void assign(int y)
{
x=y;
} */
};
int main()
{
abc o1(10),o2(20);
abc &r=o1;
abc*const r = &o1 ;
clrscr();
cout<<r.x<<"\n\n";
r=o2;
*r = o2 ;
cout<<r.x;
getch();
return 0;
}
BTW: my systems don't have a header <conio.h>; to get clrscr()
and getch(), I have to include <termcap.h>, which is a
non-standard (but very wide spread) extention. When posting
code here, it's better to forget them.
--
James Kanze (Gabi Software) email:
ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34