constructor inheritance c++ code example

Example 1: inheritance protected in c++

class base 
{
	public:
		int x;
	protected:
		int y;
	private:
		int z;
};

class publicDerived: public base
{
	// x is public
	// y is protected
	// z is not accessible from publicDerived
};

class protectedDerived: protected base
{
	// x is protected
	// y is protected
	// z is not accessible from protectedDerived
};

class privateDerived: private base
{
	// x is private
	// y is private
	// z is not accessible from privateDerived
}

Example 2: ambiguity in inheritance c++

#include<iostream.h>
       #include<conio.h>

       class ClassA
       {
              public:
              int a;
       };

       class ClassB : public ClassA
       {
              public:
              int b;
       };
       class ClassC : public ClassA
       {
              public:
              int c;
       };

       class ClassD : public ClassB, public ClassC
       {
              public:
              int d;
       };

       void main()
       {

			  ClassD obj;

			  //obj.a = 10;                   //Statement 1, Error occur
			  //obj.a = 100;                 //Statement 2, Error occur

			  obj.ClassB::a = 10;        //Statement 3
			  obj.ClassC::a = 100;      //Statement 4

			  obj.b = 20;
			  obj.c = 30;
			  obj.d = 40;

			  cout<< "\n A from ClassB  : "<< obj.ClassB::a;
			  cout<< "\n A from ClassC  : "<< obj.ClassC::a;

			  cout<< "\n B : "<< obj.b;
			  cout<< "\n C : "<< obj.c;
			  cout<< "\n D : "<< obj.d;

	   }

   Output :

              A from ClassB  : 10
              A from ClassC  : 100
              B : 20
              C : 30
              D : 40

Tags:

Cpp Example