How can I initialize an empty list as a private member in a C++ class? I don't want to prompt the user to pass in an empty list, but rather just create one when I make a new instance of the class.
header.h
class MyClass{
public:
MyClass();
private:
list<int> myList;
}
MyClass.cpp
MyClass::MyClass()
:myList(list<int>){}
This doesn't work as written, what am I missing here?
You don't need to do anything. The default constructor, like the name suggests, is called by default. So this is already correct:
class MyClass{
public:
MyClass() { } // c++03
MyClass() = default; // c++11
private:
std::list<int> myList;
};
If you want to still have myList
in the member initializer list, you can do that by simply providing empty parens:
class MyClass{
public:
MyClass()
: myList() // explicitly use default ctor
{}
private:
std::list<int> myList;
};
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