Remember that a struct and a class really only differ by whether their members are public or private by default, in C++.
Yes this is true but we ran into this about a month ago. We had a container that had base struct pointers and then added objects that were derived from the base struct. When we went to access the data we got nothing but garbage. Switching the code to classes fixed it. All we could gather is somehow it was slicing when we added to the container. Dynamic cast did not work as expected. We never found out why and didn't really waste time on it since we knew classes worked fine. We changed it, counted it a victory, and moved on. I posted that b/c under MSVC 2003 .NET and using MS's STL impl of std::map it just did not work as expected. I did not understand what was happening since we were storing base struct pointers in the map and then adding pointers to derived struct objects to it. Should have worked but none of the derived struct members were visible.
After the fact, it might be worth looking into across compilers and implementations of the STL. I still don't know what exactly was wrong and theoretically it should have worked.
Code:
#include <tchar.h>
#include <map>
#include <iostream>
#define DO_TEST1
#define DO_TEST2
struct Base
{
int bx;
int by;
virtual void printOut()
{
std::cout << "Base BX: " << bx << std::endl;
std::cout << "Base BY: " << by << std::endl;
}
};
struct Derived:public Base
{
int dx;
int dy;
virtual void printOut()
{
Base::printOut();
std::cout << "Derived DX:" << dx << std::endl;
std::cout << "Derived DY:" << dy << std::endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
std::map<unsigned int,Base *> m_Test;
#ifdef DO_TEST1
Derived x;
x.bx = 3;
x.by = 4;
x.dx = 5;
x.dy = 6;
m_Test.insert(std::pair<unsigned int,Base *>(0,&x));
std::map<unsigned int,Base *>::iterator iter = m_Test.find(0);
Derived *ptrX = dynamic_cast<Derived *>(iter->second);
ptrX->printOut();
#endif
#ifdef DO_TEST2
Derived *dynX = new Derived();
dynX->bx = 7;
dynX->by = 8;
dynX->dx = 9;
dynX->dy = 10;
m_Test.insert(std::pair<unsigned int,Base *>(1,dynX));
std::map<unsigned int,Base *>::iterator iter2 = m_Test.find(1);
Derived *ptrDynX = dynamic_cast<Derived *>(iter2->second);
ptrDynX->printOut();
delete ptrDynX;
#endif
int ch = getchar();
return 0;
}
Just tested it with this code and you are right it works just fine. I wonder what happened a month ago to give us so many problems??? I knew it should have worked. Tested in MSVS 2005 .NET standard.