Re: Array of objects from class without default constructor
Matthias wrote:
As far as I know, it's not possible to get an array new-expression call
a class constructor with parameters. Thus, it is non trivial to build an
array of object belonging to a class, say A, without default constructor.
To bypass this limitation, one can add a trivial constructor to class
A. The resuting code looks like the following:
[code]
I don't feel confortable with this solution: from my program design it's
non-sense to build an A object without specifying its size...
Are there other solutions to the `array of objects from class without
default constructor' problem? Does my solution looks horrible to C++
aesthetes?
(not a C++ expert, take everything below with a biiig grain of
salt)
Well, you could always decide to over-engineer and do something
like this (assuming you have control over the class interface):
#include <iostream>
#include <ostream>
class NextSizeCallback {
public: virtual int operator()() = 0; };
class IncCallback: public NextSizeCallback {
public: IncCallback(): n_(1) { }
virtual int operator()() { return n_++; }
private: int n_; };
class A {
public: static void setNextSizeCallback(
NextSizeCallback* c) { A::c_ = c; }
static int getNextSize() { return (*A::c_)(); }
A(): n_(getNextSize()) { }
int getSize() const { return n_; }
private: static NextSizeCallback* c_;
int n_; };
NextSizeCallback* A::c_ = NULL;
int main() {
IncCallback i;
A::setNextSizeCallback(&i);
A* t = new A[10];
for (int i = 0; i != 10; ++i)
std::cout << t[i].getSize() << std::endl;
return 0; }
I doubt this is any better in terms of readability and
maintainability than using placement new and creating your
objects explicitly, though.
--
Waterfall: One Process To Rule Them All