Search code examples
c++linker-errorsdefault-constructor

c++ undefined reference to default constructor


I am creating a C++ 11 program which compiles but fails to link. I have traced the error (shown at the bottom of this post) to a single line of code:

            m_equities[symbol] = temp;

where m_equities is defined as:

    map<string, EquityInDB> m_equities;

and temp is an instance of EquityInDB.

Can someone explain why this one line of code is causing the linker error below? It looks like that one line is trying to create an instance of my EquityInDB class using the default constructor (there is none). My EquityInDB class requires parameters in the constructor.

(Note: Commenting out the one assignment line above lets everything compile)

g++ -o MetaStockDB main.o date.o tradingday.o equity.o metastockdb.o msfileio.o equityindb.o bytearray.o metastockdb.o: In function std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, EquityInDB>::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, 0ul>(std::tuple<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&>&, std::tuple<>&, std::_Index_tuple<0ul>, std::_Index_tuple<>)': Makefile:254: recipe for target 'MetaStockDB' failed /usr/include/c++/6.3.1/tuple:1586: undefined reference to EquityInDB::EquityInDB()'


Solution

  • The m_equities[symbol] creates an elment using the default constructor, if there is no elment in the map for that key. So using operator[] requires the default constructor to exists.

    You should use insert and std::make_pair instead.

    std::map operator_at:

    1: Inserts value_type(key, T()) if the key does not exist. [...] mapped_type must meet the requirements of CopyConstructible and DefaultConstructible. If an insertion is performed, the mapped value is value-initialized (default-constructed for class types, zero-initialized otherwise) and a reference to it is returned.

    and

    [...]Return value: Reference to the mapped value of the new element if no element with key key existed.`