Click here to Skip to main content
15,921,210 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
Hi, i'm new at c++. There is one thing I can't understand. What do * or & before class method name mean? Also I have seen it after simple functions. For example, here class method returns the this pointer, but what is “&” for? Also what is const for if this class method changes object?
C++
const Counter& Counter::operator++()
   {
       ++itsVal;
       return *this;
    }
Posted
Updated 27-Feb-12 8:08am
v4

This is not just "before class", rather, this is the part of the specification of the return type of the operator "++".

You you have a type SomeType, the notation SomeType& means another type, "a reference to the instance of the type SomeType", and the consts makes the constant-modified variant the the same type, that is, the notation const SomeType& means "a reference to the instance of the type SomeType; and the instance cannot be modified through this reference".

This const modification can be considered as syntactic sugar and a fool-proof feature protecting the variable of the type const SomeType& from modification of the instance, but the value of the variable itself can be modified, as you can assign a different reference of the same type to it later on.

C++ references are well explained here, with their semantics and usage:
http://en.wikipedia.org/wiki/Reference_%28C%2B%2B%29[^].

—SA
 
Share this answer
 
v2
It isn't a '*' or an '&' before a method name, it's a '*' or an '& after a type.

For example:
C++
int * fun(int p)
   {
   }
Is saying that the function called "fun" returns a pointer to an integer. The '*' refers to the int not the fun. The same applies for '&': it would return a reference to an integer.

In the example you give, teh class method does not "return the this pointer" - it returns a reference to the item this points at (the instance of the class) - see the '*' before this?
 
Share this answer
 
Comments
infogirl 27-Feb-12 15:35pm    
So if i write for example like this, that doesn't mean i return a pointer..?
int function()
{
.....
return *p;
}


And if i want to return a ponter to int, i have to write like that..?
int * function()
{
.....
return p;
}
Chuck O'Toole 27-Feb-12 16:10pm    
Depends on the definiton of "p". For you example to do just what you ask, p would itself have to be a pointer to an int.
int *p;
OriginalGriff 28-Feb-12 3:53am    
Chuck is right - it depends on the definition of "p"
If you have a global defined as:
int pvalue = 6;
int* p = &pvalue;
then your comments are right, because in your first example, *p gets the value of pvalue from it's address stored in the pointer p. In your second example, it returns the address of pvalue, as stored in the pointer p

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900