object defining within another class?

How would i go about getting the Person person_data in the private section of the second class;
Assume i have all the other member functions what bit of code or function would you use to set
person_data. I tried person_data()// constructor and it did not work so what do i do to define it
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
//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
};
/*
Exercise P5.2. Implement a class PEmployee that is just like the Employee class except
that it stores an object of type Person as developed in Exercise P5.1.
*/
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;// i tried this person_data("Chris" ,44)  also defining a new Person object //and setting person_data equal to that new object, and that did not work either
// could someone please just show me how to do it, also explain it like i'm 5 please
double salary;
};
Last edited on
> i tried this (...) and that did not work
when posting code, post the relevant parts. There is no point in posting code that does not cause the error.
when getting an error, post the full message. Verbatim.


1
2
3
4
5
6
7
8
PEmployee::PEmployee(string employee_name, double initial_salary):
   person_data(employee_name, 0),
   salary(initial_salary)
{}

int main(){
   PEmployee foo("Chris", 3.14);
}
Your employee constructor doesn't allow you to set the age, may consider to include an extra parameter.
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
#include <iostream>
#include <string>

class person
{
    public:
        // member initialiser list : name(name), age(age_in_yrs)
        // initialise the member 'name' with the argument 'name'
        // initialise the member 'age' with the argument 'age_in_yrs'
        person( std::string name, int age_in_yrs ) : name(name), age(age_in_yrs) { /* validate age >= 0 */ }

        // ...

    private:
        std::string name ;
        int age ;
};

class employee
{
    public:
        // member initialiser list : person_data( name, age_in_yrs ), salary(salary)
        // initialise the member 'person_data' with ( name, age_in_yrs )
        // initialise the member 'salary' with the argument 'salary'
        employee( std::string name, int age_in_yrs, double salary ) : person_data( name, age_in_yrs ), salary(salary)
        { /* validate salary > 0 */ }

        // ...

    private:
        person person_data ;
        double salary ;
};
Topic archived. No new replies allowed.