elo
elo

Reputation: 541

Separate class declaration from definition

I would like to separate class definition and declaration into 2 separate files: foo.hpp and foo.inl.

foo.hpp file has Foo class declaration with its' description, and also this file includes foo.inl:

/* foo.hpp */

// Foo class description comment
class Foo;

#include "foo.inl"

foo.inl contains Foo definition without any code-description comments.

/* foo.inl */

class Foo {
    Foo() = default;

    void bar() {
        /* do something */
    }
}

I am trying to write commentaries for Foo's methods in foo.hpp to make it look like this:

/* foo.hpp */

// Foo class description comment
class Foo;

// This is my default constructor
Foo::Foo();

// This is my very helpful function
Foo::bar();

#include "foo.inl"

But compiler gives an understandable error: invalid use of incomplete type 'class Foo'.

So is there any way how can I declare functions and write comments for them in such a way?

Upvotes: 0

Views: 1372

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409364

Foo::Foo(); and void Foo::bar(); area member function declarations, and those are not allowed outside of a class.

You have it a little bit backward, define the class in the "main" header file foo.hpp. Then define the functions as inline in the "inline" header file foo.inl.

Perhaps something like this:

// Foo.hpp
#pragma once

class Foo
{
public:
    // The default constructor
    Foo();

    // This is my very helpful function
    void bar();
};

#include "Foo.inl"

Then the inline file:

// Foo.inl
#pragma once

inline Foo::Foo()
{
}

inline void Foo::bar()
{
}

If the inline functions are simple enough, put them inside the Foo class definition in the main header file Foo.hpp instead. And if they're too complicated to really be inline, put them in a separate source file Foo.cpp to be built with your application (but not included with #include).

Upvotes: 1

Jarod42
Jarod42

Reputation: 217810

If you want to split definition and declaration of class methods, you have to define the class:

// .h

// That is my class Foo
class Foo {
    // Constructor
    Foo();

    // This is my very helpful function
    void bar();
};

and

// cpp
Foo::Foo() = default;

void Foo::bar() {
    /* do something */
}

Upvotes: 1

Related Questions