void buttonClicked (Button* b)
{
if (ownedArray.contains (b)) function (ownedArray.indexOf (b));
}
However, the OwnedArray methods require a const Button pointer. Const cast doesn’t seem to work either as you can’t cast to base type button. Is there / what’s the best way round this?
Guess there’s something else wrong…? If your buttonClicked definition is in a .cpp, perhaps you forgot to specify the scope of the method? Or if it’s in a .h, perhaps you forgot the override keyword?
Which type have you passed as the template parameter of your OwnedArray<> ?
At first, your solutions didn’t work. I’ve found that this was because my OwnedArray was (understandably?) set as OwnedArray , and altering it to OwnedArray solved the problem. Also it doesn’t seem necessary to convert between const and not. I’d never initialised an array of base with a derived object.
In seriousness, can others please confirm / refute that it’s OK to do:
OwnedArray<BaseType> things;
things.add (new DerivedType());
for (int i = 0; i < things.size(); ++i)
{
things[i]->baseTypeMethod();
static_cast<DerivedType*>(things[i])->derivedTypeMethod();
}
The behavior is undefined if things contains any objects which are not actually of type DerivedType when you call the derived method using the static_cast. So this would really only be safe if you were positive that thingsonly contained objects of DerivedType… however in that case you would just make things an OwnedArray<DerivedType>.
This situation is exactly what dynamic_cast was created to handle:
OwnedArray<BaseType> things;
things.add (new DerivedType());
for (int i = 0; i < things.size(); ++i)
{
things[i]->baseTypeMethod();
DerivedType* castedType = dynamic_cast<DervicedType*>(things[i]);
if (castedType != nullptr)
castedType->derivedTypeMethod();
}