blog icon indicating copy to clipboard operation
blog copied to clipboard

C++ Class Collaborations and UML Diagram

Open qingquan-li opened this issue 2 years ago • 0 comments

It is common for classes to interact, or collaborate, with one another to perform their operations. Part of the object-oriented design process is identifying the collaborations between classes.

Example:

UML diagram of Circle, Pizza and Pizzeria classes (The Unified Modeling Language provides a standard method for graphically depicting an object-oriented system):

UML of three Class

#include <iostream>
#include <string>

using namespace std;


class Circle {
private:
    double radius;
public:
    void setRadius(double r) {
        radius = r;
    }
    double getArea() const {
        return 3.14159 * radius * radius;
    }
};


class Pizza {
private:
    double caloriesPerSqInch;
    Circle size;
public:
    void setCaloriesPerSqInch(double cal) {
        caloriesPerSqInch = cal;
    }
    void setSize(double r) {
       size.setRadius(r);
    }
    double getCalories() {
        return size.getArea() * caloriesPerSqInch;
    }
};


class Pizzeria {
private:
    string name;
    Pizza lunchSpecial;
    Pizza dinnerSpecial;
public:
    void setCalories(double caloriesPerSqInchForLunch, double caloriesPerSqInchForDinner) {
        lunchSpecial.setCaloriesPerSqInch(caloriesPerSqInchForLunch);
        dinnerSpecial.setCaloriesPerSqInch(caloriesPerSqInchForDinner);
    }
    void setSizes(double radiusOfLunchSpecial, double radiusOfDinnerSpecial) {
        lunchSpecial.setSize(radiusOfLunchSpecial);
        dinnerSpecial.setSize(radiusOfDinnerSpecial);
    }
    double getTotalCalories() {
        return lunchSpecial.getCalories() + dinnerSpecial.getCalories();
    }
};


int main()
{
    Pizza pizza;
    pizza.setCaloriesPerSqInch(10.5);
    pizza.setSize(6);
    cout << "The calories in the pizza are: " << pizza.getCalories() << endl;

    Pizzeria pizzeria;
    pizzeria.setCalories(12, 10.5);
    pizzeria.setSizes(7, 6);
    cout << "The sum of the calories from both pizzas in the pizzeria is: "
         << pizzeria.getTotalCalories() << endl;
    return 0;
}

Output:

The calories in the pizza are: 1187.52
The sum of the calories from both pizzas in the pizzeria is: 3034.78

qingquan-li avatar Sep 22 '22 19:09 qingquan-li