Assignment Operator in C ++ Function Parameter

I study data structures (List, Stack, Queue), and this part of the code confuses me.

ListNode( const Object& theElement = Object(), ListNode * node = NULL); template<class Object> ListNode<Object>::ListNode( const Object& theElement, ListNode<Object> * node) { element = theElement; next = node; } 
  • Why are there assignment operators within function parameters?
  • What does the call to Object() do?
+7
source share
3 answers

These are not assignment operations. These are the default arguments for this function.

A function can have one or more default arguments, which means that if there are no arguments at the calling point, the default value is used.

 void foo(int x = 10) { std::cout << x << std::endl; } int main() { foo(5); // will print 5 foo(); // will print 10, because no argument was provided } 

In the above code example, the ListNode constructor has two parameters with default arguments. The first default argument is Object() , which simply calls the default constructor for Object . This means that if an instance of Object is passed to the ListNode constructor, the default value of Object() will be used, which means only the default constructed Object .

See also:
The advantage of using the default function parameter
Function parameter default value

+15
source

Assignments in declarations provide default values ​​for optional parameters. Object() means calling the default constructor of Object .

The effect of the default parameters is as follows: you can call the ListNode constructor with zero, one, or two parameters. If you specify two parameter expressions, they are passed as usual. If you specify only one expression, its value is passed as the first parameter, and the second is NULL by default. If you do not pass any parameters, the first parameter by default will have an Object instance created with its default constructor, and the second by default - NULL .

+3
source

go to http://www.errorless-c.in/2013/10/operators-and-expressions.html for operators and expressions in the programming language c

0
source

All Articles