0

I have been written 2 classes A,B.
and I want class A to use class B and vice verse

but I have a problem when I tried to get the content of the class like(*A)

that's my code.

#pragma once
#include<iostream>
using namespace std;
class B;
class D
{
	B* b;
public:
	D(void){
     B n(void);
 	 (*b)=n;  //error but why????
	 
	}
	~D(void){

	}
};
#pragma once
class D;
class B
{
	D* d;
public:
	B(void){

	}
	~B(void){

	}
};

Edited by eman 22: the title should be problem with forward declartion

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by mike_2000_17
0

(*b)=n;, the n is undeclared(as an class object) and it is the name of the member function. So what are you trying to do exactly?

0

Basically, the rule goes like this:
- A forward-declaration of a class is sufficient to create and use a variable whose type is a pointer/ref to that class.
- A class declaration is required to create or use a variable whose type is of that class (value).

When you dereference a pointer to class B, you are using a variable whose type is of class B, this requires class B to be fully declared. So, to solve this problem, you need to interleave the declarations and definitions:
1) forward-declare class B
2) declare class D (uses pointer/ref to class B) (no definitions that require B)
3) declare class B
4) define class D (implement functions in D that require the declaration of class B)

Typically, you group 1) and 2) in the "D.h" and you get 3) and 4) into "D.cpp" by #including "B.h" and then implementing the member functions of class D.

Edited by mike_2000_17: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.