Help Defining a class

May 2, 2016 at 7:26pm
This is the exact problem i was giving no context. I was reading my textbook and it was suppose to teach me how to use classes. I have no idea what to do, it was poorly explained in the book. Ifsomeone could explain the steps and process like i am "5" that would be great.

Question:
Exercise P5.1. Implement all member functions of the following class:
class Person
{
public:
Person();
Person(string pname, int page);
void get_name() const;
void get_age() const;
private:
string name;
int age; // 0 if unknown
};


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
#include <iostream>
#include <string>
using namespace std;


class Person
{
public:
	Person()
	{
		name = " ";
		age = 0;
		Person::Person(name, age);
	}
	Person::Person(string pname, int page);
	string get_name() const;

private:
	string name;
	int age; // 0 if unknown
};


	
	Person::Person(string pname, int page)
	{
		cout << "Enter in the data:" << endl;
		cin >> pname >> page;
		name = pname;
		age = page;
	}
	string Person::get_name() const
	{
		return name;
	}



int main()
{
	Person First;
cout <<	First.get_name();






	return 0;
}

Last edited on May 2, 2016 at 7:28pm
May 2, 2016 at 7:55pm
Person::Person(string pname, int page)

This is a special kind of function known as a constructor. Constructor functions are run when you create an object of the class. You know it is a constructor function because it has the same name as the class.

This constructor function takes two variables, so it is called like this:

Person some_person( input_string_value, some_int_value);

The implementation should be something like this:
1
2
3
4
5
Person::Person(string pname, int page)
	{
		name = pname;
		age = page;
	}

See how I didn't have any cout or cin? There's no point to that. The function already has the parameters it needs. This constructor function gets called with those parameters.

Line 13. You're trying to call a different constructor? Why? What's that for?
Last edited on May 2, 2016 at 7:57pm
May 2, 2016 at 8:41pm
Moschops wrote:

I don't know why i put that on line 13 i was just playing with stuff to see if anything worked
May 2, 2016 at 9:58pm
That's a really bad way to program. Eventually, you'll get something that the compiler lets through, but you won't have any idea what it does.
Topic archived. No new replies allowed.