Search code examples
c++oopvisual-c++

Forward declaration not working when using as argument in a member function


My forward declaration for class B; before class A doesn't work in the below code, even when this answer mentions that a forward declaration of an incomplete type should work when used in arguments of a function.

It throws an error in A::func() saying "undefined type B". What should be the fix for this, and why does my forward declaration not work in this scenario?

Code

#include <iostream>
using namespace std;

class B;

class A
{
public:
    A()
    {
        cout << "in A's default ctor" << endl;
    }

    void func(B b1)
    {
        cout << "in A's func" << endl;
    }
private:
    int x;
};

class B
{
public:
    B()
    {
        cout << "in B's default ctor" << endl;
    }

    B(const B& b1)
    {
        cout << "in B's copy ctor" << endl;
    }

    B& operator=(const B& b1)
    {
        cout << "in B's copy assignment operator" << endl;
        return *this;
    }
    
};    

int main()
{
    A a;
    B b;

    a.func(b);
}

Solution

  • From the C++17 Standard (6.2 One-definition rule, p.#5)

    A class type T must be complete if

    (5.9) — a function with a return type or argument type of type T is defined (6.1) or called (8.2.2), or

    To avoid the error define the member function func outside the class A after the definition of the class B. For example

    class B;
    
    class A
    {
    public:
        //...
        void func(B b1);
        //...
    };
    
    class B
    {
        //...
    };
    
    void A::func(B b1)
    {
        cout << "in A's func" << endl;
    }
    

    Or without the forward declaration like

    class A
    {
    public:
        //...
        void func(class B b1);
        //...
    };
    
    class B
    {
        //...
    };
    
    void A::func(B b1)
    {
        cout << "in A's func" << endl;
    }