Friendship

Nov 19, 2015 at 7:37pm
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

Nov 19, 2015 at 8:08pm
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 Nov 19, 2015 at 8:18pm
Nov 19, 2015 at 8:23pm
Ok, thanks, If val was private that function wouldn't have access then, wasn't it?
Nov 20, 2015 at 2:35pm
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.