I have found a similar question here, but my intent is little different.
class B is the embedding class while class A is the embedded class. I want to let B::A have access to member functions of class B. I have seen compilation errors through g++ (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2. The detailed errors are as follows:
~/Documents/C++ $ g++ embed.cpp
embed.cpp:5:7: error: ‘B’ has not been declared
embed.cpp: In constructor ‘B::B()’:
embed.cpp:10:27: error: invalid use of incomplete type ‘struct B::A’
embed.cpp:14:9: error: forward declaration of ‘struct B::A’
Is there a way that I can make it work?
Thank you
#include <iostream>
#include <string>
using namespace std;
class B
{
public:
B() : impl(new B::A(this)) {}
~B(){}
private:
class A; // want to hide the implementation of A
A* impl;
};
class B::A
{
public:
A(B* _parent) : parent(_parent) {} // let embedded class A has access to this parent class
~A() { parent = NULL; }
B* parent;
};
int main(void)
{
return 0;
}
This problem is solved easily if you follow the convention of having the header in one file and the implementation in another.
In file
b.h:In file
b.cpp:My compiler was giving me a different error: in the constructor for
B, you were default-constructing an object that had no default constructor (because it’s an incomplete class). The solution is to implement theBconstructor after classAhas been fully defined, and the header/implementation separation is a natural way to achieve that.