Inheritance_demo
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 Base { | |
private: | |
int b; | |
protected: | |
int c; | |
public: | |
Base() :a(5), b(6), c(7) {} | |
int a; | |
}; | |
class Derived1 : Base { //private Inheritance | |
public: | |
void printValues() { | |
std::cout << a; //ok | |
std::cout << b; //error. 'b' is a private member in Base and therefore inaccesible to Derived1. | |
std::cout << c; //ok | |
} | |
}; | |
class Derived2 :protected Base { //protected Inheritance | |
public: | |
void printValues() { | |
std::cout << a; //ok | |
std::cout << b; //error. 'b' is a private member in Base and therefore inaccesible to Derived2. | |
std::cout << c; //ok | |
} | |
}; | |
class Derived3 :public Base { //public Inheritance | |
public: | |
void printValues() { | |
std::cout << a; //ok | |
std::cout << b; //error. 'b' is a private member in Base and therefore inaccesible to Derived3. | |
std::cout << c; //ok | |
} | |
}; | |
int main(int argc, char *argv[]) { | |
Derived1 d1; | |
std::cout << d1.a; //error. 'a' is a private member in Derived1 | |
std::cout << d1.c; //error. 'c' is a private member in Derived1 | |
Derived2 d2; | |
std::cout << d2.a; //error. 'a' is a protected member in Derived2 | |
std::cout << d2.c; //error. 'c' is a protected member in Derived2 | |
Derived3 d3; | |
std::cout << d3.a; //ok. 'a' is a public member in Derived3 | |
std::cout << d3.c; //error. 'c' is a protected member in Derived3 | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment