c++classoopc++17subclass

Is there a way to access a function of subclass by any other class?


I have the superclass A, and its subclass B and C.

I have the class D, and its member:

A* aArray[20]

but in aArray, there will be just B and C objects.

I want to implement a function that will count the number of Bs in this array, but I could not think of an effective solution.

My solution is to write getType function in each class, and check if it is 'a', 'b', 'c' in the function of D.

For example, for the subclass B:

virtual char getType() const{
    return 'b'    
};

Is it the correct way to implement this?


Solution

  • int countBs() const
    {
       int count=0;
       for (const A* item: aArray)
       {
          if (dynamic_cast<const B*>(item)) count++;
       }
       return count;
    }
    

    Note: this requires that you have virtual functions (at least the destructor) in the class hierarchy; your getType function is already there.

    Also note that this counts objects that are either B, or derived from it. If you want exactly B, use typeid() instead.

    Note: in most cases, having a C-array of raw pointers is bad...-ish. Chances are you want to use smartpointers (std::unique_ptr, likely) and either std::array if it's really a fixed 20 items, or std::vector if it's variable.

    Also note that doing typechecks like this tends to feel a bit smelly at times. There may be valid reasons to do it, though.