views:

120

answers:

3

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 classes.

+2  A: 

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.

AshleysBrain
+1  A: 

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(){}
}
Tadeusz Kopec
I think you want to put `public:` above the constructor instead of like a Java/C# style keyword.
AshleysBrain
I was more referring to the copy constructor...which is a bit more code if you have lots of properties.
Itay Moav
@AshleyBrain @Itay Moav: thanks. I work in Java now so my habits change :-)
Tadeusz Kopec
@Itay Moav: If you don't define copy constructor, compiler will do it for you. Always. I wrote it in my answer.
Tadeusz Kopec
@Tadeusz Kopec You are right, missed that part.
Itay Moav
+2  A: 

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.

Steve Jessop