Search code examples
c++forward-declaration

Why doesn't this class forward declaration compile in C++?


I'm sure that this has been asked, but I cannot find the question or answer, so here is the minimal code I tried to compile.

// goof4.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <iostream>

class A;

class B
{
public:
    A func() { return A{}; }

};

class A
{

};

int main()
{
    B b;
    auto a = b.func();

}

The declaration of B::func gives a "use of undefined type 'A' Error C2027 in MSVC 2022 using /std:c++20. I would have thought that the forward declaration of "class A" would have allowed the compiler to work on B::func until such time as class A was defined. Any help?


Solution

  • Because you have the function body using the (at that point) undefined type A in the class B itself and in a function body the type must already be defined.

    just do A funct(); in the class B itself

    and put the function body and after defining A, A B::funct() { return A{}; }

    https://ide.geeksforgeeks.org/2db37ea7-a62c-487b-8af5-10af8cebc3c6