CYB
CYB

Reputation: 1106

How does passing self-reference as parameter work in C++?

I'm confused about the code following, I cannot figure out why Test t as parameter in calc and return t will call Test(Test &t)? Can anyone help me to make it clear? Thanks a lot!

#include <iostream>
using namespace std;

class Test {
  public:
    Test(int na, int nb) {
        a = na;
        b = nb;
    }

    Test(Test &t) {
        a = t.a + 1;
        b = t.b + 1;
    }

    int getValue() {
        return a + b;
    }

    Test calc(Test t) {
        return t;
    }
  private:
    int a;
    int b;
};

int main() {
  Test t(1, 1);
  cout << t.calc(t).getValue() << endl;
}

Upvotes: 1

Views: 457

Answers (1)

vsoftco
vsoftco

Reputation: 56567

In the line

cout << t.calc(t).getValue() << endl;
        ^^^^^^^^^
           here

you pass t by value, not by reference (look again at the declaration Test Test::calc(Test t)) , so the argument t is being copied. The copy means an invocation of the copy constructor

Test(Test &t)

Same idea for the return t; - the (local) object being returned is copied from the local stack of the function to the return location destination.

BTW, you probably want a const for the copy ctor,

Test(const Test &t)

as in general you won't want to modify the source. Although technically you can have a copy ctor that takes its argument as non-const, see e.g. Can a copy-constructor take a non-const parameter?.

Upvotes: 5

Related Questions