Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incomplete type error while using a nested class in a set

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?

like image 720
xieziban Avatar asked Oct 18 '25 10:10

xieziban


1 Answers

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

like image 170
AndyG Avatar answered Oct 21 '25 00:10

AndyG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!