Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, can I prevent derived class being instantiated by classes other than friends

Tags:

c++

oop

In C++, if I have a abstract base class, is it possible to prevent its derived classes being instantiated by classes other than friends that the base class knows?

like image 727
01zhou Avatar asked Jun 10 '15 03:06

01zhou


1 Answers

You can define constructors as private, just like any other function. For example:

class foo
{

friend foo *FooConstructor(void);

public:
  void Method();
  void Method2();

private:
  foo();
  foo(const &foo);
};

foo *FooConstructor(void) 
{ 
  return new foo(); 
}

This prevents a foo being created in any way, save with the FooContructor function.

like image 62
cehnehdeh Avatar answered Oct 19 '22 07:10

cehnehdeh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!