Search code examples
c++structnestedinner-classes

How do I instantiate structs inside a nested class?


So I googled everywhere and cannot get a straight answer to my problem. I haven't touch C++ in a while so I wanted to approach a minimalist coding structure, but I ran into a problem.

I have a parent class call Data in a .h file

I have 2 more classes nested in Data called "Memory" & "Functions"

I created 2 .cpp files, one for each nested classes, "Memory.cpp" stores variable and struct data and "Functions.cpp" stores function data

I am having issues with the "Memory" class

I cannot find a way or solution to instantiate the "Memory" class's structs at all try as I might

Here is my Classes.h file

#pragma once
#include "main.h"

class Data
{
public:

    class Memory
    {
    public:
        //I ALREADY CODED THE STRUCTS IN MY "MEMORY.CPP" FILE
        struct sig;
        struct set;
        struct val;

        //I TRIED WRITING THIS INSIDE THIS PUBLIC CLASS MEMORY AND ITS AN ERROR
        //sig sig0;
        //set set0;
        //val val0;
    };


    class Functions
    {
    public:
        void setup(Memory& gMem);
        void mainLoop(Memory& gMem);
    };

    Memory gMem;
    Functions gFunc;
    

    Data()
    {
        //I'M TRYING TO PASS BY REFERENCE SELF gMem INTO SETUP FUNCTION, 
        //WHICH THE FUNCTION ACCESSES THE STRUCTS INSIDE 
        //THE PUBLIC MEMORY CLASS
        //BUT IT CANNOT EVEN GRANT THIS
        this->gFunc.setup(this->gMem);
        this->gFunc.mainLoop(this->gMem);
    }
};

Here is my main.cpp file

#include "main.h"

int main()
{
    Data run;
    return 0;
}

Here is my main.h file

#include <iostream>
#include <vector>
#include "Classes.h"

I hope this is enough information to get my problem across, I don't wanna post up my "Memory.cpp" and "Functions.cpp" files, its too much information atm. Thank you anyone who is kind enough to help me.


Solution

  • Class members need to be complete types, if the type is incomplete you can only use a pointer or a reference to it.

    So you either need to move the definitions of sig, set and val into the header file or turn sig0, set0 and val0 into references (use with caution, reference members have pitfalls) or (preferably smart) pointers.