Sign in to follow this  
Sir Ementaler

Default constructors vs default arguments

Recommended Posts

Let's consider a simple class declared within a script:

class foo{
  foo(){
    //...
  }
}

I can create its instances in both of these two ways:

foo foo1();
foo foo2;

Now let's consider a similar class, but give its constructor a parameter that can have a default value:

class foo{
  foo(int bar=0){
    //...
  }
}

This will still be valid:

foo foo1();

But the other line will return an error:

ERR : No default constructor for object of type 'foo'.

 

This error will also appear in various other cases such as trying to create a temporary copy of an object. I think that constructors which can be called with no parameters should be treated as default constructors.

Edited by Sir Ementaler

Share this post


Link to post
Share on other sites

I'll look into it.

 

Declaring a variable of the type with the default arg should definitely work and is something that I've missed in the implementation of default args.

 

However, to allow the compiler to create temporary objects using a non-default constructor with default args doesn't sound like a good idea.

Share this post


Link to post
Share on other sites

I'm almost entirely convinced that if somebody creates a constructor that can be called without any arguments, their intention is making it a default constructor. I was trying to imagine a case in which this could generate problems but I'm unable to. I'm pretty sure a constructor whose all arguments have default values should overtake all functions of a default constructor including creating temporary objects, even if only because creating a proper default constructor would become impossible due to a "multiple matching signatures" error. I'm not as experienced programmer and I won't be surprised if I had overlooked some downside of this solution so if you could explain why exactly it sounds like a bad idea, I would be thankful.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this