c++ private ctor – purpose, subverting …

Q1: what are the consequences of making a class’s ctors all private?
A1a: can’t subclass.
A1b: can’t Embed in another class as a nonref field.
A1c: Outsiders can’t instantiate stack instances, and call qq(new MyClass) either — tested in my IDE. There lies a difference with private dtor —

$ A private Destructor prevents instantiation of ALL nonref like qq(Myclass myObj), either as a stack instance or as a global variable !!
$ A private Destructor prevents explicit delete of MyClass like qq(delete myPtr) but
$ A private Destructor doesn’t prevent qq(new MyClass).

See also P146 [[more eff c++]]

Now back to private ctor.
Q1b2: but how about java-style has-a? Note in java, all reference type fields live in the host object as a 32-bit pointer whereas the pointee lives outside the real estate of host object. C# struct fields live right on THAT real estate. C++ nonref fields are like c# struct.
%%A: I think a private MyClass ctor won’t affect host object instantiation because host object can use a null ptr field. Later on that ptr can reseat to a MyClass instance returned from some function.

Q: how about protected ctor?
%%A: can subclass. I think this is used mostly for virtual inheritance.

Q: what are the alternatives?
%%A: make Destructor private. See also P146 [[more eff c++]]

Q: justification?
%%A: there’s just one dtor to manage, but any number of ctor’s.

Q: if it’s not water tight, then how can it be subverted?
%%A: friends

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s