Hichigaya Hachiman
Hichigaya Hachiman

Reputation: 307

Overloading with referenced-passed pointer

I'm trying to create a bookstore program that reads inputs from user until EOF. In order to do that, I overloaded the istream >> operator among other things.

class CSales {
public:
    //constructors 

    friend ostream & operator << ( ostream &os, const CSales &x ) const;
    friend istream & operator >> ( istream &is, const CSales &x );

    //m_vars
};
istream & operator >> ( istream &is, const CSales &x ) {
    /* following line prints error:
     * no match for 'operator>>' */
    if ( is >> x.m_isbn >> x.m_price >> x.m_count ) {
        x.m_revenue = x.m_count*x.m_price; //assignment of member is read-only object
    }

    return is;
}

int main() {
    vector<CSales*> dbs1;
    CSales *candidate = new CSales();

    while ( cin >> *candidate ) {
        //sorted by isbn
        auto iter = lower_bound(dbs1.begin(), dbs1.end(), candidate, cmp_isbn);
        //operations 

    return 0;
}
  1. I have a suspicion that the overload is not working because I'm trying to pass a pointer using reference. Am I correct in that assumption?

  2. The way I understood it, const CSales x would be incorrect since I would be changing the pointer, not the object I'm pointing to. So that possibly leaves me with either const CSales &*x or const CSales *&x. What's the difference between those two?

  3. I don't know why the x.m_revenue line is not working, why is it read-only if I don't have the operator as const?

FULL CODE.

EDIT: I'm using a vector of pointers to objects because that should make sorting more efficient (only moving pointers, not the object itself).

Upvotes: 0

Views: 40

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409196

Here is the problem:

istream & operator >> ( istream &is, const CSales &x ) {
//                                   ^^^^^

This tells the compiler that x is constant, that you will not modify x. But as it's an input operator it definitely modifies x or it would not make much sense.

The error message "assignment of member of read-only object" should have been a very clear hint about the issue.

Your suspicion of problems with pointers is a red herring (but I still would recommend you look into a way to not use pointers, pointers in modern C++ is often not needed beyond polymorphism).


And to clarify my first comment:

class CSales {
public:
    ...
    friend ostream & operator << ( ostream &os, const CSales &x ) const;
    //                                                            ^^^^^
    ...
};

The operator<< function is a non-member function, so adding the const qualifier should lead to build-errors. Only member functions can be const qualified.

Upvotes: 1

Related Questions