C++ で抽象クラスを使用してインターフェイスを実装する
 
Java では、interface を使用して多重継承が実現されます。interface は、必要なレイアウトが含まれているが、抽象的であるか、メソッド本体がないため、テンプレートに似ています。
C++ に関しては、Java とは異なり、C++ は多重継承をサポートしているため、インターフェースは必要ありません。C++ では、インターフェイスの機能は抽象クラスを使用して実現できます。
C++ での抽象クラスの概念
抽象クラスは、少なくとも 1つの純粋仮想関数を持つクラスです。純粋仮想関数を宣言することのみが可能であり、その定義はありません。宣言で 0 を割り当てることによって宣言されます。
抽象クラスは、コードを再利用可能および拡張可能にするために非常に役立ちます。これは、親クラスから継承するが、固有の定義を持つ多くの派生クラスを作成できるためです。
さらに、抽象クラスはインスタンス化できません。
例:
class A {
 public:
  virtual void b() = 0;  // function "b" in class "A" is an example of a pure
                         // virtual function
};
関数の宣言中に、関数を定義しながら純粋仮想にしようとしても機能しません。
C++ を使用してプログラムに純粋仮想関数を実装する
親クラスとして shape を使用した例を考えてみましょう。形状に関しては、さまざまな種類があり、面積などのプロパティを計算する必要がある場合、計算方法は形状ごとに異なります。
shape の親クラスを継承する派生クラスとしての rectangle と triangle。次に、純粋仮想関数に、独自の派生クラスの各形状(rectangle と triangle)に必要な定義を提供します。
ソースコード:
#include <iostream>
using namespace std;
class Shape {
 protected:
  int length;
  int height;
 public:
  virtual int Area() = 0;
  void getLength() { cin >> length; }
  void getHeight() { cin >> height; }
};
class Rectangle : public Shape {
 public:
  int Area() { return (length * height); }
};
class Triangle : public Shape {
 public:
  int Area() { return (length * height) / 2; }
};
int main() {
  Rectangle rectangle;
  Triangle triangle;
  cout << "Enter the length of the rectangle: ";
  rectangle.getLength();
  cout << "Enter the height of the rectangle: ";
  rectangle.getHeight();
  cout << "Area of the rectangle: " << rectangle.Area() << endl;
  cout << "Enter the length of the triangle: ";
  triangle.getLength();
  cout << "Enter the height of the triangle: ";
  triangle.getHeight();
  cout << "Area of the triangle: " << triangle.Area() << endl;
  return 0;
}
出力:
Enter the length of the rectangle: 2
Enter the height of the rectangle: 4
Area of the rectangle: 8
Enter the length of the triangle: 4
Enter the height of the triangle: 6
Area of the triangle: 12
Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.
