1

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?

davidbear
  • 375
  • 2
  • 13
  • 2
    You thought wrong. Read some more about when a forward declaration is necessary and when it is sufficient. – molbdnilo Nov 16 '22 at 05:06
  • 1
    See method 2 given in [this answer](https://stackoverflow.com/a/72474240/12002570) that defines the member function outside the class. – Jason Nov 16 '22 at 05:18

1 Answers1

2

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

MBobrik
  • 318
  • 1
  • 6