tags:

views:

193

answers:

3

How can I hide the default constructor from consumers? I tried to write in private but got compilation issues.

solution is:

class MyInterface
{
public:
            MyInterface(SomeController *controller) {}
};

class Inherited : public MyInterface
{

private:
            Inherited () {}
public:
            Inherited(SomeController *controller)
            {
            }

};
+1  A: 

Writing:

private:
  MyInterface();

does the trick in two ways: for a start, no-one except friends can access it, but what's better: if a friend does try to access it, the linker will complain because there is no implementation.

Same trick works for copy constructor and assignment operator.

stijn
I thought it was good practice to declare all constructors before either public or privates methods and properties were defined. This would also make it private by default, since C++ defaults to private access with class methods/properties???
bobby
indeed private by default, but by explicitly writing it like the way above, you tell the reader 'hey this constructor is private, don't even think of using it'.Apart form that, the compiler still generates the default (private) constructor if you do not declare it.
stijn
+9  A: 

In your case, since you have already provided a constructor that takes one parameter SomeController*, compiler doesn't provide any default constructor for you. Hence, default constructor is not available.

ie,

MyInterface a;

will cause compiler to say no appropriate constructor.

If you want to make constructor explicitly not available then make the same as private.

EDIT for the code you have posted:

  • You need to call base class MyInterface constructor (with single parameter) explicitly. Otherwise, by default the derived class constructor ( Inherited) will look for Base class default constructor which is missing.

    class Inherited : public MyInterface { private: Inherited (); public:

        Inherited(SomeController *controller):MyInterface(controller)
        {}
    };
    
aJ
it's an interface and i never will use like in your example.. MyInterface *int = new InhretiedFromMyInterface (somecontroller);
jack london
im trying to make some polymorphism in c++.
jack london
If you don't want other than childs to construct MyInterface, declare every constructor as protected.
fnieto
+4  A: 

Just don't put it in at all. A class with a non-default ctor does not have a compiler-provided default constructor. It DOES have a compiler-generated copy constructor; inherit from boost::noncopyable to remove that.

MSalters
rewording: 'to remove that' should be 'to prevent copying'
Martin York