SirRupertIII
SirRupertIII

Reputation: 12595

What does this do in a C++ constructor?

I saw this in a textbook, but the book doesn't explain what it actually does, and why I should do this. Here is something similar to the example in the book:

 class MyClass
 {
      public:
           MyClass(int initial_capacity = 20);
      private:
           int capacity;
 }

I can't use initial_capacity in the implementation, I can't even implement anything, so I am confused as to what this is for? Does it set capacity to 20 somehow? How is this a default constructor?

Upvotes: 0

Views: 756

Answers (4)

rbtLong
rbtLong

Reputation: 1582

It serves as a default value for initial_capacity if the user chooses not to put in a value. So in essence it takes the place of 2 constructors: one that takes an integer MyClass(int); and one that doesn't take any parameters MyClass(); which will be 20.

Assuming that you are going to use that to set a value to capacity, there are two ways to use it . . .

either in your .cpp file

#include "<...>.h"

MyClass::MyClass(int initial_capacity)
{
    capacity = initial_capacity;
}

or you can elect to do it straight from your .h file

class MyClass
{
     public:
          MyClass(int initial_capacity = 20) 
               : capacity(initial_capacity) // member initialization list
          {}
     private:
          int capacity;
};

This shorthand which is preceded by the semicolon is called a member initialization list.

Be aware though, that calling it this way may get you into trouble because it will automatically create a parameterless constructor for you.

Upvotes: 1

ivan.mylyanyk
ivan.mylyanyk

Reputation: 2101

Probably, there is missed implementation of constructor. For example, if constructor looks like this one :

MyClass(int initial_capacity = 20) {
     capacity = initial_capacity;
}

If you create object this way:

MyClass a(10);

capacity will be set to 10. On the other hand, if you will create object like this:

MyClass a;

capacity will be set to 20.

Upvotes: 11

Code-Apprentice
Code-Apprentice

Reputation: 83587

MyClass(int initial_capacity = 20);

This syntax provides a default value for the initial_capacity parameter. Note that you can do this with parameters for any function, not just with constructors. Default parameter values are helpful because it allows you to do both

MyClass c(5);

and

MyClass c;

In the later, the default value is used.

Upvotes: 2

tohava
tohava

Reputation: 5412

This is a constructor with a default parameter. It means that you can either call it with a number, or without a number. If you call it without a number, it is the same as if you called with the number 20.

Upvotes: 4

Related Questions