pimpl implementation

Hi, I am trying to implement a pimpl implementation, but seem to have a problem.
This is the header Record.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <vector>

using namespace std;
class RecImpl;
class Record{
	public:
		Record(string t);
		~Record();
		int getId();
		string getTitle();
		friend ostream & operator <<(ostream &os, Record &r);
		friend istream& operator>> (istream &in, Record &r);

	private:
		RecImpl* pimpl;
};

This is the record implemantation, RecImpl.ccp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "Record.h"
static int movieID = 0;

class RecImpl{
	public:
		RecImpl(string t): title(t), id(movieID++){
			cerr << "create " << id << endl;
		}
		~RecImpl(){
			cerr << "DELETING  " << id << endl;
		}
		int getId(){
			return id;
		}
		string getTitle(){
			return title;
		}
	private: 
		string title;
		int id;
};


But when i start the Record.ccp file
1
2
3
4
#include "Record.h"
Record:: Record(string t){
	pimpl=new RecImpl(t);
}

I get and error where i underlined, saying that incomplete type is not allowed. Can anyone tell me what what i'm missing? Thanks
new needs to see the definition of RecImpl.

One solution would be, of course, to move the RecImp class definition into a header and include RecImp.h in Record.cpp, too. But that would prob be the wrong move here as it will expose RecImpl too widely.

Instead you could provide a factory function.

1. Add the following to RecImpl.cpp after the class definition

1
2
3
4
RecImpl* CreateRecImpl(string t){
	RecImpl* pimpl=new RecImpl(t);
	return pimpl;
}


2. Create a new header with just the function definition

1
2
3
4
5
// RecImpl.h

class RecImpl;

extern RecImpl* CreateRecImpl(string t);


3. And then modify Record.cpp to use the factory function

1
2
3
4
5
6
#include "Record.h"
#include "RecImpl.h"

Record::Record(string t){
	pimpl=CreateRecImpl(t);
}

Last edited on
Thanks alot, works now!
Topic archived. No new replies allowed.