1

I've solved the problem by putting #include "stdafx.h" (this statement is missed in the original question, sorry for that) BEFORE #include "PImplTest.h" instead of AFTER it.

But I'm still confused why it cannot stay after it.

// stdafx.h
#include <tinyxml2.h>
#include <queue>
#include <map>
#include <vector>
#include <list>
#include <set>
#include <stack>
#include <string>
#include <memory>
#include <assert.h>

----------------------- the original question --------------------------------

I'm trying to use the PImpl pattern in C++. The header file is:

// PImplTest.h

#pragma once
#include <memory>

class PImpl
{
private:
    class Impl;
    std::unique_ptr<Impl> m_impl;
};

What confuses me is, if I implement the Impl class in the corresponding cpp file of the header like this:

// PImplTest.cpp
#include "PImplTest.h"
#include "stdafx.h" // this statement was missed in my first post

class PImpl::Impl // error C2079 'Impl' uses undefined class 'PImpl'
{ // error C2653 'PImpl':is not a class or namespace name
};

// main.cpp
#include "stdafx.h" // this statement was missed in my first post
#include "PImplTest.h"

int main()
{
    return 0;
}

VS reports the 2 errors in the code comments above. However, if it is implemented in a file like this:

// main.cpp
#include "PImplTest.h"

class PImpl::Impl
{ 
};

int main()
{
    return 0;
}

Then nothing goes wrong.

What's the problem? How to fix it?

Irene
  • 11
  • 3
  • 1
    Are those the *only* `#include` directives, and in particular do you have other headers that include or are included by `PImplTest.h`? – dxiv Oct 29 '20 at 08:14
  • nope, these are all the code – Irene Oct 29 '20 at 08:49
  • 1
    Heads up: you will need to add `~Pimpl();` in your header and `Pimpl::~Pimpl() = default;` in your cpp file so that `std::unique_ptr`'s destructor is instantiated when `Impl` is complete. – Quentin Oct 29 '20 at 09:15
  • Is the error message that you quote the _first_ error message output by the compiler? – paddy Oct 29 '20 at 09:51
  • I'm very sorry for missing a line of code AFTER "#include"PImplTest.h"" in the file of PImplTest.cpp in the first case, that is "#include"stdafx.h"". When I put it BEFORE the include statement of PImplTest.h, everything is right. But I'm still confused, why the include of pch should stay before the include of PImplTest.h? – Irene Oct 29 '20 at 09:57
  • Irene, the errors indicate the compiler doesn't actually see the header; if it's access the wrong file etc. Try placing the contents of the header inside the .cpp file and see what happens then. And - maybe post a self-contained program which fails to compile. – einpoklum Oct 29 '20 at 10:36
  • @Irene See [Why stdfax.h should be the first include on MFC applications?](https://stackoverflow.com/questions/16040689/why-stdfax-h-should-be-the-first-include-on-mfc-applications) Voting to close as a duplicate. – dxiv Oct 29 '20 at 16:38

0 Answers0