When to #include .h vs .cpp

I am having trouble understanding why some of my programs do not work. From what I understand, .h files are for declarations, and the .cpp files are for implementation. When I #include the .h file in the main, it should take the implementation from the .cpp file with it, shouldn't it?

Here is an example of something I am working on, that does not work unless I #include ShoppingCart.cpp in the main..

If someone could clear this up for me for the future it would be greatly appreciated

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  #include <iostream>
#include "ShoppingCart.h"

using namespace std;

int main() {
	
	Item item1 = Item("Hammer", 4.50);
	Item item2 = Item("Wrench", 3.25);
	
	ShoppingCart shoppingCart = ShoppingCart();
	
	shoppingCart.addItem(item1);
	shoppingCart.addItem(item2);
		
	cout << item1;	
	cout << item2;
	
	cout << "$" << shoppingCart.grandTotal();
	
	return 0;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#ifndef SHOPPINGCART_H
#define SHOPPINGCART_H

#include <vector>
#include "Item.h"

using namespace std;

class ShoppingCart {
	
	public:
		void addItem(const Item& item);
		double grandTotal();
		int numItems();
		
	// Constructor for empty shopping cart
	ShoppingCart();
	
	private:
		vector<Item> shoppingCart;
	
	// Prints out a shopping cart; in other words, a vector of items
	friend ostream& operator<< (ostream& os, const ShoppingCart& sc);
};

#endif 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "ShoppingCart.h"

// Creates an empty shopping cart
ShoppingCart::ShoppingCart() {
	shoppingCart = vector<Item>();
}

// Adds an item to shopping cart
void ShoppingCart::addItem(const Item& item) {
	shoppingCart.push_back(item);
}

// Returns the total price of all items in cart
double ShoppingCart::grandTotal() {
	double total = 0;
	
	for (int i = 0; i < shoppingCart.size(); i++) {
		total += shoppingCart[i].getPrice();
	}
	
	return total;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#ifndef ITEM_H
#define ITEM_H

#include <iostream>
#include <iomanip>

using namespace std;

class Item {
	
	public:
		string getName() {
			return name;
		}
		
		double getPrice() {
			return price;
		}
		
	// Empty constructor
	Item() {
		price = 0;
		name = "";
	}
	
	// Constructor for name and price
	Item(const string& itemName, double itemPrice) {
		price = itemPrice;
		name = itemName;
		
	}
	private:
		double price;
		string name;
		
	// Prints out an item
	friend ostream& operator<< (ostream& os, const Item& item) {
		os << item.name << ", $" << setprecision(2) << fixed << item.price << endl;
		
		return os;
	}	
};

#endif 
Topic archived. No new replies allowed.