Thread: Class constructor

  1. #1
    Registered User
    Join Date
    Mar 2013
    Location
    Portugal, Porto.
    Posts
    105

    Class constructor

    Hello there

    When you need to make a constructor with arguments does it make sense to include both of the constructors as the following code shows?

    Eg:
    Code:
    Rectangle( double comp = 1.0, double larg = 1.0 );
    Rectangle( );
    Also, is it good programming style to include the standard one when you need none with arguments or it can be skipped? (Knowing that the compilar creates a default one)

  2. #2
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    When you need to make a constructor with arguments does it make sense to include both of the constructors as the following code shows?
    O_o

    You should not and can not provide both.

    Code:
    Rectangle s; // This will fail to compile with "ambiguous call to overloaded function".
    Also, is it good programming style to include the standard one when you need none with arguments or it can be skipped?
    If the one created by the compiler does the right thing, you can and should avoid creating an explicit one.

    Soma

  3. #3
    Registered User
    Join Date
    Mar 2013
    Location
    Portugal, Porto.
    Posts
    105
    Oh I just noticed something important. I guess that comp = 1.0 and larg = 1.0 makes all the difference and I noticed those values were defined jst after I posted this.

    So my guess is it doesn't work because the compiler wouldn't know which constructor to use am I right?

  4. #4
    Registered User
    Join Date
    Jun 2013
    Posts
    66
    Quote Originally Posted by Khabz View Post
    So my guess is it doesn't work because the compiler wouldn't know which constructor to use am I right?
    Correct. However, if all of the constructor parameters are being defaulted, then the two should be functionally equivalent. Thus there's no need to define both if they do the same thing. If they aren't functionally equivalent, the class design has a logical ambiguity that needs to be resolved. This logical ambiguity is simply being reflected as a syntactic ambiguity, and you may yourself lucky that the compiler caught the problem for you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 12-31-2011, 02:23 AM
  2. Replies: 40
    Last Post: 06-02-2010, 10:08 AM
  3. using a class constructor w/ class array
    By matt000r000 in forum C++ Programming
    Replies: 4
    Last Post: 11-01-2009, 07:08 AM
  4. Replies: 9
    Last Post: 06-20-2008, 02:41 AM
  5. Calling constructor of the base class of a derived class..
    By CaptainPenguin in forum C++ Programming
    Replies: 5
    Last Post: 02-19-2003, 01:47 PM