I have a constructor that accepts an object of type Material:
SomeClass::SomeClass( const Material& mat ) ;
However, Material allows construction by a Vector:
Material::Material( const Vector& v ) ;
Therefore, SomeClass can allow construction by a Vector:
SomeClass m( vec ) ; // valid, since vec is constructed to a Material first,
// then is passed to the SomeClass(Material) ctor
However, after “shooting myself in the foot” more than once with ctors of this type (in different classes in the same project!) I want to disallow construction of SomeClass by Vector objects directly, instead always requiring a Material to be passed instead.
Is there a way to do this? Somehow think it has to do with the explicit keyword.
You cannot do this without interfering with your ability to transparently construct
MaterialfromVector.If you make
Material‘s constructorexplicitthen you will always have to write
Material(v)in order to construct an instance. This will prevent you from instantiatingSomeClasswith aVectoraccidentally, but it will also break all expressions that evaluate to aVectorwhere aMaterialis expected.This makes sense, because by not declaring the constructor
explicityou are saying “aVectoris just as good as aMaterialno matter what the context”. You cannot then do a half-step backward and say “oh, well, except when constructing aSomeClass“.