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){

	}
};

Recommended Answers

All 2 Replies

(*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?

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.