Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active June 4, 2026 10:29
Show Gist options
  • Select an option

  • Save sunmeat/0454756ee7345784a2ddd1034f92e71c to your computer and use it in GitHub Desktop.

Select an option

Save sunmeat/0454756ee7345784a2ddd1034f92e71c to your computer and use it in GitHub Desktop.
C++ diamond problem (rhombus inheritance)
#include <iostream>
using namespace std;
#define PI 3.14159265358979323846
// точка
class Point {
protected:
double x;
double y;
public:
Point() {
cout << "конструктор без параметрів point\n";
x = y = 5;
}
Point(int x, int y) {
cout << "параметризований конструктор point\n";
this->x = x;
this->y = y;
}
void print() const {
cout << "Point - X: " << x << ", Y: " << y << "\n";
}
~Point() {
cout << "деструктор point\n";
}
};
// коло
class Circle : public Point {
protected:
double radius;
double area = 0;
public:
Circle() {
cout << "конструктор без параметрів circle\n";
radius = 5;
area = PI * pow(radius, 2);
}
Circle(int center_x, int center_y, int radius) : Point(center_x, center_y) {
cout << "параметризований конструктор circle\n";
this->radius = radius;
}
void print() const {
cout << x << " " << y << " " << radius << "\n";
}
~Circle() {
cout << "деструктор circle\n";
}
};
// квадрат
class Square : public Point {
protected:
double x2;
double y2;
double area;
public:
Square() {
cout << "конструктор без параметрів square\n";
x2 = y2 = 10;
area = abs(x2 - x) * abs(y2 - y);
}
void print() const {
cout << x << " " << y << " " << x2 << " " << y2 << "\n";
}
~Square() {
cout << "деструктор square\n";
}
};
// коло, вписане в квадрат
class SquareCircle : public Circle, public Square {
double exclusive_area = 0;
public:
SquareCircle() {
cout << "конструктор squarecircle\n";
// exclusive_area = area_ - area_; // ??? упс!
}
void print() const {
// cout << x << " " << y << " " << x2 << " " << y2 << "\n"; // ??? ще раз упс!
cout << "SquareCircle::print - помилка!\n";
}
~SquareCircle() {
cout << "деструктор squarecircle\n";
}
};
/* у сучасній методології об'єктно-орієнтованого
програмування існує три способи розв'язання цієї проблеми.
1) об'єднувати такі поля в одне поле у похідному класі - потрібен віртуальний базовий клас
// https://ravesli.com/urok-169-virtualnyj-bazovyj-klass/
2) розглядати такий конфлікт як помилку - тобто, взагалі намагатися не застосовувати множинне успадкування
3) використовувати операцію дозволу контексту для доступу до таких полів у похідному класі */
int main() {
Point point;
point.print();
cout << "\n==============================\n\n";
Circle circle;
circle.print();
cout << "\n==============================\n\n";
Square square;
square.print();
cout << "\n==============================\n\n";
SquareCircle sc;
sc.print();
cout << "\n==============================\n\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment