been a long time in manage world and now I'm going back to C++.
Trying to do a small object management, but I'm having an error that I can't figure out.
Reduced the project to a smallest possible to show my issue:
(the identation got a bit messed up on copy/paste)
#include <iostream>
#include <vector>
using namespace std;
//
class cControl
{
public:
virtual void Draw()
{
cout << "Control" << endl;
};
};
//
class cLabel: public cControl
{
public:
cLabel()
{
}
//
void Draw()
{
cout << "Label" << endl;
}
};
//
class cControls
{
public:
vector<cControl*> listControls;
//
cLabel CreateLabel()
{
cLabel label;
// #1
//this->AddControl(&label);
return(label);
}
//
void AddControl(cControl *control)
{
this->listControls.push_back(control);
}
//
void Draw()
{
for(cControl *ctrl: listControls)
ctrl->Draw();
}
};
//
int main()
{
cControls controls;
cLabel label1=controls.CreateLabel();
// #2
controls.AddControl(&label1);
//
controls.Draw();
//
cin.get();
//
return(EXIT_SUCCESS);
}
The point is to have a base control class that others will derive (label, textbox, line, panel, etc).
I've pointed the problem with #1 and #2.
If I add the control to the list in the main function (#2), it works fine and it calls Draw from label correctly.
But if I comment #2 and uncomment #1, so it adds automatically to list when creating label, it crashes when trying to call Draw from label.
From what I've checked, when the label is added to the vector inside the CreateLabel function, something changes when it gets out of that function, which makes unaccessible when calling the Draw.
Can anyone point me out to the correct path?
Thanks,
chaos






