1

What does B(int b=0):b(b){} mean in the following portion of code?

class B
{
    int b;
public:
    B(int b=0):b(b){}
 };
nonsensickle
  • 4,438
  • 2
  • 34
  • 61
  • 3
    It defines a constructor for class `B`, taking one optional `int` parameter (if omitted, the default value of `0` is used). This constructor initializes the member variable of the class, named `b`, with the value of said parameter. – Igor Tandetnik Dec 02 '14 at 06:16
  • 1
    Just google these terms together with C++: Constructors, default arguments, and initializer lists. – cmaster - reinstate monica Dec 02 '14 at 06:19

1 Answers1

2

It's an empty constructor definition.

class B
{
    int b;
public:
    B (int b = 0) //Default initialize b to 0
        : b(b) //Initialize member b to parameter b
    { } //Empty constructor definition
};

You could write instead of the constructor

B (int b = 0)
    : b(b)
{ }

also this:

B (int b = 0)
{
    this->b = b;
}
Blacktempel
  • 3,935
  • 3
  • 29
  • 53