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;
Tuesday, January 15, 2008
Subscribe to:
Post Comments (Atom)
Labels
. linux
(1)
algorithm
(15)
analytics
(1)
bash
(2)
bigoh
(1)
bruteforce
(1)
c#
(1)
c++
(40)
collections
(1)
commands
(2)
const
(1)
cosine similarity
(1)
creating projects
(1)
daemon
(1)
device_drivers
(1)
eclipse
(6)
eclipse-plugin-development
(9)
equals
(1)
formatting
(1)
freebsd
(1)
game programming
(1)
hashcode
(1)
heap
(1)
heaps
(1)
immutable-objects
(1)
java
(19)
JDT
(1)
kernel
(1)
linux
(4)
little sugar
(23)
logging
(1)
machine learning
(1)
marker-resolution
(1)
markers
(1)
mergesort
(1)
mixins
(1)
numbers
(1)
opengl
(2)
patterns
(2)
priority-queue
(1)
programming
(51)
ps
(1)
ranking
(1)
refactoring
(3)
references
(1)
security
(1)
set
(1)
shell
(1)
similarity
(1)
statistics
(1)
stl
(1)
tetris
(1)
threads
(1)
trees
(2)
unicode
(1)
unix
(2)
views
(2)
windows programming
(2)
XNA
(1)
No comments:
Post a Comment