Your array is of the wrong type: it stores BaseClass
object instances instead of pointers to them. Since BaseClass
seems to be abstract, the compiler complains that it cannot default-construct instances to fill your array.
Even if BaseClass
were not abstract, using arrays polymorphically is a big no-no in C++ so you should do things differently in any case.
Fix this by changing the code to:
BaseClass** base = new BaseClass*[2];
base[0] = new FirstDerivedClass;
base[1] = new SecondDerivedClass;
That said, most of the time it is preferable to use std::vector
instead of plain arrays and smart pointers (such as std::shared_ptr
) instead of dumb pointers. Using these tools instead of manually writing code will take care of a host of issues transparently at an extremely small runtime cost.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…