I am fairly new to object oriented C++, and I'm trying to make a constructor for a linked list in this way:
Somewhere in the List.h we'd have this:
struct Node
{
int data;
Node *next;
};
and then in the main.cpp, I'd like to be able to construct a list like this:
int main()
{
List A({1,2,3,4,5,6});// I want the amount of numbers to indicate the size of
//the list and the numbers to go into each node in order
return 0;
}
So my question is, can i make such a constructor? If so then how? Do i have to use templates do this? I tried to find a question like this answered in SO but they all included templates and i haven't learned that yet. If i can make my constructor to do this, is it possible to do it without using templates?
Yes you can do this (using C++11).
You need to define a constructor taking an std::initializer_list<int>
.
(Yes this is a template, but I will show you how to use it. :-) )
A possible implementation of an std::intitializer_list<int>
-constructor could look like this:
//in class List:
List (std::initializer_list<int> init) {
for (auto v : init)
this->emplace_back(v);
}
where you have to implement emplace_back
yourself as an exercise. emplace_back
should construct a new Node
and append it to the List
. It will be a useful member function (I promise).
Probably unimportant notice:
If emplace_back
does heap allocations, this code might leak. In this case, delegate to a constructor that puts the List
into a valid state, so the destructor can free all the heap-allocated Nodes
.
If you do not understand this, it is most likely not too important for your application.
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