Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forward declarations, Incomplete type

Tags:

c++

I am getting the

Incomplete type is not allowed

error. Obviously I don't understand how forward declarations work. I know I cannot use methods in the header file, but what about in 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 implementation file. Is this also not permitted?

like image 225
Chebz Avatar asked Aug 21 '26 05:08

Chebz


2 Answers

Include in file Foo.cpp header Bar.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 header Bar.h in header Foo.h

Foo.h:

#pragma once
#include "Bar.h"

class Foo {
    const Bar &mBar;

public:
    Foo(const Bar &bar);

    int getVal() const;
};

Take into account that function Bar::getVal must have qualifier const

int getVal() const;

Otherwise you will get one more compilation error because this non-const function is called from a const function of class Foo.

int Foo::getVal() const {
    return mBar.getVal();
    //     ^^^^^^^^^^^ 
}
like image 91
Vlad from Moscow Avatar answered Aug 23 '26 18:08

Vlad from Moscow


Think from the perspective of the compiler. When it is compiling the source file Foo.cpp and comes to the statement mBar.getVal(), it has no idea about the members of mBar! All it knows is that mBar is a reference to a const Bar object. But without making the Bar class definition visible to the compiler you cannot access it's members.

Typically, you do forward declarations in header files to avoid pulling in too many header files( which is important if the header file is part of externally visible API). In the source file you should include the header files that contain the class definition; in this case Bar.h

like image 30
Paani Avatar answered Aug 23 '26 18:08

Paani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!