Video Coming Soon...
57: Encapsulation
Teaching about class vs. struct more deeply, the concept of encapsulation, and the fact that it's based on a tautology that ignores the real reason it exists.
The Code
This is a totally made up straw man to show how it works, but really we need constructors (learned later) to make this work. It does demonstrate the concept.
View Source file ex57.cpp Only
#include <fmt/core.h>
#include <chrono>
#include <thread>
#include <string>
class AnnoyingPerson {
std::string name;
int age;
public:
int getAge() {
return age;
}
const std::string& getName() {
return name;
}
void setAge(int age) {
this->age = age;
}
void setName(const std::string& name) {
this->name = name;
}
};
int main(int argc, char* argv[]) {
// try doing the initialize like before to see the error
AnnoyingPerson zed;
// forced to do this, which has potential errors
zed.setName("Zed");
zed.setAge(51);
fmt::println("I am {} and I am {} years old.",
zed.getName(), zed.getAge());
}
The Breakdown
line of code- Description.
The Discussion
Blah blah.
Further Study
- Do this next.
Register for Learn C++ the Hard Way
Register to gain access to additional videos which demonstrate each exercise. Videos are priced to cover the cost of hosting.