Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

how do you make an array of a certain parent object that also includes any child objects?

+3 votes
asked Oct 8, 2021 by Joe Fagan (150 points)

3 Answers

0 votes
answered Oct 8, 2021 by Alejandro Calle Rosete (140 points)
What language are we talking about? Maybe you can use bidimensional arrays
0 votes
answered Oct 8, 2021 by Peter Minarik (84,720 points)
edited Oct 13, 2021 by Peter Minarik

You can use polymorphism to achieve what you're trying to do: a pointer to parent can take a pointer to a child. It is important that we're talking about pointers though.

See the C++ example below (works similarly in most object oriented languages):

#include <iostream>

class Base
{
public:
    int baseValue;

    Base(int value) :
        baseValue(value)
    { }
    
    void virtual Print() const { std::cout << "baseValue: " << baseValue << std::endl; }
};

class Derived : public Base
{
public:
    float derivedValue;

    Derived(int baseValue, float value) :
        Base(baseValue),
        derivedValue(value)
    { }

    virtual void Print() const override { std::cout << "baseValue: " << baseValue << "; derivedValue: " << derivedValue << std::endl; }
};

int main()
{
    const int nItems = 4;
    Base * items[nItems] = { new Base(1), new Base(2), new Derived(3, 3.1f), new Derived(4, 4.1f) };
    for (int i = 0; i < nItems; i++)
        items[i]->Print();
        
    return 0;
}

Notice how the items array (of Base pointers type) can hold Base and Derived pointers just as well. When we call Print(),  polymorphism allows the virtual function to be called on the derived class when it stands in for the base class.

Output

baseValue: 1
baseValue: 2
baseValue: 3; derivedValue: 3.1
baseValue: 4; derivedValue: 4.1
+1 vote
answered Oct 8, 2021 by Rose Gonzaga (170 points)
You can't call sub-class methods on parent-class objects. Think of it this way. A circle is a geometric shape. But not all geometric shapes are circles. So not all geometric shapes can have circle properties (and in this case methods).
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...