Trying out a project in codeblocks with a class, I have a header file with the declaration in, a cpp file with the definition in and another cpp with the main code in.
This is the portion of the class definition giving me trouble:
1 2 3 4 5 6 7 8 9 10
#include <iostream>
#include <string>
#include "Sales_item.h"
using std::cout; using std::string;
Sales_item
{
//class definition
}
The opening curly brace is where I get the error message, and if I put
class Sales_item instead then it gives me an error about multiple definitions!
You can only have one of these per cpp file. You've got this one from the header. What's needed now is definition of each of those functions, like this:
1 2 3 4
Sales_item::read_class()
{
// code here
}
and so on.
This
1 2 3 4
Sales_item
{
//class definition
}
is just nonsensical and not anything the compiler will recognise. It thinks you're trying to create an object of type Sales_item, so it's expecting something like this: Sales_item someObject;
This
1 2 3 4
class Sales_item
{
//class definition
};
is seen an an attempt to create a new kind of object - a new kind of class, in fact, named Sales_item, and quite rightly it objects because you've already done that.
Okay so I have to define each function individually (which seems laborious, but is the only way to go about it?). And what about the local variables? In my declaration I have
and none of them need to be initialised (apart from given default values by the default constructor) so is the declaration of them enough or do I have to write something in the definition as well?
Okay so I have to define each function individually (which seems laborious, but is the only way to go about it?).
I must have misunderstood this - how else would you do it? Some kind of mutant all-in-one function? If you like you can do it wrapped inside the class { ...}; in the header file, but you still need to write each function individually.
... none of them need to be initialised (apart from given default values by the default constructor) so is the declaration of them enough or do I have to write something in the definition as well?
No, that's it. They don't even exist (i.e. don't take up any memory) until you actually create an instance of the class. I think under C++11, you can specify default values, but you don't have to.