
- Forum
- Programming Talk
- C and C++
- inheritance in cpp
inheritance in cpp
This is a discussion on inheritance in cpp within the C and C++ forums, part of the Programming Talk category; whenever i go for any inheritence program even simple single inheritence.i face problem in implementing modifer private ,public and protected. ...
-
03-21-2011, 03:30 PM #1
- Join Date
- Mar 2011
- Answers
- 1
inheritance in cpp
whenever i go for any inheritence program even simple single inheritence.i face problem in implementing modifer private ,public and protected. can anyone help me with example from beginning???
-
To put it short and sweet, here's what could be said about access specifiers:
Public members can be accessed by anybody.
Private members can only be accessed by member functions of the same class. Note that this means derived classes can not access private members.
The protected access specifier restricts access to member functions of the same class, or those of derived classes.
Simple example:
However, you need to also look into the method of inheritance which could change the access of the members.Code:class ClassA { public: int m_nPublic; // can be accessed by anybody private: int m_nPrivate; // can only be accessed by ClassA member functions (but not ClassB classes) protected: int m_nProtected; // can be accessed by ClassA member functions, or ClassB classes. }; class ClassB: public ClassA { public: ClassB() { // ClassB's access to ClassA members is not influenced by the type of inheritance used, // so the following is always true: m_nPublic = 1; // allowed: can access public ClassA members from ClassB class m_nPrivate = 2; // not allowed: can not access private ClassA members from ClassB class m_nProtected = 3; // allowed: can access protected ClassA members from ClassB class } }; int main() { ClassA cClassA; cClassA.m_nPublic = 1; // allowed: can access public members from outside class cClassA.m_nPrivate = 2; // not allowed: can not access private members from outside class cClassA.m_nProtected = 3; // not allowed: can not access protected members from outside class }

Reply With Quote





