Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ initialize an empty list in class

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?

like image 209
LBaelish Avatar asked Dec 19 '22 19:12

LBaelish


1 Answers

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;
};
like image 106
Barry Avatar answered Dec 24 '22 02:12

Barry