What is the difference between returning a this pointer and return by value.
I will try to explain my case with a example..
I have the 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 the value.
void display() {
cout << "The value of count is " << count << endl;
}
};
int main()
{
Count C;
Count D;
C.display();
D.display();
D=++C;
C.display();
D.display();
return 0;
}
I have the following function in a class
Count operator ++ () {
count++;
Count temp;
temp.count = count;
return temp;
}
when I use the above function, I see that the normal constructor is called when returning the value.
But I change the function as below
Count operator ++ () {
count++;
return *this;
}
The above function calls the copy constructor when returning this pointer.
Can someone help me understand the difference.
Aucun commentaire:
Enregistrer un commentaire