Entire class in header file without .cpp file

I've worked a lot with Java and C ++ is confusing.

In Java you have class files, at first I assumed it is the equivalent of header files in C ++, e.g .:

#ifndef PROGRAM_H
#define PROGRAM_H

#include <iostream>
#include <string>

class Program {
private:
    std::string name, version, author;

public:
    Program(std::string name, std::string version, std::string author) {
        this->name = name;
        this->version = version;
        this->author = author;
    }

    std::string toString() {
        return name + " " + version + " - by " + author + "\n";
    }

} MainProgram("program", "2.0a", "foo bar");

#endif

      

I just read that I have to split my classes into two files, a header for the class definition and .cpp for the class implementation.

Do I really have to do this for every class? because the header class above compiles just fine and it seems too easy to split it into two files, maybe only large classes should be split by convention? Any suggestions?

+3


source to share


3 answers


You should really separate your declarations and definitions (or interfaces and implementations) in the .h and .cpp parses.

The rationale behind this separate compilation model becomes clear when you are working with more than a few interdependent source files. Since the header could potentially be #include'd all over the place, splitting allows you to make changes to the implementation without recompiling all the code that uses the interface.



The time savings can be significant, especially when creating a bunch of quick changes for a single file.

(A notable exception to the convention of .h / .cpp pairs are template classes that do live in the .h file, but that's a whole different story.)

+5


source


The short answer is YES. Thus, if you change the implementation of the class (not the interface), clients using your class do not have to recompile, but only to link a new object file corresponding to the modified implementation.



Long answer: read the C ++ compilation model .

+3


source


Yes. You must separate. You are writing C ++. Not Java. Go and find a book / tutorial to explain this.

-1


source







All Articles