Using OwnedArray methods inside Listener


#1

Hello.

I want to be able to do this:

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?

Thank you.


#2
void buttonClicked (Button* b)
{
    const Button* button (b);
    if (ownedArray.contains (button))
    {
        // do stuff
    }
}

?


#3

Turns out that even that’s not necessary. See my rough ‘n’ ready example

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<> ?


#4

Right, with your help I worked out the problem.

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.

Thank you!


#5


#6

:joy: looks like it went through a little too much “find & replace”


#7

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();
}

which is the crux of my suggested solution…


#8

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 things only 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();
}

#9

+1

But please everyone get into the habit of writing it like this:

if (auto castedType = dynamic_cast<DervicedType*>(things[i]))
    castedType->derivedTypeMethod();

It’s shorter and safer that way.