Let's Think About This For a Second
This set is tougher than the warm-up, combining the class/object/constructor/access-specifier topics from the Advanced chapter with the pointer/reference/STL vector topics from the Intermediate chapter. The tasks involve designing a class like you would in production code, and handling pointers and memory addresses directly. Only look at the solution after trying it yourself first — bonus points if you can factor in some error-handling logic at this stage too.
Exercises
Task 1: Build a Book class with private members title (string) and price (double), along with a constructor and getter methods — then put 3 Book objects into a vector<Book> and display them with a loop. Task 2: Create an int variable and print its address using a pointer — then dereference (*) it to increase the value by 10 through the pointer, and confirm whether the original variable's value changed. Task 3: Put 10 integers into a vector<int>, then use a function that takes a reference parameter (vector<int>&) to double every value in the vector — check whether the original vector changed once the function returns.
Example Code
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Book {
private:
string title;
double price;
public:
Book(string t, double p) : title(t), price(p) {}
string getTitle() const { return title; }
double getPrice() const { return price; }
};
void doubleValues(vector<int>& nums) {
for (int& n : nums) {
n = n * 2;
}
}
int main() {
// Task 1
vector<Book> books;
books.push_back(Book("C++ Basics", 8.5));
books.push_back(Book("STL Guide", 12.0));
books.push_back(Book("OOP in Depth", 15.75));
for (const Book& b : books) {
cout << b.getTitle() << " - $" << b.getPrice() << "\n";
}
// Task 2
int score = 90;
int* ptr = &score;
cout << "Address: " << ptr << ", Value: " << *ptr << "\n";
*ptr += 10;
cout << "Updated score: " << score << "\n";
// Task 3
vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
doubleValues(nums);
for (int n : nums) cout << n << " ";
cout << "\n";
return 0;
}After running Task 2, you'll confirm that score's original value of 90 became 100 through pointer dereferencing; after running Task 3, you'll see that every value in the nums vector has doubled.5-Minute Try It
Write another function, sortByPrice(vector<Book>& books), for Task 1's Book class — borrow the idea from the Student Manager project and apply std::sort() with a lambda comparator.
A Quick Word of Caution
Don't confuse pointer arithmetic (ptr + 10) with dereferencing (*ptr += 10) — changing the pointer itself only changes the address, while changing the value always requires * (dereference).