Phil
Phil

Reputation: 13

Error: invalid initialization of reference of type

So I have classes Sensor, Car, and Agency where class Agency takes in class Car, and class Car takes in class Sensor. In my source file for class Agency I have an error for my operator[]`\ function and that says

error: invalid initialization of reference of type Agency& from expression of type Car
  return *invtptr;  

My operator[] function is supposed to be a method to index by-reference an object of the m_inventory data, where it allows you to access the agency's inventory.

Here is my operator[] function:

Agency &Agency::operator[](int index) {
    Car *invtptr = this->m_inventory;
    if (index < 0 || index > 5) {
        cout << "Array is out of bounds, exiting";
        exit(0);
    }
    else {
        for (int i = 0; i < index; i++) {
            invtptr++;
        }   
    }
    return *invtptr;
}

and here are the private members from my header file for class car:

private:
        char m_make[256], m_model[256], m_owner[256];   
        int m_year, m_sensoramnt;
        Sensor m_sensor[3];
        float m_baseprice, m_finalprice;
        bool m_available;

and here are the private members from my header file for class Agency:

private:
        char m_name[256];
        int m_zipcode[5];
        Car m_inventory[5];

Upvotes: 0

Views: 2059

Answers (2)

LLSv2.0
LLSv2.0

Reputation: 543

The problem is your return type. Look at the function protoype:

Agency &Agency::operator[](int index);

This expects you to return an Agent, but you are returning a Car. See excerpts from you code:

Car *invtptr = this->m_inventory;
...
return *invtptr;

You need to change your function to:

Car& Agency::operator[](int index);

Upvotes: 2

Don Slowik
Don Slowik

Reputation: 1120

This is because you are trying to initialize a reference of type Agency& (in the function return) from an expression of type Car (which is the type of *invtptr).

Upvotes: 0

Related Questions