Users Online
· Guests Online: 44
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
Forum Threads
Newest Threads
No Threads created
Hottest Threads
No Threads created
Latest Articles
Articles Hierarchy
C++ Program to Demonstrate use of Protected Members in Inheritance
C++ Program to Demonstrate use of Protected Members in Inheritance
This C++ program demonstrates the use of protected members in inheritance. The Base Class has all types of members namely – Public, Private and Protected. The public members are accessible from anywhere, the private members are accessible only within class and the protected members are accessible from the base class or its derived class.
Here is the source code of the C++ program demonstrates the use of protected members in inheritance. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
-
/*
-
* C++ Program to Demonstrate use of Protected Members in Inheritance
-
*/
-
#include <iostream>
-
-
class Base {
-
private:
-
int i;
-
protected:
-
int j;
-
public:
-
int k;
-
Base(int ii = 0, int jj = 1, int kk = 2) : i(ii), j(jj), k(kk) { }
-
void printData() {
-
std::cout << "i (Private) = " << i << std::endl
-
<< "j (Protected) = " << j << std::endl
-
<< "k (Public) = " << k << std::endl;
-
}
-
};
-
-
class Derived : public Base {
-
public:
-
void changeData(void)
-
{
-
//Can access public and protected members in derived class
-
j++;
-
k++;
-
// But i++ show error
-
}
-
};
-
-
int main()
-
{
-
Derived d;
-
-
std::cout << "Before changing " << std::endl;
-
d.printData();
-
d.changeData();
-
std::cout << "After changing " << std::endl;
-
d.printData();
-
}
$ a.out Before changing i (Private) = 0 j (Protected) = 1 k (Public) = 2 After changing i (Private) = 0 j (Protected) = 2 k (Public) = 3
Comments
No Comments have been Posted.
Post Comment
Please Login to Post a Comment.