Reputation: 15
I have a class as follows :
class Point {
public:
Point() { cout << "\nDefault Constructor called"; }
Point(const Point &t) { cout << "\nCopy constructor called"; }
};
and in someFunction() I am trying
void someFunction()
{
Point *t1, *t2;
t1 = new Point();
t2 = new Point(*t1);
Point t3 = *t1;
Point t4;
t4 = t3;
t4 = *t1;
t4 = t3;
}
The problem I am facing is that the last three lines of code is not getting executed. Even when I am debugging on Xcode control flows directly from Point t4;
to end of the code.
why constructor not being called here as it is being call for Point t3 = *t1;
Upvotes: 1
Views: 119
Reputation: 3686
Copy constructor and assignment are two different things. 't4 = t3;'
is an assignment, not initialization. Add
Point& operator = (const Point &t) { cout << "\nAssignment called"; return *this;}
in your class and you will see they are being called.
Debugging on Xcode control flows directly from Point t4; to end of the code.
This is because there is nothing to debug in these line of code. Add the above code then you can see control flow through these lines as well.
Further, As suggested by @Craig Young
Any decent optimizer would remove those 3 lines because they have zero effect of the overall behaviour. Do something with t4
after each assignment (e.g. Give Point an x
member and call std::cout << t4.x;
) then the assignment cannot be so trivially removed by the optimizer. And you will see control flow through these lines as well.
Upvotes: 2
Reputation: 9814
t4 = t3;
is assignment, not initialization. You need the assignment operator Point & operator=(const Point&t)
to see an output, otherwise it would use the default assignment operator, which does nothing in your case:
#include <iostream>
using namespace std;
class Point {
public:
Point() { cout << "\nNormal Constructor called"; }
Point(const Point &t) { cout << "\nCopy constructor called"; }
Point & operator=(const Point&t) { cout << "\nAssignment"; return *this;}
};
int main() {
Point *t1, *t2;
t1 = new Point();
t2 = new Point(*t1);
Point t3 = *t1;
Point t4;
t4 = t3;
t4 = *t1;
t4 = t3;
return 0;
}
outputs:
Normal Constructor called
Copy constructor called
Copy constructor called
Normal Constructor called
Assignment
Assignment
Assignment
Upvotes: 2