Created
April 15, 2016 07:06
-
-
Save jmkim/c441842970f955a47d39fd4654276c9f to your computer and use it in GitHub Desktop.
Access specifier example in inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
class parent | |
{ | |
protected: | |
int a; | |
public: | |
parent(const int a) : a(a) {} | |
bool is_equal(parent &p) { return p.a == a; } /* Can access protected (even private) member data in same class (p.a) */ | |
}; | |
class derived : public parent | |
{ | |
public: | |
derived(const int a) : parent(a) {} /* Call constructor of the parent class */ | |
bool is_equal(parent &p) { return p.a == a; } /* Error: Cannot access to protected member data (p.a) */ | |
}; | |
int main(void) | |
{ | |
parent a(2); | |
derived b(2); | |
std::cout << b.is_equal(a) << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment