Class objects

In class PEmployee class private section. I need to define person_data which is from the person class. I am not sure how calling the constructor works in this type of scenario?

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

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 
};
Person::Person(string pname, int page)
{
	name = pname;
	age = page;
}

class PEmployee { 
public:   PEmployee();   
		  PEmployee(string employee_name, double initial_salary);   
		  void set_salary(double new_salary);  
		  double get_salary() const;   
		  string get_name() const; 
private: 
	Person person_data;   
	double salary; };

PEmployee::PEmployee(string employee_name, double initial_salary)
	{
		salary = initial_salary;
		int age;
		cout << "Enter in the age:" << endl;
		cin >> age;
		Person temp = Person(employee_name, age);
		person_data = temp;

string PEmployee::get_name() const
{
	person_data.get_name();
	return 0;
}
int main()
{
	Person Andrew = Person("Andrew", 39);
	

	PEmployee Chris = PEmployee("Chris", 10000);
	




	return 0;
}

Last edited on
If you change your PEmployee class to rather accept the age as a parameter instead of requesting it from within the class then you could do the following:

1
2
3
4
5
6
7
8
9
10
class PEmployee { 
public:   PEmployee();   
		  PEmployee(string employee_name,  int employee_age, double initial_salary);   
		  void set_salary(double new_salary);  
		  double get_salary() const;   
		  string get_name() const; 
private: 
	Person person_data;   
	double salary;
 };


1
2
3
4
5
6
7
8
9
PEmploye::PEmployee() : person_data()
{
   salary = 0.0;
}

PEmploye::PEmployee(string employee_name,  int employee_age, double initial_salary) : person_data(emplyee_name, emplyee_age)
{
   salary = initial_salary;
}



Typically salary should also be put into the constructor initializer list same as person_data.
SIK wrote:
I am not suppose to change anything.I have to make it work with the format the class was written in
Topic archived. No new replies allowed.