user2086751
user2086751

Reputation:

Accessing elements of a child class through parent class in c++?

class game_list
{
    public:
        string name;
        float price;
        string platform;
        string console;
        string condition;
        bool is_portable;
        string N_bits;

};

class catridge_object:public game_list
{
    string N_bits;
    bool is_import;
};

class disk_object:public game_list
{
    string disk_type;
    int n_disk;
};

class digital_object:public game_list
{
    float file_size;
    bool is_for_pc;
};

game_list *pointerMain;

int main()
{
    int optionChosen=0;
    vector<game_list*> mainVector;

}

here game_list is the parent class and there are child classes derived from it. I am trying to create a list of game_class objects that the vector mainVector will hold. Now, depending on user input, all the objects inside the vector will have the common attributes that are described in game_list class and also depending on what user chooses, it will have an additional info from the 3 other child classes derived from the parent class. So I will be creating a dynamic game_list using the following command

pointerMain=new game_list;

Everything seems ok but the problem is when I try to access the child class using pointerMain->(any member of the child class), it doesnt work that way. Any ideas on what to do?

Upvotes: 1

Views: 412

Answers (3)

masoud
masoud

Reputation: 56479

You need cast pointerMain to the derived class type.

catridge_object* obj = dynamic_cast<catridge_object*>(pointerMain);
if (obj)
  obj->members_of_catridge_object...

Also, the base class should be polymorphic, so you need add at least a virtual method in the base class (the best choice is destructor member).

 

or (for certain casts):

static_cast<catridge_object*>(pointerMain)->members_of_catridge_object...;

Be careful it works if pointerMain made by new catridge_object, otherwise the behavior is undefined.

Upvotes: 1

Joe
Joe

Reputation: 6757

Not every child class will have the same members so to access them you will need to know the actual type. Either add a virtual destructor to the base class and use dynamic_cast or put the functionality that needs those attributes into a virtual function (declared in the base class and implemented by the children)

And as others have pointed out new game_list will create an object of type game_list and not of one of the child classes.

If you do choose to go the RTTI (dynamic_cast) route, be sure to check that it returns a non-Null pointer (which it will if the cast-to type does not match)

Upvotes: 0

Deepu
Deepu

Reputation: 7610

It is possible to cast a base pointer into a pointer of the derived type to access a member of the derived class through the base pointer. For example, the following code is valid in C++,

((disk_object *)pointerMain)->n_disk=10;

Upvotes: 0

Related Questions