Simple example of multiple inheritance functionality implemented by C++

  • 2020-06-07 04:55:41
  • OfStack

This article illustrates the multiple inheritance functionality implemented by C++. To share for your reference, specific as follows:

Multiple inheritance

1. Multiple inheritance means that a class inherits attributes of multiple base classes.

2. Constructors of derived classes under multiple inheritance must be responsible for all base class constructors at the same time.

3. Number of parameters of derived class constructors, which must satisfy the needs of multiple base class initialization.

4. Under multiple inheritance, when the derived class object is established, the system first calls the constructor of each base class in the order 1 specified when defining the derived class.

Examples of multiple inheritance:


#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
class A 
{
  private:
  float fa;
  public:
  A(float a = 0) 
  {
    fa = a;
  }
  float getdata() 
  {
    return fa;
  }
};
class B 
{
  private:
  float fb;
  public:
  B(float b = 0) 
  {
    fb = b;
  }
  float getdata() 
  {
    return fb;
  }
};
class C:public A,public B 
{
  public:
  C(int a=0,int b=0):A(a),B(b) 
  {
  }
  int sum() 
  {
    return A::getdata()+B::getdata();
  }
};
int main(int argc, char** argv) 
{
  class C c1(12,23);
  class A *a1;
  a1 = &c1;// A pointer to the base class of a derived class 
  //std::cout << c1.getdata() << std::endl;  At this time there are 2 The question of righteousness 
  std::cout << a1->getdata() << std::endl;
  std::cout << c1.B::getdata() << std::endl;
  std::cout << c1.A::getdata() << std::endl;
  return 0;
}

Output:

[

12
23
12

]

I hope this article is helpful for C++ programming.


Related articles: