开发者

How can I make the compiler create the default constructors in C++?

开发者 https://www.devze.com 2022-12-28 03:07 出处:网络
Is there a way to make the compiler create the default constructors even if I provide an explicit constructor of my own?

Is there a way to make the compiler create the default constructors even if I provide an explicit constructor of my own?

Sometimes I find them very useful, and find it a waste of time to write e.g. the copy constructor, especially for large class开发者_开发知识库es.


You can't - the compiler turns off some of its auto-generated default constructor when you provide your own, so you can prevent default-constructing certain classes that way. However, I think C++0x will allow you to explicitly state a default compiler implementation, eg:

MyClass() = default;  // 'delete' also allowed by upcoming standard to disable

I don't think any compilers support this yet - C++0x (as the next standard has been known) is not yet final, so you'll just have to make do typing out your default constructors for now. It's not much code! MyClass() {} will do as long as all the members are themselves default constructible.


The copy constructor is provided whether you define any other constructors or not. As long as you don't declare a copy constructor, you get one.

The no-arg constructor is only provided if you declare no constructors. So you don't have a problem unless you want a no-arg constructor, but consider it a waste of time writing one.

IIRC, C++0x has a way of delegating construction to another constructor. I can't remember the details, but it would allow you to define a no-arg constructor by specifying another constructor, plus the argument(s) to pass to it. Might save typing some data member initializers in some cases. But the default no-arg constructor wouldn't have provided those initializers either.


Compiler will generate default copy constructor always, unless you provide your own definition of copy constructor. Your problem is only with default no-arg constructor, which is not generated if there is any constructor definition present. But it's not so hard to provide no-arg constructor which behaves exactly like generated one:

class yourClass
{
    public:
       yourClass(){}
}
0

精彩评论

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

关注公众号