Forward declarations, incomplete type

I get

Incomplete type is invalid

mistake. Obviously I don't understand how the declarations work. I know I can't use the methods in the header file, but what about the implementation?

Here is the code:

foo.h:

#pragma once

class Bar;

class Foo {
    const Bar &mBar;

public:
    Foo(const Bar &bar);

    int getVal() const;
};

      

foo.cpp:

#include "Foo.h"

Foo::Foo(const Bar &bar) : mBar(bar) {}

int Foo::getVal() const {
    return mBar.getVal();
}

      

bar.h:

#pragma once
class Bar {
public:
    Bar();

    int getVal();
};

      

Bar.cpp:

#include "Bar.h"

Bar::Bar() {}

int Bar::getVal() {
    return 5;
}

      

mBar.getVal () is what is causing the error. However, it is in the implementation file. Is this also not allowed?

+3


source to share


2 answers


Include in Foo.cpp

header fileBar.h

foo.cpp:

#include "Foo.h"
#include "Bar.h"

Foo::Foo(const Bar &bar) : mBar(bar) {}

int Foo::getVal() const {
    return mBar.getVal();
}

      

Or include a title Bar.h

in the titleFoo.h

foo.h:



#pragma once
#include "Bar.h"

class Foo {
    const Bar &mBar;

public:
    Foo(const Bar &bar);

    int getVal() const;
};

      

Note that the function Bar::getVal

must have a const qualifier

int getVal() const;

      

Otherwise, you will get another compilation error because this non-const function is called from within the const function of the Foo class.

int Foo::getVal() const {
    return mBar.getVal();
    //     ^^^^^^^^^^^ 
}

      

+3


source


Think in terms of the compiler. When it compiles the source file Foo.cpp

and comes to the statement mBar.getVal()

, it has no idea about the members of mBar! All he knows is that mBar is a reference to a const Bar object. But without defining the Bar class visible to the compiler, you cannot access it.



Typically, you send declarations in header files to avoid too many header files (which is important if the header file is part of an externally visible API). In the source file, you must include the header files containing the class definition; in this caseBar.h

+2


source







All Articles