I come from Java (OOP) background. I made a simple class to illustrate my problem:
#include <list>
#include <string>
#include <iostream>
// classes
class InterfaceA
{
public:
virtual std::string functionA();
};
class InterfaceB
{
public:
virtual std::string functionB();
};
class DerivedAB : public InterfaceA, public InterfaceB
{
public:
std::string functionA()
{
return "I'm a A object";
}
std::string functionB()
{
return "I'm a B object";
}
};
// functions
void doStuffOnListOfA(std::list<InterfaceA*> aElements)
{
std::cout << "Print list of A" << std::endl;
for (InterfaceA* const& a : aElements)
{
std::cout << a->functionA() << std::endl;
}
};
int main()
{
std::list<DerivedAB*> derivedABs;
doStuffOnListOfA(derivedABs);
return 0;
}
I have two simple virtual classes InterfaceA
and InterfaceB
and a class DerivedAB
that multi-inherits the two first virtual classes.
Furthermore, I then create a list of pointers of DerivedAB
(std::list<DerivedAB *>
) and wish to use this list with a function designed to work on a list of InterfaceA
-derived objects. But I get an error:
(base) ❮ onyr ★ kenzae❯ ❮ multi_inheritance_type_convertion❯❯ make
g++ -c -o main.o main.cpp
main.cpp: In function ‘int main()’:
main.cpp:54:32: error: could not convert ‘derivedABs’ from ‘std::__cxx11::list<DerivedAB*>’ to ‘std::__cxx11::list<InterfaceA*>’
doStuffOnListOfA(derivedABs);
I have obviously a type casting error. I have read many articles on Stack Overflow about the different casting in C++ as well as on Multi-Inheritance, but my brain refuses to give me the answer.
Edits:
I said an erroneous statement:
"However I'm pretty sure such a code would work in Java..."
Apparently I'm missing an important concept about type inheritance...