I have following classes: Container, Element and then couple of classes that inherit from Element, eg. Button, Input, etc …
I have a problem when adding the elements to Container array, my main() looks like this:
Container c;
c.Add( Button(...) );
c.Add( Input(...) );
where “…” are some constructor parameters.
In the container class I have a array of pointers to store all elements that belong to that container:
Element ** elements;
But the problem I’m having is how to implement the Add method, I was hoping something like this would work:
void Add(const CControl & newElement){
elements[elemCnt++] = &newElement;
}
(the elements array is allocated: elements = new Element * [100];)
However I am getting this compilation error:
main.cpp: In member function ‘Container& Container::Add(const Element&)’:
main.cpp:138:23: error: invalid conversion from ‘const Element*’ to ‘Element*’
When I remove the const qualifier, I get a compilation error saying there is no suitable candidate.
The thing is, I am new to polymorphism and inheritance in C++, so I might be going wrong way about this. What would be the best approach on this?
PS: The main method must look the same, also don’t suggest any vector or STL stuff.
Addshould take a pointer:then you can call it like this
If you really cannot change the calling code, you need to somehow create a copy of the temporary.
E.g. by implementing a virtual
Clonemethod inCControl,Input,Buttonan call it inAdd.