Exercise: Singleton (Inflexible)

Let’s say that there is only one social insurance institution for all people in the world [1].

Programmatically, “only one” is typically expressed with a Singleton instance:

  • There can only one instance of the type exist. That instance is created invisible to the user, somewhere during program startup.

  • The instance is made available to users through a static method (usually called instance()).

  • Users cannot instantiate its type.

  • Users cannot copy/assign objects of its type.

Implement a SocialInsurance class such that the following program can run. Take special care:

  • Uncomment the commented-out lines and make sure that they emit compiler errors.

  • There must not be a memory leak at program end.

#include "social-insurance-inflexible.h"

#include <iostream>
#include <string>


int main()
{
    std::string id("1037190666");

    SocialInsurance::instance().charge(id, 1254.60);
    SocialInsurance::instance().charge(id, 231.34);
    
    std::cout << id << " owes \"" << SocialInsurance::instance().name() << "\" " << SocialInsurance::instance().debt(id) << " Euros" << std::endl;

    // MUST NOT COMPILE
    // ================

    // explicit instantiation
    // ----------------------

    // SocialInsurance another_instance("Another Insurance");

    // copy initialization
    // -------------------

    // SocialInsurance another_instance = SocialInsurance::instance();

    // copy assignment
    // ---------------

    // another_instance = SocialInsurance::instance();

    return 0;
}

When run, the program outputs the following:

$ ./singleton-social-insurance-inflexible-main
1037190666 owes "Die einzige Sozialversicherung" 1485.94 Euros

Footnotes