Sponsor Area

Inheritance (Extending Classes)

Question
CBSEENCO12011716

What is the difference between the members in private visibility mode and the members in protected visibility mode inside a class? Also, give a suitable C++ code to illustrate both.

Solution

 

Private Public
Private members of a class are accessible only from within other members of the same class or from their friends. Protected members are accessible from members of their same class and from their friends, but also from members of their derived classes.
#include <iostream> 
class Example
{
public:
	int a;
	int add(); private:
	int b;
};
	int Example::add()
{
	return a+b ;
}
void main( )
{
	Example ex;
	ex.a = 10; // OK: because a is public
	ex.b = 20; // Error: because b is private
	int sum=ex.add(); // local variable
	cout << 'Sum of a + b : ' <<
}
Output: Error due to access of
private member
#include <iostream.h> 
class ExBase
{
	protected: int i, j;
};

class ExDerived : public ExBase { public:
	void show()
	{
		i=35; j=45;
		//both i & j are accessible here cout<<'Value of i '<<i; cout<<'Value of j '<<j;
	}
};
void main()
{
	ExDerived exd; exd.show();//both I and j are not accessible exd.i=50;
	exd.j=60;
}

Some More Questions From Inheritance (Extending Classes) Chapter