Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C++ (http://www.programmingforums.org/forum15.html)
-   -   accessibilty class (http://www.programmingforums.org/showthread.php?t=12165)

brad sue Dec 11th, 2006 8:30 PM

accessibilty class
 
Hello,
I need to understand the accessibility of inheritance.
I have this code:
:

#include<iostream>
using namespace std;

class X {
      protected:
                    void fn() { cout << "In X::fn()\n"; }
      public:
                    X() { cout << "In X::X()\n"; }
                  virtual void print() { cout << "In X::print()\n"; fn(); }
                  virtual void fnx() { cout << "In X::fnx()\n"; }
};

class Y : protected X { // Inheritance of Y from X
        public:
                Y() { cout << "In Y::Y()\n"; }
                virtual void print() { cout << "In Y::print()\n"; fn(); }
                virtual void fny() { cout << "In Y::fny()\n"; }
};

class Z : public Y { // Inheritance of Z from Y
        public:
                Z() { cout << "In Z::Z()\n"; }
                virtual void print() { cout << "In Z::print()\n"; fn(); }
};

void foo1(X& obj) { obj.print(); }
void foo2(Y& obj) { obj.print(); }
void foo3(Z& obj) { obj.print(); }
void foo4(X obj) { obj.print(); }
 
int main() {
      X objx;
      Y objy;
      Z objz;
      foo1(objx);
      foo4(objx);
      foo2(objy);
      foo4(objy); // `X' is an inaccessible base of `Y'
      foo3(objz);
      foo4(objz); X' is an inaccessible base of `Z'

return 0;}

The error is in red on the code.
I want to understand what is happening at those errors points.
I read the documentation of accessibility rules but I am wondering why we dont have an error for
:

foo3(objz)
or the other since they all calling X::fn()
can someone help me please?

thank you
B

DaWei Dec 11th, 2006 8:38 PM

Read the definitions of "public", "private", and "protected".

brad sue Dec 11th, 2006 9:22 PM

OK relatively to protected inheritance, I quote:
"
- inherited public and protected members become protected members of the derived class.

- all the inherited members are inaccessible to the rest of the program (main & other non-memberfunctions)

- each subsequently derived class has access to the combined set of the protected and public members of the previous base classes.
(this is where I get confused in respect to the code I have.)"

why foo4(objy) would not compile?

When it calls print(),print() calls fn() since all subsequent derived class have access to the previous base class!!

grumpy Dec 12th, 2006 4:16 AM

Quote:

Originally Posted by brad sue (Post 121047)
why foo4(objy) would not compile?

Because it is being called from main(), and main() has no access to non-public attributes, base classes, or member functions of class Y.


All times are GMT -5. The time now is 1:26 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC