Menu
How to Write a C++ Class (Example: Log Class)

How to Write a C++ Class (Example: Log Class)

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;  
    }  
};  

Video Reference πŸŽ₯


3. Key Components Explained

  1. Enum Level: Defines severity levels (Error, Warn, Info).
  2. Private Member m_LogLevel: Controls which messages are printed.
  3. 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!  

Video Reference πŸŽ₯


5. Best Practices

  1. Use Enums for Levels: Avoid β€œmagic numbers” for clarity.
  2. Conditional Logging: Check m_LogLevel before printing to optimize performance.
  3. 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!