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.
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.