Private? Protected? ...

Hi, I have a doubt.

Why can I Set the attribute "int X" in "Class2"?
"Class2" doesn't have the variable member "int X"
"Class2" is derived class from Class1. And "int X" was defined on "Class1", and as private, not as protected.

Thanks a lot

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

#include <iostream>
#include <cstring>
using namespace std;
class Class1 {
public:
	int GetX() { return x; }
	void SetX(int a) { x = a; }
private:
	int x;
};

class Class2 : public Class1 {
public:

private:
};

int main() {
	Class2 obj; 
	obj.SetX(12);
	cout << obj.GetX();

	cin.get();
	return 0;
}
because Class2 inherits Class1, so therefore it inherits all the properties of Class1

so it can be seen like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Class1 {
public:
	int GetX() { return x; }
	void SetX(int a) { x = a; }
private:
	int x;
};

class Class2 : public Class1 {
public:
	int GetX() { return x; }
	void SetX(int a) { x = a; }
private:
	int x;
};


and since you inherit the Class1 as public, you can access the members the same as Class1

try reading about inheritance
Last edited on
So if I inherit a Class as public (like: class Class2 : public Class1) it isn't considerated if the members declaration are privated or protected?

I don't understand the difference between "private" and "protected".

Yes, I'll read a bit more about inherence. Thanks a lot!!
Last edited on
it isn't considerated if the members declaration are privated or protected? 

Read this best answer:
http://stackoverflow.com/questions/860339/difference-between-private-public-and-protected-inheritance

I don't understand the difference between "private" and "protected"

private members can only access within the function of the class and friends of class
protected member can only access within the function of the class and derived classes
Solved. Thanks.
Topic archived. No new replies allowed.