I come from Java that has a different way in handling what's private and has to be hided regarding a class implementation and it also has a garbage collector which means there is no need for a destructor.
I learned the basics of how to implement a class in c++ but I need to better understand how to implement a class, in particular the constructor and destructor, when using the pimpl idiom.
hpp file:
class MyClass{
public:
MyClass();
MyClass(std::vector<int>& arr);
~MyClass();
private:
struct Impl;
Impl* pimpl;
};
cpp file:
#include "MyClass.hpp"
using namespace std;
struct MyClass::Impl{
vector<int> arr;
int var;
};
I wrote the sample code of a class I need to work on(which means I can't change the way the pimpl idiom is used) using the pimpl idiom and I'm looking for an answer to these questions:
- How do I implement the constructor to create an empty instance of MyClass?
MyClass::MyClass(){}
- How do I implement the constructor to create an instance of MyClass with these arguments?
MyClass::MyClass(vector<int>& arr,int var){}
- How do I implement the destructor?
MyClass::~MyClass(){}
EDIT:
How I would do it:
MyClass::MyClass(): pimpl(new Impl) {}
MyClass::MyClass(vector<int>& arr,int var): pimpl(new Impl) {
pimpl->arr=arr;
pimpl->var=var;
}
MyClass::~MyClass(){
delete pimpl;
}