Re: Two C++ snippets for brainstorming
On 2011-12-02, Chariton Karamitas <chakaram@auth.gr> wrote:
// C++ test #1
Since this has been answered by others I'll skip it.
// C++ test #2
#include <iostream>
using namespace std;
class B;
class A {
protected:
int A_protected;
private:
int A_private;
public:
int A_public;
friend void A_friend(B *);
};
class B: public A {
protected:
int B_protected;
private:
int B_private;
public:
int B_public;
};
void A_friend(B *b) {
// QUESTION:
// If B inherits A as public, the expression [1] compiles
// and runs correctly.
//
// If B inherits A as private, [1] throws a compilation
// error.
//
// Common sense is that private members of class A,
// should not be accessible from an instance of class B
// no matter what the inheritance type is!
//
// What's going on here? In what way does the inheritance
// type affect the friend function?
cout << b->A_private << endl; // [1]
return;
}
int main(int argc, char *argv[]) {
return 0;
}
This is valid because b can be implicitly converted to a A*.
Chapter and verse: 11.4: Member access control
(from the C++ standard draft: 2 dec 1996. I don't have the final version
of the standard nor the newer C++11 standard but I think this'll do just
fine).
A member m is accessible when named in class N if
- m as a member of N is public, or
- m as a member of N is private or protected, and the reference occurs
in a member or friend of class N, or
- there exists a base class B of N that is accessible at the point of
reference, and m is accessible when named in class B. [Example:
class B;
class A {
private:
int i;
friend void f(B*);
};
class B : public A { };
void f(B* p) {
p->i = 1; // Okay: B* can be implicitly cast to A*,
// and f has access to i in A
-end example]
--
John Tsiombikas
http://nuclear.mutantstargoat.com/