I have this snippet of code which seems to work well:
class foo{/* some member variables and functions*/};
void do_somthing(foo x={}){}
int main(){
do_somthing();
}
I used to use void do_somthing(foo x=foo()){}
to default the x
argument but I see this way ={}
in some book or online example(can not remember). Is it totally ok to use it? Is there any difference between the two methods?
Beginner programmers, and programmers coming to C++ from the BASIC language often find using braces confusing or daunting. After all, the same curly braces replace the RETURN statement in a subroutine (function), the ENDIF statement in a conditional and the NEXT statement in a FOR loop.
Declaring a variable with braces in C++ Initialization occurs when you provide a variable with a value. In C++, there are several methods used to declare and initialize a variable. The most basic way to initialize a variable is to provide it with a value at the time of its declaration.
foo x=foo()
is copy initialization,
Initializes an object from another object
and foo()
is value initialization.
This is the initialization performed when a variable is constructed with an empty initializer.
foo x={}
is aggregate initialization.
Initializes an aggregate from braced-init-list
If the number of initializer clauses is less than the number of members and bases (since C++17) or initializer list is completely empty, the remaining members and bases (since C++17) are initialized by their default initializers, if provided in the class definition, and otherwise (since C++14) by empty lists, which performs value-initialization.
So the result is the same in this case (both value-initialized).
And the effects of value initialization in this case are:
if T is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized
Finally the effects of zero initialization in this case are:
If T is a scalar type, the object's initial value is the integral constant zero explicitly converted to T.
If T is an non-union class type, all base classes and non-static data members are zero-initialized, and all padding is initialized to zero bits. The constructors, if any, are ignored.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With