Relationship Diagrams
Concept Definition
Relationship diagrams show how classes connect. The most important relationships for this course are inheritance, composition, aggregation, association, and dependency. Each relationship has a different meaning, so the arrow should match the real design.
A useful analogy is a university system. A department owns classrooms, a course uses a teacher, a student knows an advisor, and a report temporarily uses a printer. The diagram should make these differences visible before code hides them.
Why It Matters
Wrong relationships create wrong code. If you model Car as inheriting from Engine, the design says a car is an engine, which is false. If you model strong ownership as a weak association, cleanup and responsibility become unclear.
Relationship diagrams force you to answer two important questions: is this an is-a relationship, and who owns whom?
Syntax Block
class Derived : public Base {}; // inheritance
class Owner { Part part; }; // composition
class User { Service& service; }; // association or dependency
Explained Code
Example: Relationships in C++
#include <string> // std::string
class Shape {
public:
virtual ~Shape() = default; // base for inheritance
};
class Circle : public Shape {}; // Circle is a Shape
class Book {
private:
std::string title; // simple owned data
};
class Library {
private:
Book book; // Library strongly owns Book
};
classDiagram
Shape <|-- Circle
Library *-- Book
Course o-- Teacher
Doctor --> Patient
OrderService ..> Logger
Key Points / Rules
- Use inheritance only for true
is-arelationships. - Use composition when one object strongly owns another.
- Use aggregation for weaker whole-part relationships.
- Use association when objects know each other but ownership is not central.
- Use dependency when one class temporarily uses another.
Common Mistakes
- Using inheritance for reuse only. Reuse without substitutability often belongs to composition.
- Confusing aggregation and composition. Ask whether the part's lifetime depends on the whole.
- Drawing arrows without explaining ownership. A diagram should communicate responsibility.
- Making every relationship bidirectional. Two-way links increase coupling.
Quick Check
- Which relationship fits
LibraryowningBookobjects? - Why is
Carinheriting fromEnginea bad design?
Viva Answer
Relationship diagrams show how classes are connected. The main design choices are inheritance for is-a, composition for strong has-a, aggregation for weak has-a, association for knowing, and dependency for temporary use.