Returning Object Confusion

I am learning C ++, but it's hard for me to understand how objects are returned by a member function / method. I follow "Teach yourself C ++ in 21 days."

So, I understand classes and objects, not just about returning an object. I will give an example (currently studying operator overloading).

const Counter& Counter::operator++()
{
    ++itsVal;
    return *this;
}

I am just very confused about the inverse type. This method says that it should return a reference to the counter object, but when the object is dereferenced with

return *this;

Are we returning an object of class Counter? Why does the function header say that we are returning a reference to a counter object? Why doesn't the method header just say that the return type is an object of type Counter? Here I am confused: \

, , , , -, , , . , , - .

+4
4

Counter?

, . , , ( ) return.

const Counter& Counter::operator++() // return by reference (to const)
{
    ++itsVal;
    return *this;
}

Counter Counter::operator++()        // return by value. Note the body of function is the same.
{
    ++itsVal;
    return *this;
}

BTW: const ( , ) operator++ . -const . ,

Counter& Counter::operator++() // return by reference (to non-const)
{
    ++itsVal;
    return *this;
}
+5

, , , , -,

, . , . .

:

Counter c;
do_something( ++c + 5 );

++c c, :

++c;
do_something( c + 5 );

- c.

+2

return * this;

Counter?

, .

* . , . this - .

, "" .

T *t;

// ...

T u = *t;

* , , . , , . , , .

++ , '* p' , . . . , .

++ . , . , - , :

* , . : , , , , . , , .

+1

itsVal plus 1.

counter_object++ , else. , (counter_object++).func(), .

+1

Source: https://habr.com/ru/post/1653519/


All Articles