& in a declaration, in c++, means that the object is passed in as a reference.
Code:
void foo (int &bar)
{
bar=3;
}
This code defines a function (foo) that takes an int reference (bar) as its only parameter. Since it's a reference, the int variable passed to this function will be set to 3 when the function exits. That is,
Code:
int baz;
foo( baz );
printf( "%d", baz );
will ouput the number 3.
References are basically pointers, except with object semantics. They have most of the advantages of pointers (not making copies, ability to send data back), and the advantages of values (simpler syntax, shouldn't have to check for null) all in one.
& used in a statement (not in a declaration), is the address-of operator, and simply returns the address of the object that it is used with.
Code:
int bar;
printf( "%u", &bar );
This will print the address of the variable bar (if it compiles, I don't know if that code is safe or not and haven't compiled it).
The real problem you're having is in this code:
Code:
ratio(ratio &x) //showing the garbage value when i use this is it pointer
{
x.num=this->num;
x.den=this->den;
}
In class of name 'foo', a method with the name of the class is a constructor. A constructor builds the class, does whatever initialization you want it to do, and then returns your newly constructed object.
In this case, you're not initializing your class (that is, the "this" pointer)... you're changing the values of the passed-in parameter (x). Now, you can do this, but the problem is that you're using uninitialized data (the local members of the ratio being constructed), which is a bad thing!
If you're trying to build your new ratio object, copying the old one, this code would do that.
Code:
ratio(ratio &x)
{
num = x.num; // this->num and num are the same thing, since we're
// in a member method/constructor
den = x.den
}
though I'd make x const on principle.
The following code would be a good optimization, however:
Code:
ratio(ratio &x) : //showing the garbage value when i use this is it pointer
num( x.num ),
den( x.den )
{
}
The : following the constructor signature specifies how to initialize the variables in the list following it.
If you're actually wanting to modify the ratio that you're passing, what you need to do is call your base constructor (ratio()) explicitly, as in this code:
Code:
ratio(ratio &x) :
ratio() // explicitly call base constructor to initialize num and den
{
x.num=this->num;
x.den=this->den;
}