954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Arrays in relation to constructors.

Quick question from someone very new to constructors... If the function body of a class constructor is an array, can I then use any instantiation of that class just like an array?

ie: World *anthill and then later... anthill[x][y]

or is that wishful thinking?

-Ella

SuperSapien
Newbie Poster
3 posts since Oct 2008
Reputation Points: 10
Solved Threads: 0
 

You need to look into operators,
You may find this useful
http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html

Chris

Freaky_Chris
Master Poster
702 posts since Apr 2008
Reputation Points: 325
Solved Threads: 118
 

ok Thank you.. that makes sense. I have some rudimentary knowledge of operator overloading already.

All arrays I'm using are 2D. For example, in my world class, I'm trying to build a constructor that looks like this..

World::World()
{
for (int i = 0; i <= 19; i++)
{
for (int j = 0; j <= 19; j++)
{
//creates an empty array
}
}
//calls fillGrid();
}


So in the operator overload function body, can I just do something like this which, to me, seems to say "Whenever you encounter an instance of these guys [], do the following.."? int& ClassName::operator[]( int indx ) {
if( indx < 0 || indx >= size ) {
//some error handling
exit(-1);
}

return data[indx];
}

I found the above snippet online but the example of this overload worked with a class that only used lists, not grids.

Thanks again..

Ella

SuperSapien
Newbie Poster
3 posts since Oct 2008
Reputation Points: 10
Solved Threads: 0
 

i may have over complicated it for you :lol: my apologise. Ofcourse this is depending on whether or not you have the array in the class as private or public. if it is private then ok you need to go down the operator route, if its public then you can use class.arrayname[][] as normal.

Freaky_Chris
Master Poster
702 posts since Apr 2008
Reputation Points: 325
Solved Threads: 118
 

Thanks :) That makes sense. This was sort of why I had an instinct to build the default constructor like this. I saw how someone else tried to do this and it seemed quite intuitive.

Thanks for your time.

-Ella

SuperSapien
Newbie Poster
3 posts since Oct 2008
Reputation Points: 10
Solved Threads: 0
 

It's ok, if thats everything mark as solved please

Chris

Freaky_Chris
Master Poster
702 posts since Apr 2008
Reputation Points: 325
Solved Threads: 118
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You