Karlo Kampić
Karlo Kampić

Reputation: 11

How to use & modifier on a parameter in a C++Function call

I've been given a task for my cpp homework, the task is long and has many more functions that this, but I am stuck at the beggining. What I am trying to do here is just write out the point that is given on the screen.

#include <iostream>
using namespace std;

class Point {
public:
    double x, y;
    Point(){
        x=0.0;
        y=0.0;
    };
    Point(double x,double y){
        this -> x = x;
        this -> y = y;
    }
    void print() {
        cout << "(x,y) = ("<< x <<","<< y <<")"<<endl;
    }
};

class Triangle {
public:
    Point A;
    Triangle(const Point& p1){
        A.x = p1.x; 
        A.y = p1.y;
    }

    void print1(){
        cout << "A(x,y) = ("<< A.x <<","<< A.y <<")"<<endl;
    }
};

int main(){
    Triangle A{1.0,2.0};
    A.print1();
    return 0;
}

What my thinking here is, I have a class named Point and it is made of two variables x and y, class Triangle in the task has 3 points, but I am using just one for simplicity, it has a point that is from class Point (so it should have x and y coordinates) and a constructor that has a point from class Point also. I was thinking just to link their x and y coordinates and to print them out. But it doesn't work like that, can you help me. I have more code from the task if you need, and code from our lessons. Thank you.

Upvotes: 0

Views: 148

Answers (1)

user4581301
user4581301

Reputation: 33952

Triangle(const Point& p1) accepts a const reference to a Point. A reference is an alias to an existing variable. In this case rather than copying in a Point, the Triangle constructor receives the Point itself. The const is important because it is a promise that the Point will not be modified inside by Triangle's constructor. This allows you to pass in a reference to a temporary Point that otherwise would not be around long enough for modification to be meaningful and is rejected by the compiler to prevent possible errors.

Triangle A{1.0,2.0};

will attempt to make Triangle from two floating point values. Triangle needs a reference to a Point, so you must make that Point first.

Triangle A{ {1.0,2.0} };
          ^ ^ 
          | Construct a temporary Point from 2 floating point numbers
          Triangle constructor arguments: one Point

Unrelated improvement: Use the Member Initializer List

Triangle(const Point& p1): A{p1}{
}

Upvotes: 1

Related Questions