Ok so, I'm writing a code with a struct [in C++], and I'm not sure whether to implement the struct in the header file or in the source file.
The struct includes a constructor:
struct Point
{
double x;
double y;
Point(double xCo, double yCo)
{
this->x = xCo;
this->y = yCo;
}
int comparePoint(Point point)
{
...
}
};
I wrote in the header file:
typedef struct Point point;
Is it good enough, or is it a bad design? As I read in some websites, a struct is usually implemented in the header file,
but in a previous assignment that I had [in C] the course's staff provided us with a header file that included declaration to the struct and NOT the implementation.
I saw other questions here similar to this one, but they didn't really answer my question.
If the struct is used in multiple C++ files then declare it in the header. If it is limited to one C++ file then putting in that file is fine. As MiNipaa stated, you're confusing definition and declaration. What you have in your header file are declarations, not definitions. A declaration tells the compiler what an object looks like.
Technically, a struct is like a class, so technically a struct would naturally benefit from having constructors and methods, like a class does. But this is only “technically” speaking.
Introduction to C++ Struct Constructor. A structure called Struct allows us to create a group of variables consisting of mixed data types into a single unit. In the same way, a constructor is a special method, which is automatically called when an object is declared for the class, in an object-oriented programming language.
RE: struct's in header files! Because this declares an instance of the data in all the files you include this header in. So if you have more that one file, it gets multiply declared.
You can declare the constructor in the header and write down an implementation in the cpp file:
struct Point
{
Point(double xCo, double yCo);
...
};
Point::Point(double xCo, double yCo)
{
...
}
But there must be a declaration in the header as the compiler depends upon it for building the other cpp files that are dependent on the struct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With