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?

2
  • 2
    You thought wrong. Read some more about when a forward declaration is necessary and when it is sufficient. Commented Nov 16, 2022 at 5:06
  • 1
    See method 2 given in this answer that defines the member function outside the class. Commented Nov 16, 2022 at 5:18

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.