alex
alex

Reputation: 1287

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.

Upvotes: 2

Views: 55

Answers (2)

Wintermute
Wintermute

Reputation: 44063

Make B a private nested class of A:

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

  B member_;
};

Addendum re: comment: The implementation can be separated from the declaration like this:

Header:

class A {
public:
  void letBSayHi();
private:
  class B {
  public:
    void sayHi();
  };

  B member_;
};

Source file:

void A::letBSayHi() { member_.sayHi(); }
void A::B::sayHi() { std::cout << "hola!\n"; }
//   ^^^^-- interesting part here

Upvotes: 5

Michel Billaud
Michel Billaud

Reputation: 1826

Well, if you want to include, why not?

class A {
#include "B.hpp"
...
};

Upvotes: 0

Related Questions