0

I have the following piece of code in which I am trying to store a child struct childStruct in std::map with the data part being the parent struct parentStruct. However, when I try to retrieve again the data part for the child which is variable2, I get a wrong value.

Here is the code:

// Example program
#include <iostream>
#include <string>
#include <map>

struct parentStruct
{
    uint32_t variable1;
};

struct childStruct : parentStruct
{
    uint32_t variable2;
};


int main()
{
    struct childStruct test;
    std::map<uint32_t, struct parentStruct> m_list;
    test.variable1 = 50;
    test.variable2 = 100;
    m_list[1] = test;


    struct childStruct *test2 = static_cast<struct childStruct *> (&m_list.at(1));

    std::cout << test2->variable1 << std::endl;
    std::cout << test2->variable2 << std::endl;
}

The output of the previous program is:

50
138353

Instead of being:

50
100

How can I can the correct value which is stored in variable2.

0 Answers0