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:
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!