# [C++] Help please - Class problems

This topic is 2519 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi guys,

I'm pretty new to C++ and I am experiencing a problem and hoping someone can help me to solve this. I have created a class called Food which has a header file and a cpp file (food.hpp and food.cpp). I also have another cpp file called MainFrame.cpp, but this is not a class. The problem I'm stuck with is trying to create an food object in the MainFrame.cpp, but I keep getting errors. Can someone tell me how exactly do you create a object of a class (food) within an different cpp file please? Here's my codes:

//Food.hpp
#ifndef FOOD_H
#define FOOD_H

class Food
{
public:
Food(std::string setName, double setPrice);
~Food(void);

std::string name;
double price;
};

#endif

---------------------------------------------------------------------------------------------------

//Food.cpp
#include<string>
#include "Food.h"

Food::Food(std::string setName, double setPrice)
{
name = setName;
price = setPrice;
}

Food::~Food(void)
{
};

---------------------------------------------------------------------------------------------------

//MainFrame.cpp
#include<iostream>

using namespace std;

int main()
{
Food::food("beef", 3.80);
}

---------------------------------------------------------------------------------------------------

Thanks.

##### Share on other sites
Why do you have a : after the } in the Destructor? Try to remove it..

and you also have to create an instance of Food

 int main () { Food *food = new Food ("beef", 3.80); // work with food delete food; // when u don't need it anymore return 1; } 

##### Share on other sites
Hi flyingdutchman,

Thanks for the reply. I have removed the ; after the destructor and tried the code you've suggested, but I am still getting the error. Heres the error messager: 'error C2653: 'Food' : is not a class or namespace name'

Do i need to include the food.cpp in my mainframe.cpp by any chance?

P.S. this food is expensive because it's organic ^^ lol

##### Share on other sites
You need to #include Food.h into MainFrame.cpp. You do not need dynamic allocation.
 #include <iostream> #include "Food.h" using namespace std; int main() { Food food("beef", 3.80); std::cout << "We have some " << food.name << " for " << food.price << '\n'; } 
Your food header should #include <string>, as it makes use of std::string. Your Food.cpp should include Food.h as the first line, that way you'll catch errors like omitting the <string> include.

You never include cpp files*.

* [size="1"]Unless you know what you're doing.

##### Share on other sites
Thanks alot. That solved the problem . Thanks again guys

1. 1
2. 2
3. 3
JoeJ
20
4. 4
5. 5
frob
19

• 11
• 11
• 12
• 13
• 9
• ### Forum Statistics

• Total Topics
632213
• Total Posts
3004850

×