user2471817
user2471817

Reputation: 11

passing reference to object c++

Okay so I'm doing a little for-fun project, I'm an experienced LAMP developer and I decided to mess around with C++

This code is just my attempt at making a working application thats a little bit more difficult than "Hello World" My problem here is in void Defer(). I want to pass a reference to class PoS to my ItemList, so that it can leverage the tax values when returning receipts and calculations

but here is my error that I'm getting:

"ItemList::ItemList(PoS &pos)" provides no initializer for: -- reference member "ItemList::client"

class PoS {
    private:
        /*
            States

            0: Main Menu
            1: Order Menu
            2: Edit Menu
            3: Tax Menu
            4: Business Menu
        */
        int State; 
        vector<ItemList> Orders;
        bool IsLiveFlag;
        double Tax = 0.06;

    public:
        PoS() {
            // Constructor
        }
// .......
        void Defer() {

            string Command;

            gotoMain:
            ShowMain();

            cin>>Command;
            if (tolowercase(Command) == "1") {
                ItemList order(*this);
                Orders.push_back(order);

                State = 1;
                Orders[Orders.size() - 1].Defer();
                State = 0;
            }
        }
}


class ItemList {

    private:
        vector<Item> Items;
        double Subtotal;
        double Tendered;
        bool   Paid;
        PoS&   client;
    public:


        ItemList(PoS& pos) {
            Subtotal = 0;
            Tendered = 0;
            Paid     = 0;
            PoS&    client = pos;
        }

For some reason I can't get a reference to PoS to send over to my ItemList as a parameter, its really frustrating!

Upvotes: 0

Views: 142

Answers (1)

R Sahu
R Sahu

Reputation: 206567

A reference member variable must be initialized before the body of the constructor. That is the meaning of the compiler error message in your post.

Instead of

ItemList(PoS& pos) {
    Subtotal = 0;
    Tendered = 0;
    Paid     = 0;
    PoS&    client = pos;
}

use

ItemList(PoS& pos) : client(pos) {
    Subtotal = 0;
    Tendered = 0;
    Paid     = 0;
}

You can improve on it by using the same syntactic form to initialize the other member variables also.

ItemList(PoS& pos) : Subtotal(0),
                     Tendered(0),
                     Paid(0),
                     client(pos) {}

Upvotes: 2

Related Questions