Jump to content
  • Advertisement
Sign in to follow this  
walkingcarcass

quickie -- C++ arrays and constructors

This topic is 4465 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have something essentially like this
class A{
	public:
		A(int,int,int);
};
I can initialise an array of As like this, right? A array[3] = {A(1,1,1), A(2,2,2), A(3,3,3)}; So far so good. What I have now is this:
class B{
	private:
		A array[2][2][2];
	public:
		B() /* HERE */ {
		}
		B(int whatever) /* HERE */ {
		}
};
I want to initialise the array in different ways in the two places marked "HERE". Reason being the operator= is costly. My intuition is to write something like
B() : array({{{A(...),A(...)},{A(...),A(...)}},{{A(...),A(...)},{A(...),A(...)}}}) {}
Unsurprisingly, it doesn't compile. So what instead?

Share this post


Link to post
Share on other sites
Advertisement
The only thing I can think of is to provide a standard constructor for A that basically does nothing. Additionally you'd add a public initialisation method
that acually performs the same operation as A(int,int,int), i.e. A::Init(int,int,int).
You can then - inside the constructor bodies of B, call this Init method on each array-entry.
This might not seem like a clean solution, but neitehr is having a 3D array of objects with a non-trivial constructor [smile]:

class A {
bool isValid;
public:
A(int, int, int) : isValid( true ) {
// perform costly operation.
}
// track validity
A() : isValid( false ) {
// do nothing.
}
// delayed initialisation method
void Init(int, int, int) {
// do not initialise twice!
assert(isValid == false);
// ...
// mark the object to be valid
isValid = true;
}
// ...
};

class B {
A array[2][2][2];
public:
B() {
// initialise contents of "array" - ignore the bitshift-trickery :P
for ( int i = 0; i < 2*2*2; ++i )
array[(i >> 2) & 1][(i >> 1) & 1][i & 1].Init( 0, 0, 0 );
}
B(int x) {
// initialise contents of "array" - ignore the bitshift-trickery :P
for ( int i = 0; i < 2*2*2; ++i )
array[(i >> 2) & 1][(i >> 1) & 1][i & 1].Init( x, x, x );
}
};



HTH,
Pat.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!