C++ simple code, unexpected results

Hello ! My name's AswanSensei, and I'm a beginner in C++. I recently coded the little program underneath, as an introduction to classes.
However, the function supposed to modify an object from the class Person (the completelyModifyPerson void) seems not to modify what it is supposed to. Any advices ?

After using completelyModifyPerson to modify every value to 150, i get :

"Person has an age of 50 years, is 175cm high and weighs 63kg."
Which are my default values from the main func.


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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
  //============================================================================
// Name        : lab.cpp
// Author      : aswan
// Version     :
// Copyright   : 
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
using namespace std;

class Person{
private:
	int Age;
	int Height;
	int Weight;
public:
	void setAge(int x){
		Age = x;
	}
	int getAge(){
		return Age;
	}
	void setHeight(int x){
		Height = x;
	}
	int getHeight(){
		return Height;
	}
	void setWeight(int x){
		Weight = x;
	}
	int getWeight(){
		return Weight;
	}
};

void completelyModifyPerson(Person pers){
	int a;
	
	cout << "Height ?\n";
	cin >> a;
	pers.setHeight(a);
	
	cout << "Weight ?\n";
	cin >> a;
	pers.setWeight(a);
	
	cout << "Age ?\n";
	cin >> a;
	pers.setAge(a);
}

void Outputs(int x, int y, int z){
	cout << "Person has an age of " << x << " years, is " << y << "cm high and weighs " << z << "kg.\n \n";
}

int main() {
	Person Jean;
	Jean.setAge(50);
	Jean.setHeight(175);
	Jean.setWeight(63);
	completelyModifyPerson(Jean);
	int r = Jean.getAge();
	int s = Jean.getHeight();
	int t = Jean.getWeight();
	Outputs(r,s,t);

return 0;
}

Last edited on
Thats because you're passing the Person Object directly. The thing you're doing is copying the person object and editing the copy. Then it just gets deleted because the function ends.

There are multiple ways to fix that. The easyest would just be to pass Person as a reference. To do that simply edit line 38 to void completelyModifyPerson(Person& pers){!

That should do it!

Btw, try not to mix your naming conventions!
Last edited on
Hello AswanSensei,

Another solution would be to make the functions "completelyModifyPerson" and "Outouts" member functions of the class so they have direct access to the class varibles.

Andy
those king of errors occur sometimes when dealing with c++ code. C++ can sometimes get a but complicated and it can affect your code with errors. Although those errors can be detected using programs like checkmarx or others, it is recommended to try and avoid them. There are many tutorials among the web that might help you.
Good luck.
Topic archived. No new replies allowed.