When you pass an object that you've created into a class method, its passed in by reference, which means any changes you made will be passed out, right?
i.e
Beforehand, object with two data members, X and Y, with values of 4 and 5
Passed into class method that multiplies each data member by 10
Afterwards, object with two data members, X and Y, with new values of 40 and 50.
class Point
{
public:
int x, y;
Point(int, int);
Point();
void PointMultiply(Point);
}
void Point::PointMultiply(Point p) // HERE IS WHAT IM TALKING ABOUT
{
x = x * 10;
y = y * 10;
}
int main()
{
Point p1(4, 5);
p1.PointMultiply();
cout << p1.x << ", " << p1.y << endl; // WHEN I PRINT THIS WILL IT HAVE THE NEW VALUES OF X AND Y?
}
You are not actually passing any object to the function. p1.PointMultiply(); This will not compile because you didn't pass a point object to the function.
You could do something like this
1 2
Point p2;
p1.PointMultiply(p2);
This will pass p2 by value (not by reference) to the function.
You are not actually using p inside the function so it doesn't make much difference if you pass it by reference or not.
I think that, based on the cout statement at the end, he wanted to pass p1 to the PointMultiply() function. That's what I assumed when I compiled and ran the code (with a few fixes).
#include <iostream>
class Point
{
public:
int x, y;
Point(int, int);
Point();
void PointMultiply(Point);
};
Point::Point(int a, int b) //added the ctor
{
x=a;
y=b;
}
void Point::PointMultiply(Point p)
{
x = x * 10;
y = y * 10;
}
int main()
{
Point p1(4, 5);
std::cout << p1.x << ", " << p1.y << std::endl; //for me, this prints "4, 5"
p1.PointMultiply(p1);
std::cout << p1.x << ", " << p1.y << std::endl; //and this prints "40, 50"
return 0;
}
Looking back, I'm thinking that because the PointMultiply() function body uses bare variables, the compiler assumes that they correspond to the invoking object's x and y variables. Since this is a pointer, that's what's causing the variables to retain their new values even after the function ends?