Constructor: don't understand what book is saying?

I've read over this section a couple of times but I don't understand this at all?? Could someone please explain to me what this means?

The bolded is the the book "definition".

Normally, as in the Sale class, default constructors have no parameters. However, it is
possible to have a default constructor with parameters if all of its parameters have
default values, so that it can be called with no arguments. It would be an error to create
one constructor that accepts no arguments and another that has arguments but allows
default values for all of them. This would create two “default” constructors. The following
class declaration illegally does this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

class Sale // Illegal declaration!
{
private:
double taxRate;
public:
Sale() // Default constructor with no arguments
{ taxRate = 0.05; }
Sale(double r = 0.05) // Default constructor with a default argument
{ taxRate = r; }
double calcSaleTotal(double cost)
{ double total = cost + cost * taxRate;
return total;
};

As you can see, the first constructor has no parameters. The second constructor has one
parameter, but it has a default argument. If an object is defined with no argument list, the
compiler will not be able to resolve which constructor to execute.


How is the code above different from this? Is it just a matter of order or?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 // Sale class declaration
 class Sale
 {
 private:
 double taxRate;

 public:
 Sale(double rate) // Constructor with 1 parameter
 { taxRate = rate; // handles taxable sales
 }

 Sale() // Default constructor
 { taxRate = 0; // handles tax-exempt sales
}

 double calcSaleTotal(double cost)
 { double total = cost + cost*taxRate;
 return total;
 }
 };



How is the code above different from this?
For starters, code above will not compile. And book is pointing at it.

Difference between functions:
1
2
3
void print(int r) {std::cout << r;}
//and
void print1(int r = 10) {std::cout << r;}
Is that first function can be called only as:
1
2
3
4
print(5); //5
//and second can be called as either:
print1(100); //100
print1(); // 10 


I think the point of the book is that if you have a default constructor without arguments

Sale()

you can't also have one with arguments which all have a default value

Sale (double r = 0.05)

This is what the first version does, so the first version does something which is illegal.

The second version defines two constructors, but the first doesn't define a default value

Sale (double r)

so the compiler will not confuse it with the default constructur without arguments

Sale ()

So the point is, if you define a constructur where all arguments have a default value, the compiler will treat this as a default constructor without arguments. So you can not have both.
Thank you very much for your help!!
Topic archived. No new replies allowed.