Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading