I am working on translating some Java code into C++. When I try to write code like:
.h:
class A {
private:
class B;
std::set<B> b_set;
};
.cpp:
class A::B {
};
I got an incomplete type error. I understand that that is because the nested class is incomplete before using it in b_set
. But what's the best way to fix it?
You can describe your entire B
class in the .h
file.
Here's a working example.
#include <set>
class A {
private:
class B{
B() : foo(1) { }
int foo;
};
std::set<B> b_set;
};
However, if you want to separate your definition and instantiation, you can do this:
A.h
#include <set>
class A {
private:
class B {
public:
B();
private:
int someMethod();
int foo;
};
std::set<B> b_set;
};
A.cpp
#include "A.h"
A::B::B() : foo(1) { }
int A::B::someMethod() {
return 42;
}
Generally speaking, nested classes can be a serious PITA because of all the hoops you have to jump through to access anything from them.
Another good reference on nested classes: Nested class definition in source file