Wednesday, November 27, 2013

Inheritance in C++


What to inherit?
In principle, every member of a base class is inherited by a derived class 
– just with different access permission
A class can be derived from more than one classes, which means it can inherit data and functions from multiple base classes. To define a derived class, we use a class derivation list to specify the base class(es). A class derivation list names one or more base classes and has the form:
class derived-class: access-specifier base-class
Access Control Over the Members
• Two levels of access control over class members
class definition inheritance type
base class/ superclass/ parent class

class Point{
protected: int x, y;
public: void set(int a, int b);
};
derived class/ subclass/ child class
class Circle : public Point{ ......
};
0 

Example 
// derived classes
#include <iostream>
using namespace std;

class CPolygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b;}
  };

class CRectangle: public CPolygon {
  public:
    int area ()
      { return (width * height); }
  };

class CTriangle: public CPolygon {
  public:
    int area ()
      { return (width * height / 2); }
  };
  
int main () {
  CRectangle rect;
  CTriangle trgl;
  rect.set_values (4,5);
  trgl.set_values (4,5);
  cout << rect.area() << endl;
  cout << trgl.area() << endl;
  return 0;
}

No comments:

Post a Comment