Tuesday, January 15, 2008

Default Constructors : C++

Just imagine if your class does not have a default constructor and infact has one that accepts a parameter . In that case few things might not be possible . To illustrate

class Piece{
public:
Piece(int n);

};


Things like these will not work

Piece pieces[10];

Why?? -> cause u don t have a default constructor and trying to create an array of 10 piece instances just tries to call exactly that for every one of them .

Piece * pieces = new Piece[10];

wont work.

How to get it working :

Piece pieces[] = {
Piece(1),
Piece(2),
Piece(3)
};


Another way to get it working would be :

Piece * pieces[10];

: here you are just declaring an array of 10 Piece pointers;

Or Piece* *pieces = new Piece*[10];

But you still need to initialize all the pointers like this :

for(int i = 0;i < 10;i++){ pieces[i] = new Piece(i); }

Another way of initializing accomplishing this would be :

void * memory = operator new[](10 * sizeof(Piece));

this will create memory for 10 piece objects . Now we can go an and make the memory more specific to Piece :

Piece * pieces = static_cast<piece*>(memory);

Now that pieces points to memory for Piece , lets initialize the pieces with code like

for(int i = 0;i < 10;i++){ new(&pieces[i]) Pieces(i); }

Though this arcane technique will get the job done . It seriously is arcane . Not only that it also has the disadvantage of boilerplate code like this :

for(int i = 9;i >= 0;i--){
pieces[i].~Piece();
}

operator delete[] memory;

If we do not follow the 1st approach , we see that what problems we can face . A small hack to get around this problem would be :

class Piece{
public:
Piece(int n = Piece::UNDEFINED);
private:
static const int UNDEFINED;
};


const int Piece::UNDEFINED = -1;

No comments: