C++ — Structs and const member functions
A C++ struct can hold both data and member functions. A const subtotal function reads the quantity and price without changing the line item.
A simple example
Read one field
- Start with A point with x = 2
- Do this Read x
- Result 2
#include <iostream>
int main() {
struct Point { int x; };
Point point{2};
std::cout << point.x << '\n';
}
2
Represent an invoice line
A struct exposes its fields by default. The const on subtotal promises that calling the method does not modify the object, which lets the example call it on a const line item.
A café invoice lists three juices at 125 cents each. Store the quantity and price together, then calculate the subtotal when the receipt is printed. Changing the quantity can then update the total automatically.
Run the example
C++17. Run these commands from the directory containing the example. Use a Unix-style shell.
c++ -std=c++17 lesson.cpp -o lesson
./lesson
#include <iostream>
struct LineItem {
int units;
int cents;
int subtotal() const { return units * cents; }
};
int main() {
const LineItem line{3, 125};
std::cout << line.subtotal() << '\n';
return 0;
}
375
The line holds three units at 125 cents each. Multiplication gives 375 cents. Keeping the subtotal derived means there is no third field that can become stale.
Try it yourself
Create a second line with two units at 90 cents each.
Check your answer
Its subtotal is 180 cents. The two subtotals together are 555 cents before any taxes or delivery charges.