0

So basically I am trying to figure out a way of creating array where each element could be a different type (I am creating an Equipemnt which contains all items owned by player where each item is separate class) Each of classes (B,C,D) has one method of exactly same name which is used when particular tab[] element is clicked onto.

Unfortunately trying to use union did not solve my problem.

Example:

union A
{
B b;
C c;
D d
}
A tab[3];
tab[0]=B item1(a,b,c,...);
tab[1]=C item2;
tab[2]=D item3;
MrSuhar
  • 47
  • 6
  • 4
    You want to look into inheritance and polymorphism. Here's a link to get start, https://www.learncpp.com/cpp-tutorial/111-introduction-to-inheritance/ – noobius Jun 25 '20 at 21:50
  • Look at `std::variant` which "The class template std::variant represents a type-safe union. An instance of std::variant at any given time either holds a value of one of its alternative types, or in the case of error - no value (this state is hard to achieve, see valueless_by_exception). " https://en.cppreference.com/w/cpp/utility/variant – Richard Chambers Jun 25 '20 at 21:52
  • Does this answer your question? [How to store variant data in C++](https://stackoverflow.com/questions/208959/how-to-store-variant-data-in-c) – Richard Chambers Jun 25 '20 at 21:54
  • Did you search at all? There are many, many previous answers to this. – underscore_d Jun 26 '20 at 10:27

2 Answers2

1

Use std::variant type like

std::vector<std::variant<B, C, D>>
stackoverblown
  • 734
  • 5
  • 10
  • I was able to create an array I needed. However I cannot access methods of aforementioned classes held in std::variant. I will post it as other question though. – MrSuhar Jun 26 '20 at 11:28
-1

Better create parent Class called element , then you can create child classes for your items and store all of the objects of child classes in the array with parent class type

//creating objects of items
B gun;  
C knife;

//an array
Element items[2]; 

//adding objects of your items in the array 
items[0]=gun;
items[1]=knife;

By the way better use vector to create array

yusufX019
  • 58
  • 5