Class Object Question

closed account (365X92yv)
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.

Yes?
I don't understand you. It will be easier if you post code.
1
2
3
4
5
6
7
void foo::bar(){
//...
}
//equivalent to 
void bar(foo *this){
//...
}
closed account (365X92yv)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

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?

}


Is the object p passed in by reference?
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.

hardlinecoded wrote:
// WHEN I PRINT THIS WILL IT HAVE THE NEW VALUES OF X AND Y?


It did for me when I ran the code.
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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#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?
Last edited on
Yes, you are right.
Topic archived. No new replies allowed.