Maxpm
Maxpm

Reputation: 25602

Private and Protected Members

I'm having trouble understanding the difference between private and protected members in a C++ class. In simple terms, what is the difference?

Upvotes: 0

Views: 2454

Answers (3)

Kristopher Johnson
Kristopher Johnson

Reputation: 82545

Protected members can be accessed by derived classes (and friends).

Private members can only be accessed by the declaring class (or by friends).

Simple example:

class Base
{
protected:
    int prot;

private:
    int priv;

public:
    int Prot() const { return prot; }
    int Priv() const { return priv; }
};

class Derived
{
public:
    void ShowProt() { cout << prot; }  // OK - prot is accessible because it is protected
    void ShowPriv() { cout << priv; }  // Compile Error - cannot access priv, which is private
    void ShowPriv2() { cout << Priv(); } // OK, because Priv() is public
};

Upvotes: 1

John Dibling
John Dibling

Reputation: 101494

protected members are accessible by derived classes. private members are not.

Generally (most of the time) members should either be private or public. It is rare and unusual to need a protected member (edit) in a well-designed system.

EDIT:

Maybe I should elaborate on why protected members can be a code-smell.

If derived classes have access to data members that other classes do not, this could be an indication that the base & derived classes are too tightly coupled. The derived classes have access to the base class' state, and therefore the base class' state is subject to corruption. If this were not the case, then there's also often no reason to just make the data members public.

Others have gone in to greater detail on this.

Here is what Stroustrup says in his text:

Members declared protected are far more open to abuse than members declared private . In particular, declaring data members protected is usually a design error. Placing significant amounts of data in a common class for all derived classes to use leaves that data open to corruption. Worse, protected data, like public data, cannot easily be restructured because there is no good way of finding every use. Thus, protected data becomes a software maintenance problem.

See also this question.

Upvotes: 6

Mark Loeser
Mark Loeser

Reputation: 18657

From the C++ FAQ:

  • A member (either data member or member function) declared in a private section of a class can only be accessed by member functions and friends of that class
  • A member (either data member or member function) declared in a protected section of a class can only be accessed by member functions and friends of that class, and by member functions and friends of derived classes
  • A member (either data member or member function) declared in a public section of a class can be accessed by anyone

Upvotes: 1

Related Questions