C++ - Access to private member from inherited class

Hello,

I have two classes, Person and Student.

Person class:
int id;
string name;
int age;

void set_id(int);
int get_id();
void setname(string);
string getname();

Student class: inherited from Person
int stno;
void set_stno(int);
int get_sto();

Now, How can I define set_age and get_age method in Student class?

My Solution is:


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
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include<string>
using namespace std;

class person
{
private:
	int id;
	string name;
protected:
	int age;
public:
	void set_id(int);
	int get_id();
	void setname(string);
	string getname();
	virtual void set_age(int);
	virtual int get_age();
};

class student :public person
{
private:
	int stno;
public:
	void set_stno(int);
	int get_sto();
	int get_age();
	void set_age(int);
};
void student::set_stno(int no)
{
	stno = no;
}
int student::get_sto()
{
	return stno;
}
int student::get_age()
{
	return person::get_age();
}
void student::set_age(int _age)
{
	person::age = _age;
}

void person::set_age(int _age)
{
	age = _age;
}
int person::get_age()
{
	return age;
}
void person::set_id(int _id)
{
	id = _id;
}
void person::setname(string _name)
{
	name = _name;
}
int person::get_id()
{
	return id;
}
string person::getname()
{
	return name;
}



int main()
{
	student s;
	s.set_age(10);
	cout << s.get_age();

	return 0;
}

Last edited on
Why not simply:

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

class person {
private:
	int id {};
	string name;
	int age {};

public:
	void set_id(int);
	int get_id() const;
	void setname(const string&);
	string getname() const;
	void set_age(int);
	int get_age() const;
};

class student : public person {
private:
	int stno {};

public:
	void set_stno(int);
	int get_sto() const;
};

void student::set_stno(int no) { stno = no; }
int student::get_sto() const { return stno; }

void person::set_age(int _age) { age = _age; }
int person::get_age() const { return age; }
void person::set_id(int _id) { id = _id; }
int person::get_id() const { return id; }
void person::setname(const string& _name){ name = _name; }
string person::getname() const { return name; }

int main()
{
	student s;

	s.set_age(10);
	cout << s.get_age();
}


What's the difference between a person id and student stno?
Last edited on
Thank you, but I’d like to access age property in person from student.
And student inherited from person
So make age protected.
1
2
3
4
5
6
7
class person {
private:
	int id {};
	string name;
protected:
	int age {};
// ... 

Topic archived. No new replies allowed.