E
E
evilandfox2016-08-03 23:09:23
Programming
evilandfox, 2016-08-03 23:09:23

Two classes refer to each other and lie in different .h files (without .cpp). How to do?

Here is an example sketched:

//parent.h
#pragma once
#include <QObject>
#include "child.h"

class Parent : public QObject {
    Q_OBJECT
public:
    Parent() : QObject()
    {
        child = new Child(this);
    }
private:
    Child *child;
};

//child.h
#pragma once
#include <QObject>
#include "parent.h"

class Parent;

class Child : public QObject {
    Q_OBJECT
public:
    Child(Parent *_parent) : QObject(_parent), parentPtr(_parent)
    {}
private:
    Parent *parentPtr;
};

Compiler in Qt (MinGW 4.9) spits out an error
C:\Users\Winner\Documents\example\child.h:11: ошибка: no matching function for call to 'QObject::QObject(Parent*&)'
     Child(Parent *_parent) : QObject(_parent), parentPtr(_parent)
                                                                 ^

How to fix the code so that everything works? I will be very grateful

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rou1997, 2016-08-04
@evilandfox

Child(Parent *_parent) : parentPtr(_parent)

#
#algooptimize #bottize, 2016-08-03
@user004

forward declaration?

A
Anton Zhilin, 2016-08-03
@Anton3

You have 2 classes that refer to each other. From an architectural point of view, this situation is called tight coupling, and you need pretty good reasons to allow it. Tell us more about what Parent and Child do, maybe you can refactor the code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question