Oct 23, 2014 at 3:26am UTC
Hi. Whats the use of using int funct() const; in class declaration? Because my class functions work even without using const.
Also what is meaning of int& funct(); the ampersand does it return address? if so of what?
Last edited on Oct 23, 2014 at 3:42am UTC
Oct 23, 2014 at 3:52am UTC
const is used to control the ability of code to make accidental changes to data. You should declare your functions as const whenever possible, and when passing by reference you should try to pass by const T & whenever possible.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
class A{
int a;
public :
A(): a(0){}
void f0(){
//OK
this ->a++;
//OK
this ->f2();
//OK
this ->f3();
}
void f1() const {
//Error. const functions can't modify members.
this ->a++;
//Error. const functions can't call non-const functions.
this ->f2();
//OK
this ->f3();
}
void f2(){
}
void f3() const {
}
};
int main(){
A a;
const A &b = a;
//OK
a.f2();
//OK
a.f3();
//Error. Can't call non-const functions on const objects.
b.f2();
//OK
b.f3();
}
Last edited on Oct 23, 2014 at 3:52am UTC
Oct 24, 2014 at 1:38pm UTC
What the const T&? whats T?
Oct 24, 2014 at 1:49pm UTC
'T' is a common placeholder for an arbitrary type.