How to Write a C++ Class
By The Cherno | Full Playlist π
1. Purpose of the Log Class
π Key Idea: A Log class manages debug messages printed to the console, aiding in tracking application behavior.
- Use Case: Debugging games/apps by printing status updates, errors, or warnings.
- Advantage: Centralizes logging logic for reusability and cleaner code.
2. Basic Log Class Structure
Declaration:
class Log {
public:
// Log levels to control message severity
enum Level {
Error = 0,
Warn,
Info
};
private:
Level m_LogLevel = Info; // Default level
public:
void SetLevel(Level level) {
m_LogLevel = level;
}
void Error(const char* message) {
if (m_LogLevel >= Error)
std::cout << "[ERROR]: " << message << std::endl;
}
void Warn(const char* message) {
if (m_LogLevel >= Warn)
std::cout << "[WARNING]: " << message << std::endl;
}
void Info(const char* message) {
if (m_LogLevel >= Info)
std::cout << "[INFO]: " << message << std::endl;
}
};
3. Key Components Explained
- Enum
Level: Defines severity levels (Error,Warn,Info). - Private Member
m_LogLevel: Controls which messages are printed. - Public Methods:
SetLevel(): Sets the minimum severity level to log.Error(),Warn(),Info(): Print messages if the level is enabled.
4. Example Usage
int main() {
Log logger;
logger.SetLevel(Log::Level::Warn); // Ignore Info messages
logger.Info("App started"); // Not printed
logger.Warn("Low memory!"); // Printed
logger.Error("Critical error!"); // Printed
return 0;
}
Output:
[WARNING]: Low memory!
[ERROR]: Critical error!
5. Best Practices
- Use Enums for Levels: Avoid βmagic numbersβ for clarity.
- Conditional Logging: Check
m_LogLevelbefore printing to optimize performance. - Expandability: Add timestamps, file output, or threading in advanced versions.
6. Whatβs Next?
- Advanced Features: File logging, timestamps, thread safety.
- Optimization: Avoid performance overhead in release builds.
Cheat Sheet
| Method | Usage |
|ββββββ-|βββββββββββββββ|
| SetLevel() | logger.SetLevel(Log::Level::Warn); |
| Error() | logger.Error("Message"); |
| Warn() | logger.Warn("Message"); |
| Info() | logger.Info("Message"); |
| Full Video π | Playlist π |
π‘ Pro Tip: Start with a simple logging system and expand it as your project grows!
