const

Feb 10, 2015 at 2:43pm
what are the diff between
1)const return_type func(){}
2) return_type func()const{}

as far I understand 1st one return type is const like const int etc.

but 2nd one is not clear to me.
so if you help me to understand 2nd on.
thanx.
Feb 10, 2015 at 2:51pm
#1: The item being returned from the function is const.
#2: The function itself is const, meaning it does not modify the calling object. IE: it can safely be called with a const object.


Example:

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
int data;

class Example
{
public:
    int& foo() const { return data; }
    const int& bar() { return data; }
};

int main()
{
    Example nc;  // a non-const object
    const Example cc;  // a const object

    // Example of #1:
    nc.foo() = 5;   // OK, return value is non-const, so we can assign it.
    nc.bar() = 5;   // ERROR, return value is const, so we can't assign it.

    // Example of #2:
    nc.foo();  // OK
    nc.bar();  // OK

    cc.foo();  // OK, object is const, but function is also const
    cc.bar();  // ERROR, object is const, so cannot call a non-const function
}
Feb 10, 2015 at 3:08pm
I can understood.
but
nc.foo() = 5;

is new.

object.funtion()=value;

plz can you explain this line.
Feb 10, 2015 at 3:13pm
foo() returns a reference (that's what the & symbol means).

A reference is basically an alias for an existing variable.

Since foo() returns a reference to 'data', nc.foo() = 5; will assign 5 to the 'data' variable.

I can't really explain in any more detail than that. Perhaps read a tutorial on references to gain a better understanding.
Feb 10, 2015 at 3:18pm
thankx;
actually I overlook the return type; so it make me difficult to understand.

once again thx.
every thing clear to me.
Topic archived. No new replies allowed.