Pladnius Brooks
Pladnius Brooks

Reputation: 1308

C++ Accessing data in child classes

My question is pretty much in the code that follows. I am trying to create an array of pointers to abstract objects each with an ID and cost. Then I create objects like cars and microwaves and assign the pointers to point to them. Once they are created, how do I access the child data from the array? Is that possible. How do I even access the child objects at all if the classes are created in the heap and pointed to in the base class array?

class Object
{
public:
    virtual void outputInfo() =0;

private:
    int id;
    int cost;
};

class Car: public Object
{
public:
    void outputInfo(){cout << "I am a car" << endl;}

private:
    int speed;
    int year;

};

class Toaster: public Object
{
public:
    void outputInfo(){cout << "I am a toaster" << endl;}

private:
    int slots;
    int power;
};


int main()
{
    // Imagine I have 10 objects and don't know what they will be
    Object* objects[10];

    // Let's make the first object
    objects[0] = new Car;

    // Is it possible to access both car's cost, define in the base class and car's speed, define in the child class?

    return 0;
}

Upvotes: 0

Views: 241

Answers (2)

KV Prajapati
KV Prajapati

Reputation: 94625

Use protected access modifier.

class Object
{
public:
    virtual void outputInfo() =0;

protected:
    int id;
    int cost;
};

and override outputInfo() in sub-classes of Object which print id,cost and other fields.

Call the overridden method -outputInfo() via,

Object *object=new Car;
object->outputInfo();
delete object;

Upvotes: 1

user1610015
user1610015

Reputation: 6668

You need to use dynamic_cast to downcast to the subclass:

if (Car* car = dynamic_cast<Car*>(objects[0]))
{
    // do what you want with the Car object
}
else if (Toaster* toaster = dynamic_cast<Toaster*>(objects[0]))
{
    // do what you want with the Toaster object
}

dynamic_cast returns a pointer to the subclass object if the object's runtime type is actually that subclass, or a null pointer otherwise.

Upvotes: 0

Related Questions