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?
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.
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.
To prevent instantiation withtin the class, modify the constructor to throw error if it's invoked.
Use friend
s! 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With