Muhammad Umer
Muhammad Umer

Reputation: 18097

Access subclass methods from array of superclass in c++?

I have the SuperClass called Transaction, it has methods:

then the subclass called Order has these methods:

so Order inherits from Transaction.

My problem is that there can be multiple types of transactions... Orders, Payment, etc.

Therefore i hold every type of transaction in the array like this:

Transaction trans[100];
trans[0] = Order order(val,val,val);
trans[1] = Order order(val,val,val);
trans[2] = Order order(val,val,val);
...

But now when i call trans[3].Get_item(); i get error that Transaction class has no method Get_item, yes it doesn't but what it's holding has.

I have tried making array an array of pointers and accessing using -> operator. But the problem persists.

Real Code ::::::

vector<Transaction *> trans;
....
Order order(words[0], words[1], words[2], words[3], words[4], words[5]);
trans.push_back(&order);
....
trans[i]->Getitem(); //error here.

Upvotes: 1

Views: 381

Answers (1)

deviantfan
deviantfan

Reputation: 11434

An array like Transaction trans[100]; can't hold subclasses of Transaction, only Transaction itself. If you want an array to hold arbitrary Transaction child classes, make an array of pointers (raw or not doesn't matter). Example with a vector and raw pointers:

std::vector<Transaction *> t;  
t.push_bask(new Transaction()); //insert constructor params if necessary params 
t.push_bask(new Order());  
t[0]->getType();
t[1]->getType();
...
//and don't forget delete, or use smart pointers.

If you additionally need to access methods not available at all in the parent, the compiler needs to know the actual type, ie. it expects you to make an appropriate cast first. If you can't say what type it is, you can't call the method.

((Order*)t[1])->getItem(); //you can do that because you know [1] is a Order  

//but this is wrong and leads to UB:
((Order*)t[0])->getItem();  //wrong!

In some (not all) situations, dynamic_cast can help to test for some type.

Upvotes: 4

Related Questions