can new[] call a customized constructor ? Howto make a union of pointers on arrays ?

Hi all,
can new[] call a customized constructor ?
In addition, I would like to do something like this, a kind of union of pointers :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class MyPointer {
public:
  MyPointer(int aClassId) : mClassId(aClassId) {};
  operatornew[]();
  Class0& operator*() {return *ptr0;}
  Class0* operator->() {return ptr0;}
  Class0& operator[](int aN) {return ptr0[aN];}
  Class1& operator*() {return *ptr1;}
  Class1* operator->() {return ptr1;}
  Class1& operator[](int aN) {return ptr1[aN];}
private:
  int mClassId;
  Class0* ptr0;
  Class1* ptr1;
}

MyPointer::operatornew[](size_t aSize) {
  switch (mClassId) {
    case 0 : {
      ptr0 = new Class0[aSize];
      break;
    }
    case 1 : {
      ptr1 = new Class1[aSize];
      break;
    }
  }
}


Any advice is welcome.

the alternative I use today but which is very unconveniant is to have a voi* pointer and to have if/else with static_cast of the pointers !!!
Last edited on
If you use this thing with a Class0*, but you've constructed a Class1*, there's no compile time check that you're doing the wrong thing. This is not the sort of problem you want to defer until runtime to discover.
Last edited on
Topic archived. No new replies allowed.