简体   繁体   中英

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

I have the SuperClass called Transaction , it has methods:

  • Type
  • Guid
  • Customer

then the subclass called Order has these methods:

  • item
  • quantity
  • cost ...

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM