object reference

I am new to this forum concerning this great language and i have some questions concerning references:
1-why do i make a reference for and object as i can use this object directly?as
Count counter;
Count &countRef=counter;
counter.function()
countRef.function()

What is the difference between the last 2 statments.

2-For the following function , what is meant by it as i see it a lot and why it is used? int &Class::setname(int x)
{
y=x;
return y;
}
int &z=c.setname(20)
as y is a data member of a Class
why Class name and variable "z" is preceded by & ?

What is the difference between the last 2 statments.


None. You normally only use references as function parameters and return values, you can declare references inside a function, but as you just noticed it normally doesn't make too much sense.

why Class name and variable "z" is preceded by & ?


int &z is the same thing as int& z. The compiler doesn't care which you use.
thank u
for the 1st q , what i got from you is clear but for second question i want an explanation for this code
int &Class::setname(int x)
{
y=x;
return y;
}
int &z=c.setname(20)
1
2
3
4
5
int &Class::setname(int x)
{
y=x;
return y;
}


Is a member function that takes an int parameter x, sets a member y of the class "Class" to x, and returns a reference to y.

 
int &z = c.setname(20);


Calls setname on the type Class object c, with a parameter of 20, and assigns it return value to the int reference z.
but what is the difference between returning a reference to y and returning y it self.
None. But when you don't return a reference to y you do NOT return y itself, but a copy of the value that y has.
Topic archived. No new replies allowed.