Friendship

I have a question,

A function declared as a friend of a derived class has acces to the data member of the base class??.

Thanks

Why don't you just try it?

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
#include <iostream>

class A {
public:
    A(int val) : val(val) {}
protected:
    int val;
};

class B : public A {
public:
    B(int val) : A(val) {}
    friend void print(const B&);
};

void print(const B& b) {
    std::cout << b.val; 
}

int main()
{
    B b(3);
    print(b);

    return 0;
}

3


looks like yeah ;)
It has access to everything class B has access to which excludes private data of A
Last edited on
Ok, thanks, If val was private that function wouldn't have access then, wasn't it?
yeah, exactly.
But B doesn't have access to it either so it would be pretty weird if it would work that way :)
Topic archived. No new replies allowed.