1

In the Book C++ Primer by Stanley B. Lippman*,* Josée Lajoie

in Chapter 14.2 of Class Constructors it states:

Should we also provide support for specifying an opening balance but no client name? As it happens, the class specification disallows this explicitly. Our two-parameter constructor with a default second argument provides a complete interface for accepting initial values for the data members of class Account that can be set by the user:

class Account { public: // default constructor ... Account(); // parameter names are not necessary in declaration Account( const char*, double=0.0 ); const char* name() { return _name; } // What is this for?? // ... private: // ... }; 

The following are both legal Account class object definitions passing one or two arguments to our constructor:

int main() { // ok: both invoke two-parameter constructor Account acct( "Ethan Stern" ); 

How does this Invoke the 2-parameter constructor when it has not been declared with single argument??

 Account *pact = new Account( "Michael Lieberman", 5000 ); 

And how does the above line call the constructor with default arguments

 if ( strcmp( acct.name(), pact->name() )) // ... } 

The book seems to be highly unclear with incomplete codes. Need a good explanation on Constructors. Please clarify.

1 Answer 1

8

This isn't about constuctors, this is about default arguments.

void f(int x, int y = 5) { //blah } 

when you call it providing less arguments, it uses the values of default arguments. E.g.

f(3); //equivalent to f(3, 5); 

If one of the function parameters has a default value, then all successive parameters must have ones too.

void f(int x, int y = 3, int z = 4) { //blah } f(0); // f(0, 3, 4) f(1, 2); //f(1, 2, 4) f(10, 30, 20); //explicitly specifying arguments 

HTH

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.