Where to define Public: and Private:

Write your question here.
I have a class with a header file and its associated .cpp file. The header file looks as follows:
1
2
3
4
5
6
7
8
class Item //item.h
{
private:

public:
     Item();
     string itemType;
};

The .cpp file looks like this:
1
2
3
4
5
6
7
8
9
//item.cpp
#include "Item.h"
class Item
{
     Item()
     {
          itemType = "item";
     }
};


In the .cpp file, it doesn't know what itemType is, it says it hasn't been defined, but I clearly defined it in the header file. Where have I gone wrong?
Is it necessary to again declare a private: and public: instead the .cpp file, or is the compiler able to know which is which based on the header file?
Your cpp file definition is wrong.

this is how you define class functions (constructor in this case)
1
2
3
4
5
6
//item.cpp
#include "Item.h"
Item::Item()
{
          itemType = "item";
}

Are you suppose to use a scope resolution to associate Item() to your class Item?

So maybe
1
2
3
4
 Item::Item() 
{
             itemType="item";
 }

instead of
1
2
3
4
5
6
class Item
{
      Item()
      {
             itemType="item";
      }


Just looking at how I do it. But I am a beginner as well.
Last edited on
Thank you both, that clears things up.
One last question: if I didn't have a header file but wanted another class to be able to utilize the functions of this class, could they simply #include the .cpp file?

And to clear things up for anyone who may have the same question:
1. You don't redefine the class in the .cpp file, you simply use the scope resolution operator (::) to specify that it's located in the header file, since the header file is where you defined the class.
2. You don't need to specify public/private inside the .cpp file when already specified in the header.
The files should look like:
1
2
3
4
5
6
7
8
class Item //item.h
{
private:

public:
     Item();
     string itemType;
};

1
2
3
4
5
6
//item.cpp
#include "item.h"
Item::Item()
{
     itemType = "item";
} 
Last edited on
other classes only need to include a header file to make use of a class.

then the other class creates an object instance first from that included class, and only then use the methods of that class on it's object instance.

Topic archived. No new replies allowed.