Is there a syntax in C++ to initialize an array of pointers to objects with different types without extra assignments? I tried to provide a complete example below.
#include "stdio.h"
class Base {
public:
Base(int cnt=1) : _cnt(cnt) {}
virtual void print() { printf("?\n"); }
protected:
int _cnt;
};
class A : public Base {
public:
A(int val, int cnt=1) : _val(val), Base(cnt) {}
void print() override { for (int i=0; i<_cnt; i++) printf("A(%d)\n", _val); }
private:
int _val;
};
class B : public Base {
public:
B(const char* val, int cnt=1) : _val(val), Base(cnt) {}
void print() override { for (int i=0; i<_cnt; i++) printf("B(\"%s\")\n", _val); }
private:
const char* _val;
};
// *** I would like to combine the following statements ***
A a = { 42, 2 };
B b = { "hi there", 3 };
Base* test[] = { &a, &b };
int main() {
for (auto *x : test) { x->print(); }
}
When I try
Base* test2[] = {
&A(42, 2),
&B("hi there", 3),
};
I get errors for taking address of temporary. The code needs to run code on a small embedded system, so I try to avoid dynamic allocation.
Hope this is not a FAQ ...
Thanks for any help!