Reputation: 3580
I want to start by showing some code and explain my problem later.
class swcObject :
public swcRectangle
{
public:
bool visible;
};
class swcText
{
public:
std::string text;
protected:
virtual void attachedToParent() = 0;
};
class swcLabel :
public swcObject,
public swcText
{
public:
int text_align;
private:
void attachedToParent();
};
...
class swcComboBox :
virtual protected swcObject
{
public:
void setPosition(int x, int y);
private:
swcLabel label;
};
Now I have this class w/c has a member object of type std::vector<swcObject>
.
class swcWindow :
private swcObject
{
public:
void addObject(const swcObject &object);
private:
std::vector<swcObject> objects;
};
I came into this few problems w/c I haven't encountered before and Google seems don't have a relevant problem like mine.
swcWindow window;
swcComboBox cbox;
window.addObject(cbox);
'swcObject' is an inaccessible base of 'swcComboBox'
I do not want to access swcComboBox::swcObject
members on public scope like this cbox.x = 0;
, but instead cbox.setPosition(0, 0);
because there will be always an adjusting of some member elements whenever the swcComboBox
had changed its location.
swcWindow window;
swcLabel label;
window.addObject(label);
In this case, label
have a base classes of swcText
and swcObject
. After adding the label
to one of member of window.objects
(is of type std::vector), swcText
properties are gone, like the text
property.
I want to create a temporary objects and initialize its property in a init()
method outside of those classes and copy it using swcWindow::addObject()
. Is this possible without a cast? I think this one would do but its awful(?), and I didn't try it yet if this is working:
void addObject(const swcObject &object, SWC_TYPES type)
{
switch (type)
{
case LABEL:
//do casting?
...
}
}
Please recommend any other way how can I achieve those kind of implementation with the same functionalities.
Upvotes: 0
Views: 196
Reputation: 9238
vector store elements by value, as if you passed your ComboBox to a procedure which takes a swcObject by value, not by reference. This leads to cut of object to its base class, which is prohibited if you use protected inheritance.
You shouldn't store polymorphic objects in vector, just as you shouldn't pass them by value. You can try storing references or (smart) pointers in vector - that should solve your problems.
Upvotes: 1