I have a 'Bank' class and a 'Branch' class. 'Branch' is inherited from 'Bank'. I want to allow ONLY 'Bank' object to create new 'Branch' objects. (e.g. only citi group can open new branches of citi banks).
What is the best design pattern to achieve this?
I am currently using friend class with private constructor. but I am not sure whether it's the right way to do it.
There's your problem, you're using inheritance. You're looking for an abstract factory pattern, where the
Bank
is the branch creator, and provide access to constructor of branches only to their respective creators.This programs to an interface rather than a concrete class. So you have
Branch
pointers andBank
pointers, and don't really need to know their exact type.If you have a
Bank*
and callcreateBranch()
, you'll get aBranch*
back but it will point to a correct concrete object.