All are from C++ faqs
The situation is similar to personal secrets (shared only with friends), family secrets (shared with friends and children), and nonsecrets (shared with anybody), respectively.
A private: member of a class is accessible only by members and friends of the class.
A protected: member of a class is accessible by members and friends of the class and by members and friends of derived classes, provided they access the base member via a pointer or a reference to their own derived class.
A public: member of a class is accessible by everyone.
class base{
private:
int m;
protected:
int i, j;
void get(int c, int d){i=c; j=d;}
public:
void set(int a, int b){i=a; j=b;}
};
class derived:public base{//protected, private
int k;
public:
void setk(){ k = i*j;}
};
base b;
derived d;
b.i = 1; // wrong
d.i = 1; // wrong
b.m = 2; // wrong
d.k = 2; // wrong
b.get(2,3); // wrong
b.set(2,3); // OK
d.set(3,4); // OK, wrong if using 'protected'
d.setk(); // OK
How can a class Y get the bits of an existing class X without making Y a kind-of X?
class X {
public:
void f() throw();
void g() throw();
private:
int a_;
float b_;
};
class Y1 {
public:
void f() throw();
protected:
X x_;
};
void Y1::f() throw()
{ x_.f(); }
No comments:
Post a Comment