Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I implement a struct with constructor in header or source file? [duplicate]

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.

like image 700
Nadin Haddad Avatar asked Sep 13 '12 14:09

Nadin Haddad


People also ask

Should I put a struct in the header or not?

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.

Do structs need constructors and methods?

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.

What is struct constructor in C++?

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.

Why are structs in header files multiply declared?

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.


1 Answers

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.

like image 98
Pavel Ognev Avatar answered Oct 06 '22 21:10

Pavel Ognev