I will tell you what happens when the return
constructor allows you to make a good example for you. I call the class called Counter
return in two ways:
return by temporary object:
// method 1 class Counter { private : int count; public : Counter() : count(0) {} int get_count(void); Counter operator++(int); }; int Counter::get_count() { return count; } Counter Counter::operator++(int) { count++; // create a temp object and assigning count value, then return. Counter temp; temp.count = count; return temp; }
return by an unnamed temporary object:
// method 2 class Counter { private : int count; public : Counter() : count(0) {} Counter(int c) : count(c) {} int get_count(void); Counter operator++(int); }; int Counter::get_count() { return count; } Counter Counter::operator++(int) { count++; // call 'Counter(int c)' constructor return Counter(count); }
main:
#include <iostream> using namespace std; int main() { Counter c1, c2; c1++; c1++; c2 = c1++; cout << "c1=" << c1.get_count() << endl; cout << "c2=" << c2.get_count() << endl; return 0; }
The result of both methods is identical, the operator return Counter(count);
in the second class
does what all three operators did in the first. this operator creates an object of type Counter
; this object has no name; he won't be long enough to be needed. this unnamed object is initialized with the value provided by the count
argument, after the nameless object is initialized with the count
value, it can be returned.
The effect of the first class
same as the second class
:
Exit:
c1= 3 c2= 3
in the expression c2 = c1++;
c1
incremented, then c2
assigned.
source share