0

I have an object SeatSelection. In this object, I declare a array of integer arrays as follows

int *rows[25];

My SeatSelection constructor initializes the rows variable as follows:

SeatSelection::SeatSelection(int start, int range){
  this->range = range;
  this->start = start;

  for(int i = 0; i < range; i++){
    rows[i] = new int[10];

  for(int j = 0; j < 10; j++)
    rows[i][j] = (j+1);
  }
}

In theory, I should now have an array of integer arrays of size 10 right?

In my driver class,

I am declaring two SeatSelection objects, both with different paramaters:

SeatSelection premium(1,5);
SeatSelection regular(6, 15);

premium should have 5 rows of 10 seats each = 50 seats.

regular should have 15 rows of 10 seats each = 150 seats.

Through some debugging, I found out that both these distinct SeatSelection objects are sharing the same rows pointer/array. I did not declare this variable as static. Why is this happening?

17
  • 6
    Did you consider std::vector ? Commented Oct 18, 2013 at 21:41
  • 5
    Debug output and an SSCCE or it didn't happen. Commented Oct 18, 2013 at 21:44
  • This is for an assignment where we are not allowed to use std::vector. Our arrays must be done "by hand." Commented Oct 18, 2013 at 21:45
  • 2
    @OmarDarwish: No. I want you to build an SSCCE that demonstrates the same problem. 20 lines of code ought to do it. Commented Oct 18, 2013 at 21:50
  • 1
    Here's something that will blow your mind. Since rows was a global, it actually did have implicit static lifetime! Commented Oct 18, 2013 at 21:58

2 Answers 2

1

To get a separate rows variable for each class instance, it's not sufficient to make the variable "not static".

You have to make it a class member to give it per-instance storage.

Other non-static variables have the storage duration determined by their scope. A non-static namespace-member (including the global namespace) variable has one copy for the entire program. A non-static local variable has one copy per invocation of the function.

Sign up to request clarification or add additional context in comments.

1 Comment

@John: Agreed. Your crystal ball worked quite well for this one.
0

Looks like int *row[25] are not part of SeatSelection class. You may have row[] array locally / globally declared and each of SeatSelection object is using same space. After premium object writes to row[] memory, regular object overwrites it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.