-
Stupid Structs Question
How do I make a struct? For example say i'm making a struct named rider, do i need to make a rider.h and then a rider.cpp? All i'm doing is going to be creating a constructor for the rider thats all. So would my file be rider.h
Code:
#include<string>
using namespace std;
struct rider
{
string lastName;
int tickets;
int time;
}
and then i would just compile that with the main.cpp. OR can i just so the struct rider part in the main.cpp before the int main().
-
If your constructor is simple, you can define inside the rider definition and you would not need a rider.cpp file.
You can put the rider definition in its own header file or in the main.cpp if you will only be using it in main.cpp. If you plan on using it in any other cpp files, you should put it in its own header.
If you know anything about classes, the answer is exactly the same as what you would do with a class.
-
Usually classes/structs go into headers (declarations), and then an implementation file (cpp) accompanies it. It's mainly for organization, splitting the code up into chunks.
-
Not only that, but then you can include the header file in multiple source files which can then all use it. See, wherever you use the struct/class you need the declaration, the skeleton:
Code:
class x {
public:
int y;
x();
};
But the implementation
can only exist in one file. So usually the code that needs to be wherever the class is used (declaration) goes in the header file, while the implementation goes in a separate source file.
If you only have one source file (or the struct/class is only used in one source file) then none of this is a problem and you can go ahead and get rid of your header file(s).