Thursday, 21 September 2017

Single level inheritance demo in C++

/*
 Single Level Inheritance Demo in c++ to calculate are of rectangle
*/
#include "iostream"
using namespace std;

class Shape{

 protected :
  int height, width;
 public:
  void setWidth(int ht){
   height = ht;
  }
  void setHeight(int wt){
   width = wt;
  }
};

class Rectangle: public Shape{
 public:
 int calculateArea(){
  return (height*width);
 }
 
};

int main(){
 Rectangle  rob;
 rob. setWidth(10);
 rob.setHeight(20);
 cout<<"\nArea: "<<rob.calculateArea()<<endl;
};

//*************************************
//Variations made as Shape is inherited as protected way

/*
class Shape{

 protected :
  int height, width;
 public:
  void setWidth(int ht){
   height = ht;
  }
  void setHeight(int wt){
   width = wt;
  }
};

class Rectangle: protected Shape{
 protected:
 int calculateArea(){
  setWidth(20);
  setHeight(30);
  return (height*width);
 }
 public:
  void printArea(){
   cout<<"Area: "<<calculateArea();
  }
};

int main(){
 Rectangle  rob;
// rob. setWidth(10);
// rob.setHeight(20);
 rob.printArea();
}; 
*/

/*
 OUTPUT
[pavan@localhost Unit-2-Inheritance]$ g++ Shape.cpp
[pavan@localhost Unit-2-Inheritance]$ ./a.out 

Area: 200
[pavan@localhost Unit-2-Inheritance]$ 


*/

No comments: