Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The whole class in header file without .cpp file

Tags:

c++

I have been working a lot with Java, and C++ is right down confusing.

In Java you have class files, at first I supposed it's the equivalent to header files in C++, like so:

#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've just read that I should separate my classes into two files, the header to define the class, and the .cpp to implement the class.

Should I really do it to each class? because the header class above compiles just fine, and it seems too simple to really separate it to two files, perhaps maybe only large classes should be separated by convention? Any suggestions?

like image 885
julian Avatar asked Feb 10 '23 11:02

julian


1 Answers

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

The reasoning behind this separate-compilation model becomes clear when you work with anything more than a handful of interdependent source files. Since a header can potentially be #include'd all over the place, the separation allows you to make changes to the implementation without needing to recompile all code that is utilizing the interface.

The savings of time can be significant, especially when making a bunch of quick edits to a single file.

(The notable exception to the convention of .h/.cpp pairings is for templated classes - which do indeed just live in a .h file - but that's a whole other story).

like image 189
cowsock Avatar answered Feb 16 '23 03:02

cowsock