Monday 4 February 2013

inheritance in c++


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

class more1           //base/super/parent class
{
protected:
int position;
public:
more1()      //constructor
   {
   position=0;
   }

   void forward()     //member function
   {
   position++;
   }

   void show()
   {
   cout<<"position= "<<position<<endl;;
   }
   };


class more2:public more1       //sub/derived/child class
{
public:
void backward()
   {
   position--;
   }};
                                //main body
   void main()
   {
   more2 m;
   m.show();
    //As constructor can't be inherited, but in this case, as sub class
      //has no constructor to initilize position therefore, sub class will
    //automatically call constructor of it's super class.
   m.forward();
   m.show();
   m.backward();
   m.show();

   getch();
   }

0 comments:

Post a Comment