Bahramdun Adil Bahramdun Adil - 5 months ago 15
C++ Question

Why the copy constructor called, when I return just a reference of the object c++

It is the code which I cannot figure out why it is not working the way I want, I look around the internet, but did not some good solution.

Point class:

class Point
Point(const Point &) {
cout << "copy constructor was called" << endl;
Point(int x, int y) : x(x), y(y) {
void setX(int x) {this->x = x;}
void setY(int y) {this->y = y;}
int getX() const { return x; }
int getY() const { return y; }
int x;
int y;

Circle class:

class Circle
int rad;
Point &location;
Circle(int radius, Point &location) : rad(radius), location(location) {}
int getRad() { return rad; }
Point & getLocation() { return location; }

The usage:

int main() {
Point p(23, 23);
Circle c(12, p);

Point p1 = c.getLocation();

cout << p.getX() << endl; // prints 23, which I want to be 200
// copy constructor was called

return 0;

Answer Source

In the following line:

Point p1 = c.getLocation();

p1 is not a reference, so basically you're copying the referenced object returned by getLocation(), thus calling copy constructor.

A solution would be to declare p1 as a reference like this:

Point& p1 = c.getLocation();