Hatefiend Hatefiend - 11 months ago 77
C++ Question

C++ - Incomplete class type?

I've been working with a lot of C and Java lately so I'm a bit confused coming back to C++ on why this is not allowed.

incomplete type is not allowed

#pragma once

class Expression
Expression power; // <--- incomplete type is not allowed

I believe the answer here is to change the line
Expression power
Expression *power
but I don't understand why that is. I can declare objects like
vector<int> var
without having to make them a pointer, but the second I have an object of the same type as the file it's being declared in, I need one? I've looked around but cannot find any tutorials/videos on a class making an object of itself.

Answer Source

If you put an instance of a class inside itself, if you notice, you are creating recursion, since every instance has its own Expression power, and this goes on forever. If you have a pointer though, you can control this infinite recursion, since at any time you can set power to nullptr, (or NULL/0, pre C++11), to end the recursion.