c++ - Return using this pointer vs return by value -


what difference between returning pointer , return value.

i try explain case example..

i have following code

#include <iostream> using namespace std;  class count {     private:          int count;            public:          //constructor         count():count(0) { cout << "constructor called" << endl; }          count(count& c):count(c.count)         {               cout << "copy constructor called" << endl;          }          //destructor         ~count() { cout << "destructor called" << endl; }          count  operator ++ () {             count++;             count temp;             temp.count = count;             return temp;             //return *this;          }          //display value.          void display() {              cout << "the value of count " << count << endl;          }  };  int main() { count c; count d; c.display(); d.display(); d=++c; c.display(); d.display(); return 0; } 

i have following function in class

count  operator ++ () {         count++;         count temp;         temp.count = count;         return temp; } 

when use above function, see normal constructor called when returning value.

but change function below

count  operator ++ () {         count++;         return *this; } 

the above function calls copy constructor when returning pointer.

can me understand difference.

your return *this not "return pointer". this pointer, *this not pointer, object of count type. return *this returns current value of *this value, i.e. returns copy of count object.

the return temp version same thing, unexplainable reason first stores current state of *this in local variable temp , returns temp. don't know point of doing is.

both variants same thing. both return value in case. both versions call copy constructor (at least conceptually, call can optimized out).


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

html - How can i make an element from a bottom stacking context stays in front of another higher stacking context? -

html - href attribute breaking an element -