dear all

i am a newcomer, i read c++ book already, still so blur for private, public and protected variables, anyone can give me examples for differe from them and some explanation. thanks a lot.

LI

private variables can only be accessed by the class .

class A
{
private:
   int x;
public:
   void SetX(int n) { x = n; } // <<< this is ok
};

int main()
{
    A aobj;
    aobj.x = 0; // << error because not inside the class
}

protected is similar to private but can also be accessed by inherited classes

class A
{
protected:
   int x;
public:
   void SetX(int n) { x = n; } // <<< this is ok
};

class B : public A
{
public:
    void ShowX() { cout << A::x << "\n"; } /// this is ok
};

public can be accessed by anybody

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.