Function declaration inside or outside the class

JohnJohnGa picture JohnJohnGa · Jan 31, 2012 · Viewed 88.2k times · Source

I am a JAVA developer who is trying to learn C++, but I don't really know what the best practice is for standard function declarations.

In the class:

class Clazz
{
 public:
    void Fun1()
    {
        //do something
    }
}

Or outside:

class Clazz
{
public:
    void Fun1();
}

Clazz::Fun1(){
    // Do something
}

I have a feeling that the second one can be less readable...

Answer

6502 picture 6502 · Jan 31, 2012

C++ is object oriented, in the sense that it supports the object oriented paradigm for software development.

However, differently from Java, C++ doesn't force you to group function definitions in classes: the standard C++ way for declaring a function is to just declare a function, without any class.

If instead you are talking about method declaration/definition then the standard way is to put just the declaration in an include file (normally named .h or .hpp) and the definition in a separate implementation file (normally named .cpp or .cxx). I agree this is indeed somewhat annoying and requires some duplication but it's how the language was designed.

For quick experiments and single file projects anything would work... but for bigger projects this separation is something that is practically required.

Note: Even if you know Java, C++ is a completely different language... and it's a language that cannot be learned by experimenting. The reason is that it's a rather complex language with a lot of asymmetries and apparently illogical choices, and most importantly, when you make a mistake there are no "runtime error angels" to save you like in Java... but there are instead "undefined behavior daemons".

The only reasonable way to learn C++ is by reading... no matter how smart you are there is no way you can guess what the committee decided (actually being smart is sometimes even a problem because the correct answer is illogical and a consequence of historical heritage.)

Just pick a good book or two and read them cover to cover.