Access Class Member

Let's say there are 3 classes A, B and C.
B is inherited from A.
C is a friend class of B.

Can C access member functions of A?
From C you can only access member functions that are declared public or protected. With protected members, you can only access them with a B object.

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
41
42
43
44
45
46
#include <iostream>
class A
{
private:
    void APrivate() { std::cout << "APrivate\n"; }
protected:
    void AProtected() { std::cout << "AProtected\n"; }
};

class B : public A
{
    friend class C;
};

class C
{
public:
    void CPublic()
    {
        B bObject;

        std::cout << "CPublic calling AProtected\n";
        bObject.AProtected();

        // Can't do this, APrivate is private to A
        //bObject.APrivate();

        A aObject;
        // Can't do this, you must use a B object to
        // access protected methods
        //aObject.AProtected();
    }
};

int main()
{
    C cobj;
    cobj.CPublic();

    B bobj;
    // Can't do this, 'main' isn't a friend of B
    // bobj.AProtected();

    return 0;
}
Topic archived. No new replies allowed.