There is a lot more that is supposed to go with this. For now, I'm just trying to implement a class that uses a vector. Class is called ItemList, it's the header file. Main creates the object and attempts to add to the vector. Compiler doesn't recognize "list" as a class, even though I've declared it. Could it be that I missed something in the constructor? I'm not sure of the relationship between the ItemList class and the vector, since the class is just supposed to be a vector.

testShoppingCart.cpp

    #include <string>
    #include <iostream>
    #include "ItemList.h"
    //#include "ShoppingCart.h"
    //#include "ItemOrder.h"
    #include "Item.h"
    using namespace std;

    int main()
    {

    //  ShoppingCart cart();
    //  ItemOrder order();


        string n = "dog";
        int p = 300;
        Item item(n,p);

        int pp;
        pp = item.priceFor();
        cout << "Item price: " << pp << endl;

        string theItem = item.toString();
        cout << theItem << endl;

        ItemList list();

        list.add(Item("silly putty",3));
        }

ItemList.h

#ifndef ItemList_h_
#define ItemList_h_
#include <vector>
#include "Item.h"

using namespace std;

class ItemList{
public:
    ItemList();
    //ItemList(vector<Item> l);
    void add(Item);
    int size();
    void get(int);

private:
    vector<Item> l;
};

ItemList::ItemList(){
    vector <Item> item;
}

void ItemList::add(Item i){
    l.push_back(i);
}

//void ItemList::add(Item product){
//  list.ItemList::item.push_back(product);
//}

Item.h

#ifndef Item_h_
#define Item_h_

#include <iostream>
#include <ostream>
#include <string>
#include <sstream>

using namespace std;

class Item {

public:
    Item(const string& n, const int& p) : name(n), price(p) {}
    Item();
    //~Item();
    int priceFor();
    string toString() const;

private:
    string name;
    int price;
};


int Item::priceFor(/*int p*/) {
     return Item::price;
}

string Item::toString() const {
    ostringstream result;
    result << name << ", " << "$" << price << "." << '\n';
    return result.str();
}

#endif

ItemList list();

This doesn't do what you think it does. Due to a parsing ambiguity, the resolution of the above declares a function called list that takes no arguments and returns an object of type ItemList. It doesn't create a new object called list with a type of ItemList, to do that you need to remove the parens:

ItemList list; // Create a new ItemList called list

Confused yet? ;)

So then to instantiate a class with the default constructor, omit parentheses, but with parameters, use parens (along with params)?

So then to instantiate a class with the default constructor, omit parentheses, but with parameters, use parens (along with params)?

Intuitive, isn't it? :D

This article has been dead for over six months. Start a new discussion instead.