samedi 4 avril 2015

C++ design pattern - member-only class

I want a class that can only be instantiated as a member of another class.


Id est:



class A
{
public:
A() :
member_()
{};
void letBSayHi() { member_.sayHi(); }
private:
B member_;
};
class B
{
public:
void sayHi() { printf("hola!"); }
};


thus:



A alpha(); // valid
alpha.letBSayHi(); // # hola!
B beta(); // invalid
beta.sayHi(); // impossible


The singleton pattern obviously wouldn't work, as I want one instance of class B for every instance of class A. But any instantiation of class B other than as a class A-member should be prohibited.


Aucun commentaire:

Enregistrer un commentaire