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 by Joe Fagan (150 points)

3 Answers

0 votes
answered Oct 8 by Alejandro Calle Rosete (140 points)
What language are we talking about? Maybe you can use bidimensional arrays
0 votes
answered Oct 8 by Peter Minarik (34,450 points)
edited 5 days ago 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
    int baseValue;

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

class Derived : public Base
    float derivedValue;

    Derived(int baseValue, float 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++)
    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.


baseValue: 1
baseValue: 2
baseValue: 3; derivedValue: 3.1
baseValue: 4; derivedValue: 4.1
0 votes
answered Oct 8 by Rose Gonzaga (150 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.