Default details for constructor parameters in C++

  • 2020-05-30 20:54:15
  • OfStack

Default details for constructor parameters in C++

Preface:

The value of the parameter in the constructor can be either passed as an argument or specified as some default value, that is, if the user does not specify an argument value, the compiler makes the argument take the default value. Initialization can also be done in the constructor in this way.


#include <iostream>
using namespace std;
class A
{
  public :
  A(int aa=0,int bb=00); // Specify the default parameters when you declare the constructor 
  int volume( );
 
  int a;
  int b;
  
};

int main( )
{
 
 A obj(4);
 cout<<obj.a<<" "<<obj.b;  
return 0;
}

The result of the program running is


4 0

As you can see, the use of default parameters in constructors is convenient and efficient. It provides multiple options for creating objects that act as several overloaded constructors.

The benefit is that even if you don't provide an argument value when the constructor is called, not only will you not make a mistake, but you will also ensure that the object is initialized to its default parameter value. This is especially handy when you want to have the same initialization state for every object.

A few notes on constructor defaults:

You should specify the default value when you declare the constructor, not just when you define the constructor. The parameter name can be omitted when the constructor is declared in line 5 of the program. If all the parameters of the constructor specify default values, you can define an object with one or more arguments, or without them. Overloaded constructors cannot be defined after all default constructors are defined in a class.

If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!


Related articles: