Search code examples
c++stackstack-overflowdistributed-computingcallstack

Can an excessively deep C++ class hierarchy cause a stack overflow?


Suppose I have a C++ program that has excessively deep inheritance as follows:

using namespace std;

class AbstractParentGeneration0 {
    private:
      ...
    protected:
      ...
    public:
      virtual returnVal funcName(void) = 0;
};

class AbstractParentGeneration1: virtual public AbstractParentGeneration0 {
    private:
      ...
    protected:
      ...
    public:
      virtual returnVal funcName(void) = 0;
};

.
.
.

class AbstractParentGeneration999999999: virtual public AbstractParentGeneration999999998 {
    private:
      ...
    protected:
      ...
    public:
      virtual returnVal funcName(void) = 0;
};

class ChildGeneration: public AbstractParentGeneration999999999 {
    private:
      ...
    protected:
      ...
    public:
      returnVal funcName(void) { ... };
};

Suppose the nature of the program is such that the deep inheritance can not be compacted (suppose it represents an evolutionary species lineage or a deep taxonomy hierarchy)

Isn't there a stack overflow danger when calling the top abstract class?

What strategies (other than "ulimit -s bytes" or collapsing the abstract hierarchy) do C++ programmers use to work within system boundaries?

Is there a way to flatten a deep vertical inheritance hierarchy across many host systems via RPC?

Do some people design their own call stack mechanism?

Is there such a thing as a distributed network / cluster call stack?


Solution

  • To answer your specific question, no there will be no danger of stack overflow at runtime when calling the top level abstract virtual method. Most implementations of C++ will have a vtable pointer entry in the object instance that points directly at the appropriate implementation function.

    If you're curious about how this works, I recommend you write such a program with a few levels of hierarchy, and load up an assembly level debugger that shows you what is really going on.