Why do you split the definition and declaration of functions in c++?

Viewed 827

I usually code in Java, but I have started to learn c++ as I'm trying to get into some competitive programming. What is confusing for me right now is that in java you can declare a method within a class, make it public and thats that.

For example, in Java:

public class Main{
    public int javamethod(int myNum){
        return myNum;
    }
}

Whereas in C++, you split the function declaration and definition into different files (like cprogram.hpp and cprogram.cpp). Isn't this redundant and repetetive? What exactly is the point of this?

C++ example (header file)

int cppfunc(int myNum);

(cpp file)

int cppfunc(int myNum){
    return myNum;
}
1 Answers

There are 3 reasons:

  1. Function must be declared before it can be called. So if you have fun1() calling fun2() and vice versa you cannot write implementation for each upon declaration.

  2. To hide dependencies. If implementation is dependent on some include and you don't want to require every user of the function to include it - then you have to split declaration and implementation.

  3. C++ follows crappy archaic build scheme. Headers are copy pasted into other headers and are rebuild each time. Compilation time will rise to ridiculous numbers as each header is recompiled again and again.

Issues 2 and 3 are addressed in C++20. Modules TS solves these two issues and with them you'll be able to write functions without splitting definition and implementation just like in Java without any issues.

Note: you don't have to split declaration / definition. You only need to make the function inline as otherwise linker might scream at you.

Related