Gary
Gary

Reputation: 21

How to prevent static instances of simple C++ class objects while allowing dynamic instances

I know how to prevent dynamic instantiation of a class in C++. (Define my own 'new' operator) But is there a simple way to prevent static instantiation so that I force dynamic instances? That is, how do I do this... (This is not a derivable abstract base class. Just a simple class)

class B {

};

B b;  // how do I prevent this without using friends or some derived class trick

B* b;
b = new B;  // still want to be able to do this.

Upvotes: 2

Views: 880

Answers (2)

Don Pedro
Don Pedro

Reputation: 11

You can prevent it by making the c'tor private:
class B { ... };
Instead of b = new B; you will do: b = B::alloc();

But this is only half of the truth, right? I could still do an

static B* b = B::alloc();

yielding a pointer to a statically (i. e. created before execution of main()) object - i.e. this is more or less a static object, it only is located on the heap. Is there a way to prevent this?

Upvotes: 1

Drakosha
Drakosha

Reputation: 12165

You can prevent it by making the c'tor private:

class B {
B() {}

public:
  static B* alloc() { return new B; }
};

Instead of b = new B; you will do: b = B::alloc();

Upvotes: 13

Related Questions