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

Recommended Answers

All 5 Replies

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

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.

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

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

Chris

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.