V
V
Vladimir Semenyakin2016-02-24 17:38:19
C++ / C#
Vladimir Semenyakin, 2016-02-24 17:38:19

Why can't you declare stack objects of outer classes for inner classes?

For certain code, there is a need to use the objects of the outer class for the inner class.
Here is what is going to be:

The code being built
class Outer {
public:
  class Inner {
    Outer *_outer;
  public:
    Inner() : _outer(new Outer()) { }
  };

  Outer() { }
};


But this is not:
Code that is not built
class Outer {
public:
  class Inner {
    Outer _outer;
  public:
    Inner() : _outer() { }
  };

  Outer() : _inner() { }
};


Gives an error: " field '_outer' has incomplete type "
Very strange - after all, in both cases, access to the constructor implementation is needed. Why does it work in the first case (when creating an object on the heap), but if it is done "not by a pointer" - no.
PS: By the way, I'll ask at the same time: what is the correct name for objects that are stored in some context not by a pointer?
(edited): Corrected the question based on AtomKrieg 's comment about recursion

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MiiNiPaa, 2016-02-24
@semenyakinVS

A class is considered complete when the closing parenthesis is reached when it is parsed. When declaring a nested class inside an outer class, it is not yet complete and you cannot declare a member of its type. You can create a pointer to an incomplete type, so the first option compiles.
You can fix it like this:

struct Outer 
{
  struct Inner;
};

struct Outer::Inner 
{
    Outer _outer;
    Inner() : _outer() { }
};

R
res2001, 2016-02-24
@res2001

At the very beginning, make an announcement:

class Outer;

class Outer {
private:
  class Inner {
    Outer _outer;
...

It might help.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question