开发者

How can I create an interface without parameterless constructor in C++?

How can I hide the default constructor from con开发者_JAVA百科sumers? 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)
            {
            }

};


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)
        {}
    };
    


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜