Inheritance derived from, inherit, base classes

Base and Derived Classes

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

#include <iostream>
 
using namespace std;

// Base class
class Shape {
   public:
      void setWidth(int w) {
         width = w;
      }
      void setHeight(int h) {
         height = h;
      }
      
   protected:
      int width;
      int height;
};

// Derived class
class Rectangle: public Shape {
   public:
      int getArea() { 
         return (width * height); 
      }
};

int main(void) {
   Rectangle Rect;
 
   Rect.setWidth(5);
   Rect.setHeight(7);

   // Print the area of the object.
   cout << "Total area: " << Rect.getArea() << endl;

   return 0;
}
run by http://www.cpp.sh/

Access public protected private

Same class Yes Yes Yes
Derived classes    Yes        Yes          No  
Outside classes yes No No

Multiple Inheritance

class derived-class: access baseA, access baseB....



https://www.tutorialspoint.com/cplusplus/cpp_inheritance.htm



posted @ 2019-05-16 10:00  Poission  阅读(207)  评论(0编辑  收藏  举报