Classes and objects in C++ - Time & Space Complexity
When working with classes and objects, it's important to know how the time to run your program changes as you create and use more objects.
We want to see how the program's speed changes when the number of objects grows.
Analyze the time complexity of the following code snippet.
class Box {
public:
int length;
Box(int l) : length(l) {}
int getLength() { return length; }
};
void printLengths(Box boxes[], int n) {
for (int i = 0; i < n; i++) {
std::cout << boxes[i].getLength() << std::endl;
}
}
This code defines a simple class and prints the length of each Box object in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each Box object to call getLength()
- How many times: Exactly once for each object in the array (n times)
As the number of Box objects increases, the program does more work by calling getLength() for each one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to getLength() |
| 100 | 100 calls to getLength() |
| 1000 | 1000 calls to getLength() |
Pattern observation: The number of operations grows directly with the number of objects.
Time Complexity: O(n)
This means the time to run the code grows in a straight line as you add more objects.
[X] Wrong: "Creating objects or calling methods inside a loop always takes constant time no matter how many objects there are."
[OK] Correct: Each object and method call adds work, so more objects mean more time spent.
Understanding how loops over objects affect time helps you explain your code clearly and shows you know how programs scale.
"What if the getLength() method did a complex calculation instead of just returning a value? How would the time complexity change?"
Practice
class in C++?Solution
Step 1: Understand what a class represents
A class groups related data (variables) and functions (methods) to model real-world things.Step 2: Compare options with the definition
Only To group data and functions that represent a real-world concept correctly describes this purpose; others are unrelated to classes.Final Answer:
To group data and functions that represent a real-world concept -> Option AQuick Check:
Class = group data + functions [OK]
- Thinking classes only store numbers
- Confusing classes with program speed
- Believing classes replace variables
Car in C++?Solution
Step 1: Recall C++ class declaration syntax
The correct syntax is:class ClassName { };with a semicolon at the end.Step 2: Check each option
class Car { }; matches the correct syntax. Options A, C, and D have syntax errors or wrong order.Final Answer:
class Car { }; -> Option AQuick Check:
class ClassName { }; syntax [OK]
- Writing 'Car class' instead of 'class Car'
- Missing semicolon after class body
- Using parentheses after class name
class Box {
public:
int length;
void setLength(int len) { length = len; }
int getLength() { return length; }
};
int main() {
Box box1;
box1.setLength(10);
std::cout << box1.getLength();
return 0;
}Solution
Step 1: Understand the class methods
The methodsetLengthsets thelengthto 10 forbox1. The methodgetLengthreturns this value.Step 2: Trace the output statement
std::cout << box1.getLength();prints the value 10 stored inlength.Final Answer:
10 -> Option DQuick Check:
setLength(10) then getLength() = 10 [OK]
- Forgetting to call setLength before getLength
- Expecting default value 0 without initialization
- Confusing method names
class Person {
string name;
int age;
public:
void setName(string n) { name = n; }
void setAge(int a) { age = a; }
};Solution
Step 1: Check class syntax
The class ends with a semicolon, and functions have correct return types (void). Data members are private by default, which is allowed.Step 2: Check for missing includes
The code usesstringbut does not include<string>header, which is required forstd::string.Final Answer:
Missing #include <string> header -> Option CQuick Check:
Use #include <string> for string type [OK]
- Assuming private members need public keyword
- Forgetting to add semicolon after class
- Confusing function return types
class Student {
int id;
string name;
public:
Student(int i, string n) : id(i), name(n) {}
void display() {
std::cout << "ID: " << id << ", Name: " << name << std::endl;
}
};
int main() {
Student s1(101, "Alice");
s1.display();
return 0;
}What concept does this code demonstrate?
Solution
Step 1: Identify the special function in the class
The functionStudent(int i, string n) : id(i), name(n) {}is a constructor initializing the object's data members.Step 2: Check other options
There is no inheritance, no function overloading, and no static members shown.Final Answer:
Constructor initializing object data -> Option BQuick Check:
Constructor sets initial values [OK]
- Confusing constructor with regular method
- Thinking this shows inheritance
- Assuming static members without keyword
Ready to prove it?
Pass the test and this pattern moves unknown
