Class Diagrams
Concept Definition
A UML class diagram shows the shape of a class: its name, important data members, important methods, and visibility. In this course, visibility means whether a member is public, private, or protected. A class diagram is a design sketch, not a replacement for code.
Think of it like an architect's floor plan. The plan is not the building, but it helps you see structure before construction begins. Good diagrams also help reviewers ask better design questions.
Why It Matters
Many beginner projects fail because classes are designed only while typing code. A class diagram slows you down just enough to ask what the object owns and what operations it should expose. That prevents public data, God Classes, and random methods placed in main().
Class diagrams also help you explain your design in viva, project defense, and team discussions.
Syntax Block
class ClassName {
private:
Type field; // private data
public:
Return method(); // public behavior
};
Explained Code
Example: Diagram and C++ Class
#include <string> // std::string
class Book {
private:
std::string title; // private field shown as -title
bool available = true; // private field shown as -available
public:
explicit Book(std::string bookTitle) : title(std::move(bookTitle)) {} // constructor
void checkout() { available = false; } // public operation
void returnBook() { available = true; } // public operation
bool isAvailable() const { return available; } // public query
};
classDiagram
class Book {
-string title
-bool available
+checkout()
+returnBook()
+isAvailable() bool
}
Key Points / Rules
- Use
+for public members. - Use
-for private members. - Use
#for protected members. - Show important members, not every tiny implementation detail.
- Keep diagrams consistent with the code they describe.
Common Mistakes
- Drawing every local variable. Class diagrams show class structure, not every temporary variable.
- Making all fields public in the diagram. That usually reveals weak encapsulation.
- Adding methods that do not belong to the class responsibility. This can create a God Class.
- Letting the diagram become stale. A wrong diagram is worse than no diagram.
Quick Check
- What does
-string titlemean in the diagram? - Why should a diagram hide minor implementation details?
Viva Answer
A class diagram represents a class's name, data, behavior, visibility, and relationships. It helps explain and review OOP design before or alongside implementation.