C++ Beginner · Lesson 12 of 22
Structs and classes: members, methods and constructors
Bundling data and behaviour, public and private, constructors, const methods.
Estimated time · 60–90 min
Learning goals
What you will understand
- Explain structs and classes: members, methods and constructors in your own words
- Use it in a small robotics example
- Verify the result instead of assuming it worked
Understand the idea first
The mental model
A struct or class groups related data (members) with the functions that operate on it (methods). In a struct everything is public by default; in a class everything is private by default. Keep data private so that no outside code can put an object into an invalid state.
A constructor sets the starting state and can validate its arguments. Use the member initializer list (: id_{id}) to initialize members. Mark methods that do not change the object const.
Guided lesson
Work through these steps
- 1.
Read the structs and classes: members, methods and constructors example and identify what each line owns or changes.
- 2.
Create a small source file, compile with -std=c++17 and warnings enabled, and run it.
- 3.
Change one input, predict the result before running, then compare the output.
- 4.
Record one compiler or runtime error and explain the correction in your own words.
Worked example
Read it before you run it
class Motor {
// A new type that bundles motor data with its operations.
public:
// The functions below are the public interface.
Motor(int id, double max_speed) : id_{id}, max_speed_{max_speed} {}
// Constructor: initializes both members using the initializer list.
int id() const { return id_; }
// Getter; const promises it does not change the motor.
bool set_speed(double speed) {
// A method that changes state, but only for legal values.
if (speed < 0.0 || speed > max_speed_) return false;
// Reject speeds outside the allowed range.
speed_ = speed;
// Store the accepted value.
return true;
// Report success.
}
// End of set_speed.
private:
// Data below is hidden from outside code.
int id_;
// Motor number.
double max_speed_;
// Configured upper limit.
double speed_{0.0};
// Current speed, starting at zero.
};
// A class definition ends with a semicolon.What the example is doing
- 1.Read declarations from right to left: identify each value's type, name, and initial value.
- 2.Follow the data through each expression before considering syntax shortcuts.
- 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.
Watch it run · Values in memory
See what this code does
The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.
Demo for Structs and classes: members, methods and constructors. Expected result: motor 3 ok rejected
Practice code
Now type it yourself
Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice
#include <iostream>
class Motor {
public:
Motor(int id, double max_speed) : id_{id}, max_speed_{max_speed} {}
int id() const { return id_; }
// TODO: write set_speed(double speed): return false if speed is below 0 or above max_speed_, otherwise store it and return true
private:
int id_;
double max_speed_;
double speed_{0.0};
};
int main() {
Motor m{3, 1.5};
std::cout << "motor " << m.id() << (m.set_speed(1.0) ? " ok" : " fail") << '\n';
std::cout << (m.set_speed(9.0) ? "accepted" : "rejected") << '\n';
return 0;
}Expected output
motor 3 ok
rejectedStuck? Show the full solution (try it yourself first)
#include <iostream>
class Motor {
public:
Motor(int id, double max_speed) : id_{id}, max_speed_{max_speed} {}
int id() const { return id_; }
bool set_speed(double speed) {
if (speed < 0.0 || speed > max_speed_) return false;
speed_ = speed;
return true;
}
private:
int id_;
double max_speed_;
double speed_{0.0};
};
int main() {
Motor m{3, 1.5};
std::cout << "motor " << m.id() << (m.set_speed(1.0) ? " ok" : " fail") << '\n';
std::cout << (m.set_speed(9.0) ? "accepted" : "rejected") << '\n';
return 0;
}Expected result
How you know it worked
- After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
- Changing the stated input produces the result you predicted.
Practical exercise
Apply the lesson
Create a Motor class whose constructor requires an ID and a maximum speed. Add a const status() method returning a std::string and make set_speed refuse values outside the range. Test both cases.
Before you continue
- The program builds with -std=c++17 and no warnings
- You can explain the key rule without reading the example
- The normal and edge cases both have recorded results
If something goes wrong
Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.
Print the inputs and intermediate values, then check conversions, units, and collection order.