I'm studying data structures (List, Stack, Queue), and this part of code is confusing 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 there are assignment operators within function parameters?
- What does
Object()
call do?
go to http://www.errorless-c.in/2013/10/operators-and-expressions.html for operators and expressions in c programming language
Those are not assignment operators. Those are default arguments for the function.
A function can have one or more default arguments, meaning that if, at the calling point, no argument is provided, the default is used.
In the example code you posted, the
ListNode
constructor has two parameters with default arguments. The first default argument isObject()
, which simply calls the default constructor forObject
. This means that if noObject
instance is passed to theListNode
constructor, a default ofObject()
will be used, which just means a default-constructedObject
.See also:
Advantage of using default function parameter
Default value of function parameter
The assignments in declarations provide default values for optional parameters.
Object()
means a call toObject
's default constructor.The effect of the default parameters is as follows: you can invoke
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 one is defaulted toNULL
. If you pass no parameters, the first parameter is defaulted to an instance ofObject
created with its default constructor, and the second one is defaulted toNULL
.