开发者

Can we have a body for the default constructor in C++?

Can w开发者_开发问答e have a body for the default constructor in C++?

Thanks.


Yes, of course you can. Any constructor that doesn't require an argument is a default constructor.


Yes the default constructor (ie. the one without any parameters) can have a body like any other constructor. This is a good place to put "default" initializing code. Set member variables to sensible values. Perhaps set pointers to null or allocate component objects.

Perhaps the word 'default' is the cause of confusion? It is a default in terms of being called without any specific parameters, not necessarily the default if there's no definition.


It is not required to explicitly specify a default constructor. However it is good practice to go ahead and explicitly implement one, this way you are not relying on the default behavior to be what you really want.

If you do implement a public default constructor it definitely should have a body, even if it is empty.

In some cases it is ok to have a protected or private ctor. If the ctor is private (refered to as a hidden constructor) ctor is private then it is ok if it does not have a function body because it can never be called.


Constructor is used to initialize the members of a class. So, surely any constructor can have a body. By providing yourself a constructor, you are just over riding the default constructor.

class foo
{
    int x ;
    public:
       foo()  // default constructor
       {
           x=10;  // How ever you can achieve this with initializer lists too.
       }
};
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜