Help with Age Class Program

Fairly simple program to calculate someones age, mostly done just can't figure out the last part. Any help is appreciated. This is my first forum post btw, I'm a noob can someone please also tell me how to format the code better and place it in that window so its more readable?


#include <iostream>

using namespace std;

class ageDefiner{
private:
double age;
double yearBorn;
double currentYear = 2016;

public: void getYearBorn (int x){

x = yearBorn;
}
double getAge(){
age = currentYear - yearBorn;
return age;
}
};

int main() {
int yearBorn;
ageDefiner A1;

cout << "What year were you born in? \n\n";
cin >> yearBorn;


cout << "You are " << A1.getAge() << " years old.\n\n";

}
Hello and welcome =)
I'm a noob can someone please also tell me how to format the code better and place it in that window so its more readable?

Read here - http://www.cplusplus.com/articles/jEywvCM9/

I'll edit this post soon.

Edit: You're definitely on the right track here. A few things to change though.

1
2
3
4
void getYearBorn(int x){

	x = yearBorn;
}

This looks more like a set function rather than a get function. Also you need to reverse the order of it.

1
2
3
4
void setYearBorn(int x){

	yearBorn = x; // like this
}

Now you just have to call it to set the year you were born -

1
2
3
cout << "What year were you born in? \n\n";
cin >> yearBorn;
A1.setYearBorn(yearBorn);


Edit 2:
Now that the year has been set for A1. You can get the age.

Full program:

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
#include <iostream>

using namespace std;

class ageDefiner{
private:
	double age;
	double yearBorn;
	double currentYear = 2016;

public: 
	void setYearBorn(int x)
	{

		yearBorn = x;
	}
	double getAge()
	{
		age = currentYear - yearBorn;
		return age;
	}
};

int main() {
	int yearBorn;
	ageDefiner A1;

	cout << "What year were you born in? \n\n";
	cin >> yearBorn;
	A1.setYearBorn(yearBorn);

	cout << "You are " << A1.getAge() << " years old.\n\n";
	
}
Last edited on
Wow thanks so much I wasn't expecting a response so fast! Thanks :D
You're very welcome! anytime =)
Topic archived. No new replies allowed.