tags:

views:

522

answers:

1

In Flex (and many other languages) a function/method of a class can be declared private or protected (or public). What's the difference? I have the impression it has something to do with the relationship to child classes and how things are inherited or can be called, but I'm not sure what, exactly.

+7  A: 

In general:

  • Private members can only be accessed by the class itself.
  • Protected members can only be accessed by the class itself and its descendants.
  • Public members are accessible by everyone.

Thus, visibility increases as you go from private to protected to public.

In C++, you can control how the visibility of members should be inherited to the descendants by prepending the base class name with the private, protected or public keywords, meaning you want the visibility of the base class members to be at most at that level.

class A {
private:
    int privA;
protected:
    int protA;
public:
    int pubA;

    // privA can be accessed inside class A
    // protA can be accessed inside class A
    // pubA  can be accessed inside class A
};
// pubA can be accessed by anyone

class B : public A {
    // No change to visibility of members
    // privA can't be accessed inside class B
    // protA can be accessed inside class B
    // pubA  can be accessed inside class B
};
// pubA can be accessed by anyone

class C : protected A {
    // Public members downgraded to protected
    // privA can't be accessed inside class C
    // protA can be accessed inside class C
    // pubA  can be accessed inside class C
};
// None of the members can be accessed outside class C

class D : private A {
    // Public and protected members downgraded to private
    // privA can't be accessed inside class D
    // protA can't be accessed inside class D
    // pubA  can't be accessed inside class D
};
// None of the members can be accessed outside class D

In each of the cases above, the descendant classes are of course able to introduce their own private, protected and public members.

Ates Goral