Function that returns object and "return *this"

Hello,

I'm trying to understand the following function (it's part of a class called "stackDouble", with a data array and size). I understand what it does, but I am a bit confused about a few things. I'm a bit iffy on the function returning it's class name by reference (i.e. stackDouble & stackDouble). I'm also iffy on "return *this", and why do you need to declare this as a pointer, and what would happen if you didn't.

Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15



const stackDouble & stackDouble::show() const{

    cout << "[" << size << "]" << endl;

    for (unsigned i = 0; i < size; i++){
    cout << " " << data[i] << endl;

    }

return *this;

}
Last edited on
The reason you have to treat this like a pointer is because really it is one. If you didn't dereference it, then you'd be trying to return a pointer to the object, which would give you an error when you try to compile your program.
I'm a bit iffy on the function returning it's class name by reference

It's not returning its class name by reference, but the instance. this is a pointer to the instance. *this is the instance itself.

In this example, there's probably no need to return the instance by reference, however returning an instance by reference is useful where a number of operations can be chained together such as with operators.
Topic archived. No new replies allowed.