What is the operator= returning?

Came across a code. I am posting the snippet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Animal & Animal::operator=(const Animal & o) {
    cout << "assignment operator" << endl;
    if(this != &o) {
        _type = o._type;
        _name = clone_prefix + o._name;
        _sound = o._sound;
    }
    return *this;
}

int main( int argc, char ** argv ) {
    Animal a;
    a.print();

    const Animal b("goat", "bob", "baah");
    b.print();

    const Animal c = b;
    c.print();

    a = c;
    a.print();

    return 0;

My question: This is he pointer to the current object right? The assignment operator returns the object of Animal type right? since it is returning *this? But isn't it supposed to return address of object since its return type is Animal & ? I am not understanding this.
It is returning an address - it is returning a reference to that object. That is so that you don't unnecessarily copy objects when you don't need to. It also allows you chain the variables, i.e. a = b = c or the like.

As an example of other times when you might return an reference:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int& func() {
    static int i = 0; // it needs to still exist after the function to work right
    return i;
}

int main() {
    std::cout << func() << std::endl; // print the value
    func() = 10; // modify the reference
    std::cout << func() << std::endl;

    return 0;
}
Last edited on
Topic archived. No new replies allowed.