daniel
daniel

Reputation: 13

no matching constructor initialization issue in passing pointer to object

I am facing an issue with passing object pointer in parameter.(it's compiler error) I have a 2 class, for simplicity I created class one and class two.

one.h

#pragma once
#include "two.h"
class one
{
private:
    two* t;
public:
    one();
};

one.cpp

#include "one.h"
one::one()
{ t = new two(this);//error: No matching constructor for initialization of 'two' }

two.h

#pragma once
#include "one.h"
class two
{
public:
    explicit two(one*);

};

two.cpp

#include "two.h"
two::two(one*o)
{ }

Upvotes: 1

Views: 96

Answers (2)

Liu Yubo
Liu Yubo

Reputation: 126

you'd better not include two headers in each other,

you can change the #include "one.h" in two.h to a definition like class one;.

include two headers in each other, will confuse the compiler, and make many strange errors.

#include means extend the full header file in there.

and #pragma once make the header file extend only once, you can try to copy the full content of the one.h to where #include "one.h" is, and you will find the problem.

for example, in one.cpp, after extend the header file, the file is like this:

class two
{
public:
    explicit two(one*);

};
class one
{
private:
    two* t;
public:
    one();
};
one::one()
{
    t = new two(this);
}

because there is no declaration or definition of class one before class two, the constructor of class two is not correctly declared, so the error happens.

Upvotes: 0

Ryan Haining
Ryan Haining

Reputation: 36822

In your .h files, add forward declarations for the other classes. When you have headers including each other, one will not actually get the include, otherwise they'd expand to include each other infinitely.

So in one.h you'll have:

#pragma once

class two;  // removed include, added forward declaration

class one
{
private:
    two* t;
public:
    one();
};

Then actually do the include in one.cpp where you need the complete definition of two

#include "one.h"
#include "two.h" // added this include
one::one()
{ t = new two(this);}

Upvotes: 1

Related Questions