Search code examples
c++constructorcircular-dependencyforward-declarationinitializer-list

Confused by class constructor and initializer list, suspicious of circular dependency


I want to pass a referenced instance of a class through another class's constructor. Now I cannot do so, because I get stuck in syntax error. I tried for several hours, though I learned many things (such as circular dependency or forward declaration), but practically cannot solve my issue. I have this files:

Project.h (the constructor of Project class is passed a reference instance of Buffer class)

Project.cpp

Buffer.h

Buffer.cpp

The above four files are active in my problem (my guess).

Here is Project.h content:

#include<string>
#include<regex>
#include<iostream>
#include<vector>
#include "Buffer.h"

using namespace boost::filesystem;

#ifndef PROJECT_H
#define PROJECT_H

class Project(Buffer & buffer_param) : bufferObj(buffer_param)
{

    Buffer& bufferObj;

public: 
    Filer& filer;

    std::string project_directory;
    void createList(std::vector<std::string> list_title);
};

#endif

Here is project.cpp Content:

#include<string>
#include<regex>
#include<iostream>
#include<vector>
#include<boost\filesystem.hpp>

#include "Project.h"


using namespace boost::filesystem;


void Project::createList(std::vector<std::string> list_title)
{
    //this->filer.createFile();
}

Buffer.h

    #include<string>
    #include<map>


    #ifndef BUFFER_H
    #define BUFFER_H

    class Buffer
    {
        std::map<std::string, std::string> storage_str;

        void setValueString(std::string key, std::string value);
        std::string getValueString(std::string key);
    };

    #endif

Buffer.cpp

#include<string>
#include<map>
#include "Buffer.h"


void Buffer::setValueString(std::string key, std::string value)
{
    this->storage_str[key] = value;
}

PROBLEM:

Without passing the buffer to the project constructor, everything works perfectly, but as soon as I start passing an instance of it, the errors get thrown:

All Errors of Project.h File:

error C2143: syntax error : missing ')' before '&'
error C2143: syntax error : missing ';' before '&'
error C2079: 'Buffer' uses undefined class 'Project'
error C2059: syntax error : ')'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2530: 'buffer_param' : references must be initialized
error C2143: syntax error : missing ';' before ':'
error C2448: 'bufferObj' : function-style initializer appears to be a function definition

Error of Project.cpp File:

error C2027: use of undefined type 'Project' 
     see declaration of 'Project'

Solution

  • To elaborate on deviantfan's comment, instead of this

    class Project(Buffer & buffer_param) : bufferObj(buffer_param)
    {
      ...
    

    There should be this:

    class Project
    {
    public:
      Project(Buffer & buffer_param) : bufferObj(buffer_param)
      {
      }
    
    private:
      ...