How can I pass `this` to a constructor without circular references (or losing type) in c++?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-06 21:46:37

You need to separate declaration (in .h files) and implementation (in .cpp files). Then use forward declaration in header files to prevent circular reference. In implémentation files you can use includes.

It will fix your issue but also optimize your compilation.

Check What are forward declarations in C++? and Separating class code into a header and cpp file.

As far as you do not use a class but only declare attributes or parameters as pointers or references to the class you can use class Creator; rather than #include "Creator.h"

Not sure this is best practice, but you can use template to solve this

#include <iostream>

class Creation 
{
public:
    template<typename Creator> // type concept of Creater
    Creation(Creator &whoMadeMe) 
    {
        std::cout << whoMadeMe.age;
    }
};

class Creator 
{
public:
    Creator()
    {
        myThing = new Creation(*this);
    }
    int age = 42;
    Creation * myThing = nullptr;
};

godbolt link: https://godbolt.org/z/ILbFpS

BTW, use new carefully. Or use smart pointers to make life easier.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!