Forwarding declaration issue

Flaviu_ 971 Reputation points
2024-04-03T07:26:01.5233333+00:00

I have:

// a.h
#pragma once
class B;
class A
{
public:
	void SomeMethod() const;
	B m_b;	// on stack
};
// a.cpp
#include "a.h"
#include "b.h"
void A::SomeMethod() const
{
	//
}
// b.h
#pragma once
#include "a.h"
class B
{
public:
	void OtherMethod(A const& a) const;
};
// b.cpp
#include "b.h"
void B::OtherMethod(A const& a) const
{
	//
}

Error: B m_b; is not recognized. If I put #include "b.h" in a.h file, I got forward declaration error. How can I overcome this?

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,636 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 114.7K Reputation points
    2024-04-03T07:37:17.58+00:00

    For example, try this:

    // a.h
    #pragma once
    
    #include "b.h" 
    
    class A
    {
    public:
    	void SomeMethod( ) const;
    	B m_b;
    };
    
    // a.cpp
    #include "a.h"
    
    void A::SomeMethod( ) const
    {
    	//
    }
    
    // b.h
    #pragma once
    
    class A;
    
    class B
    {
    public:
    	void OtherMethod( A const& a ) const;
    };
    
    // b.cpp
    #include <regex>
    #include "a.h"
    #include "b.h"
    
    void B::OtherMethod( A const& a ) const
    {
    	//
    }
    
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful