Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure a specific class only can create an instance of another class?

Tags:

c++

c++11

How can I restrict the instantiation of a class from only within a specific class?

I don't want to restrict it within a single file, so anonymous namespace is not an option for me.

Please note that I want to make the declaration of the to-be-restricted class visible to the entire world, just that only one specific candidate from the entire world can only instantiate it.

How can I achieve this?

like image 240
Mariners Avatar asked May 29 '17 16:05

Mariners


People also ask

Can a Java class contain an instance of another class?

Yes, that is of course possible. And it is easy to think about something where it is required. You might have a container which contains childs where the childs need a reference to the parent.

How do I restrict the number of instances of a class in Java?

Actually object is not made unless contructor is called(thats why its called as constructor) and if we make the contructor private then we can restrict the creation of object and then with factory methods we can control the creation as we want as in this case it only allows creation of 1 object.

How do you avoid the instantiation of a class by any code outside of the class in Java?

To prevent instantiation withtin the class, modify the constructor to throw error if it's invoked.


1 Answers

Use friends! Making a class Foo a friend of a class Bar means that Foo can access Bar's private members. If you make the constructor(s) private, only Foo will be able to create an instance of Bar.

struct restricted_t {
    friend struct allowed_t; // allow 'allowed_t' to access my private members
private:
    // nobody can construct me (except for my friends of course)
    restricted_t() = default;
};

struct allowed_t {
    restricted_t yes; // ok
};

struct not_allowed_t {
    restricted_t no; // not ok
};

int main() {
    allowed_t a; // ok, can access constructor
    not_allowed_t b; // error, constructor is private
}
like image 123
Rakete1111 Avatar answered Sep 22 '22 17:09

Rakete1111