OOP principles overview in C++ - Time & Space Complexity
When we use object-oriented programming (OOP), we organize code into objects and classes. It is important to understand how the time it takes to run our programs grows as we use these OOP ideas.
We want to know how the main actions in OOP affect the program's speed as the program gets bigger.
Analyze the time complexity of the following code snippet.
class Box {
public:
int length, width, height;
Box(int l, int w, int h) : length(l), width(w), height(h) {}
int volume() {
return length * width * height;
}
};
void printVolumes(Box boxes[], int n) {
for (int i = 0; i < n; i++) {
std::cout << boxes[i].volume() << std::endl;
}
}
This code defines a Box class with a method to calculate volume. Then it prints the volume of each box in an array.
- Primary operation: Looping through each box and calling the volume method.
- How many times: The loop runs once for each box, so n times.
As the number of boxes increases, the total work grows in a straight line with the number of boxes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 volume calculations and prints |
| 100 | About 100 volume calculations and prints |
| 1000 | About 1000 volume calculations and prints |
Pattern observation: Doubling the number of boxes doubles the work done.
Time Complexity: O(n)
This means the time to run grows directly with the number of boxes we process.
[X] Wrong: "Calling a method inside a loop makes the program slower in a way that changes the overall time complexity."
[OK] Correct: Each method call here does a simple calculation, so it only adds a small fixed amount of work per item. The overall time still grows linearly with the number of items.
Understanding how loops and method calls affect time helps you explain your code clearly and shows you know how programs scale. This skill is useful when discussing your designs and choices.
"What if the volume method itself contained a loop over some internal data? How would the time complexity change?"