protected access specifier

Hello,
I have started studying classes after functions and structures.I got the meaning of public and private but I am still confused with protected data in class. Can anyone explain protected data in a class in simple words to me and give examples ? I will be glad.
Last edited on
public: anything outside the class can access it

protected: only this class and derived classes can access it

private: only this class can access 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
30
31
32
33
34
35
36
37
38
39
40

class Example
{
public:
  void foo()
  {
    pub = 0;  // all okay!
    prot = 0;
    priv = 0;
  }

public:
  int pub;
protected:
  int prot;
private:
  int priv;
};

class Derived : public Example  // Derived is a child of Example
{
public:
  void bar()
  {
    pub = 0;  // okay -- public means i can access it
    prot = 0; // okay -- protected, but I'm a child, so I can access it
    priv = 0; // ERROR -- private, I can't access it
  }
};

class SomeOtherClass // not related to Example
{
public:
  void test(Example& e)
  {
    e.pub = 0; // okay -- public
    e.prot = 0; // ERROR -- I'm not a child, can't access it
    e.priv = 0; // ERROR
  }
};


classes or functions declared as friends of a class can access that class's protected and private stuff.
thank you Disch
Topic archived. No new replies allowed.