Halona
Halona

Reputation: 1485

How to use list of structs in c++

I would like to build a struct Packet that contains list of Headers. The relevant code I use:

//Packet.h
#include <list>

using namespace std;

struct Header {
    Header();
    bool Valid;
    long unsigned DestAddr:48;
};

struct Packet_t {
    Packet_t();
    list<Header> Headers;
};

Now I try to build the constructor for Packet_t that will initialize the Headers list to include only one header - FirstHeader:

//Packet.cpp
#include "Packet.h"

Header::Header() {
    Valid = false;
    DestAddr = 0;
};

Packet_t::Packet_t(){
    ValidPacket = false;
    Header FirstHeader(); //here I try to initialize the first Header using its constructor
    Headers.push_front(FirstHeader);
};

The error I get:

Packet.cpp: error: no matching function for call to 'std::list >::push_front(Header (&)())'

Really appreciate any help

Upvotes: 3

Views: 8578

Answers (1)

juanchopanza
juanchopanza

Reputation: 227400

This is a function declaration:

Header FirstHeader();  // function FirstHeader, returns a Header

What you need is

Headers.push_front(Header());

or

Headers.emplace_front(); // default constructs FirstHeader object in place

or, if you need an instance to work on before pushing,

Header FirstHeader;
// ... do stuff to Header

Headers.push_front(FirstHeader);

Alternatively, use the constructor initialization list to initialize the list with one element:

Packet_t::Packet_t() : Headers(1) // or Headers{Header(args....) if need args
{

}

Upvotes: 7

Related Questions