C++ STL list  type as an argumnet default value

Roger Alcindor
Roger Alcindor used Ask the Experts™
on
I am coding a C++ class which has a member function void Start(list<int> lst);

I wish to assign a default  value to the lst parameter but I haven't worked out how to declare and implement this in the declaration of the member function .

How would I declare this with a default list of integers 1,3,5,7 for example ?

class MyClass
{
        public:
        MyClass(){};
       ~MyClass(){};
void Start(list<int> lst = ???);
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Author

Commented:
By the way, I am using Embarcadero C++ builder XE10.1 Berlin "Borland Classic Compiler",not C++ 11
evilrixSenior Software Engineer (Avast)

Commented:
C++11? If so, as simple as this...

void Start(list<int> lst = {1, 2, 3, 4, 5});

https://en.cppreference.com/w/cpp/language/list_initialization
evilrixSenior Software Engineer (Avast)

Commented:
You beat be to it! Prior to C++11, there is no standard way to do this.
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

evilrixSenior Software Engineer (Avast)

Commented:
One way would be to initialise with an empty list as the default and so if you function sees an empty list it assumes the default value. This won't work if you want to pass valid empty lists.

void Start(list<int> lst = std::list<int>());
evilrixSenior Software Engineer (Avast)

Commented:
Another option is to pass the list via pointer, set the default value of the pointer to null so that if no list is passed, your function receives null and assumes default values.
I have solved the issue as follows.

in the header file where the Start function is declared, I have coded the following function:

list <int> DefaultParamList(void)
{
	list<int> rtn;

	rtn.clear();
	rtn.push_back(11);  // tightening status
	rtn.push_back(13);  // Torque Status
	rtn.push_back(14);  // Angle Status
	rtn.push_back(24);  // torque value
	rtn.push_back(28);  // angle Value
	rtn.push_back(45);  // timestamp
	return rtn;
}

Open in new window


The Start function is declared as follows:

void Start(list<int> paramlist = DefaultParamList());

Open in new window


I have tested the code and it works as expected.

Author

Commented:
The empty list  std::list<int>()  was considered with interest.

Thanks for your comments,

Roger

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial