Video Coming Soon...
59: You Don't Need Constructors
This exercise is pending. Quick notes about this exercise:
- Talk about why C++ has the odd syntax to pre-initialize variables
- Show how you can use default initialization and designated initializers to avoid constructors.
- Talk about why you want to do this.
- Demonstrate that it's a performance gain most of the time, and show when it's not.
The Code
View Source file ex59.cpp Only
#include <fmt/core.h>
#include <chrono>
#include <thread>
#include <string>
struct SimplePerson {
std::string name;
int age{1};
int pets{_guess_pets(age)};
bool alive{true};
std::string how_alive() {
return alive ? "very alive" : "very dead";
}
void print() {
fmt::println("I am {} and I am {} years old. I have {} pets and I am {}.",
name, age, pets, how_alive());
}
private:
int _guess_pets(int age) {
return age / 10 + 1;
}
};
int main(int argc, char* argv[]) {
// try doing the initialize like before to see the error
SimplePerson baby{.name="Baby", .pets=0};
baby.print();
SimplePerson zed{.name="Zed", .age=51};
zed.print();
SimplePerson mary{.name="Mary", .age=28, .pets=1};
mary.print();
SimplePerson zombie{.name="Zombie", .age=100, .alive=false};
zombie.print();
}
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.