Print service provided by iDogiCat: http://www.idogicat.com/
home logo





Home > IT > Programming > C++ Programming > iDog's C++ Tips

iDog's C++ Tips

Controlling Instantiation of Class

Prevent instantiation by making all constructors private, and write a static function to return instances of the class. Inside this static function, you can put any control logic as you like.


class InstanciationControlable {
public:
    const static int MAX_NUM = 5;

private:
    static int count = 0;
    InstanciationControlable();
public:
    InstanciationControlable* getInstance() {
        if(count >= MAX_NUM)
            return null;

        count++;
        return new InstanciationControlable();
    }
};

Preventing Inheritance

Like the 'final' keyword in Java used on a class. The trick is to make all constructors as private.

Note that only making the default constructor private won't eventually prevent inheritance, for example, following code compiles:


class Base {
private:
    Base() {}
public:
    Base(int i) {}
};

class Derived {
public:
    Derived(int i) : Base(i) {}
};

// program using the classes

Derived d(1);

Preventing Copying of Instance

If an instance of a certain class should never be copied, then make both copy constructor and assignment operator private.


class UncopyableClass {
private:
    UncopyableClass(const UncopyableClass&);
    UncopyableClass& operator=(const UncopyableClass&);
};