Code Snippets C/C++ Code Snippets

C++ program to demonstrate use of protected data members in inheritance.

By: IncludeHelp, On 06 OCT 2016

In this program we will learn how to use/access a protected data member inside derived class in c++ programming inheritance?

Here we are using public inheritance on two class; here based class is class A which has a protected data member p that will be accessed inside derived class class B.

Derived class’ public member function get_p() is accessing protected data member of class A.

C++ program (Code Snippet) – Demonstrate use/access of Protected Data Member inside Derived class’s Public Member Function using C++ Inheritance

Let’s consider the following example:

/*C++ program to demonstrate use of 
protected data members in inheritance*/

#include <iostream>

using namespace std;

//class definition
class A{
	private:
		int a;
	protected:
		int p;
	public:
		void get_a(int a){
			this->a=a;
		}
		void put_a(){
			cout<<"a="<<a<<endl;
		}
};
class B: public A{
	private:
		int b;
	public:
		void get_b(int b){
			this->b=b;
		}
		void get_p(int p){
			this->p=p;
		}
		void put_b(){
			cout<<"b="<<b<<endl;
		}		
		void put_p(){
			cout<<"p="<<p<<endl;
		}		
};
int main(){
	//creating object of B (derieved class)
	B objB;
	//get values of a,b and p
	objB.get_a(10);
	objB.get_b(20);
	objB.get_p(30);
	//print values of a,b and p
	objB.put_a();
	objB.put_b();
	objB.put_p();
	
	return 0;
}

Output

            a=10
            b=20
            p=30
        




Copyright © 2024 www.includehelp.com. All rights reserved.