C++ Stuff

Patterns

Singleton

class Singleton {
public:
    static Singleton* getInstance()
    {
        if (!instance)
            instance = new Singleton();
        return instance;
    }

    void log(std::string str)
    {
        std::cout << "In class: " << str << std::endl;
    }

private:
    Singleton() = default;
    Singleton& operator=(Singleton const& rhs) = delete;
    Singleton(Singleton const&) = delete;
    static Singleton* instance;
};

Singleton* Singleton::instance = nullptr;

int main()
{
    Singleton* singleton = Singleton::getInstance();
    singleton->log("In main! \n");

    return 0;
}

Diverse

Runtime polymorphism

  • header
  • class Base
    {
    public:
        virtual void log();
        Base();
        virtual ~Base();
    };
    
    class Derived: public Base
    {
    public:
        virtual void log() override;
        Derived();
        virtual ~Derived() override;
    };
    
  • cpp
  • void Base::log()
    {
        std::cout << "Base Method \n";
    }
    
    Base::Base()
    {
        std::cout << "Base Constructor \n";
    }
    
    Base::~Base()
    {
        std::cout << "Base Destructor \n";
    }
    
    void Derived::log()
    {
        std::cout << "Dervied Method \n";
    }
    
    Derived::Derived()
    {
        std::cout << "Derived Constructor \n";
    }
    
    Derived::~Derived()
    {
        std::cout << "Derived Destructor \n";
    }
    
  • main
  • int main()
    {
        Base *base = new Base;
        base->log();
        delete base;
    
        Base *poly = new Derived;
        poly->log();
        delete poly;
    
        return 0;
    }
    

    Shallow/Deep Copying

    Operator Overloading