Justin
Justin

Reputation: 405

Problem Initializing an Array Of Structs

I am trying to initialize the following array of the following struct, but my code isn't compiling. Can anybody help me out?

The struct/array:

struct DiningCarSeat {
    int status;
    int order;
    int waiterNum;
    Lock customerLock;
    Condition customer;

    DiningCarSeat(int seatNum) {
        char* tempLockName;
        sprintf(tempLockName, "diningCarSeatLock%d", seatNum);
        char* tempConditionName;
        sprintf(tempConditionName, "diningCarSeatCondition%d", seatNum);
        status = 0;
        order = 0;
        waiterNum = -1;
        customerLock = new Lock(tempLockName);
        customer = new Condition(tempConditionName);
    }
} diningCarSeat[DINING_CAR_CAPACITY];

The relevant errors:

../threads/threadtest.cc: In constructor `DiningCarSeat::DiningCarSeat(int)':
../threads/threadtest.cc:58: error: no matching function for call to `Lock::Lock()'
../threads/synch.h:66: note: candidates are: Lock::Lock(const Lock&)
../threads/synch.h:68: note:                 Lock::Lock(char*)
../threads/threadtest.cc:58: error: no matching function for call to `Condition::Condition()'
../threads/synch.h:119: note: candidates are: Condition::Condition(const Condition&)
../threads/synch.h:121: note:                 Condition::Condition(char*)
../threads/threadtest.cc:63: error: expected primary-expression before '.' token
../threads/threadtest.cc:64: error: expected primary-expression before '.' token
../threads/threadtest.cc: At global scope:
../threads/threadtest.cc:69: error: no matching function for call to `DiningCarSeat::DiningCarSeat()'
../threads/threadtest.cc:51: note: candidates are: DiningCarSeat::DiningCarSeat(const DiningCarSeat&)
../threads/threadtest.cc:58: note:                 DiningCarSeat::DiningCarSeat(int)

Thanks in advance!

Upvotes: 0

Views: 433

Answers (2)

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99685

Condition and Lock are have no default constructors. You should use initialization list to construct them.

I would change/add constructors for Condition and Lock so they could accept const char* and int. Then DiningCarSeat will look like:

DiningCarSeat(int seatNum) : 
  status(0), 
  order(0), 
  waiterNum(-1), 
  cutomerLock( "diningCarSeatLock", seatNum), 
  customer("diningCarSeatCondition", seatNum) 
{}

Upvotes: 1

Seth
Seth

Reputation: 46453

There are multiple issues here:

These should both be pointers, since you are newing them in your constructor:

Lock customerLock;
Condition customer;

You don't declare a type for seatNum:

DiningCarSeat(seatNum) {

You don't allocate memory for tempLockName or tempConditionName:

    char* tempLockName;
    sprintf(tempLockName, "diningCarSeatLock%d", seatNum);
    char* tempConditionName;
    sprintf(tempConditionName, "diningCarSeatCondition%d", seatNum);

Upvotes: 1

Related Questions