I am learning PImpl using the following MyClass
. In the main function, I am using this class. I am getting a compilation error when I try to use the overloaded arrow operator function. The IntelliSense in Visual Studio suggests pointer to incomplete class type is not allowed
and I have attached the screenshot of the exact compiler error. It would be great to know what exactly is the problem here and how exactly to implement an overloaded arrow operator in this case.
// myclass.h
#ifndef MYCLASS_H
#define MYCLASS_H
#include <memory>
class MyClass {
public:
MyClass(int number);
MyClass(const MyClass& other);
MyClass& operator=(MyClass rhs);
~MyClass();
int getNumber();
void setNumber(int number);
struct Impl;
private:
std::unique_ptr<Impl> pimpl;
Impl* operator->();
};
#endif // MYCLASS_H
// myclass.cpp
#include "myclass.h"
struct MyClass::Impl {
Impl(int number) : m_data{ number } {}
int m_data;
};
MyClass::MyClass(int number) : pimpl{ new Impl(number) } {}
MyClass::MyClass(const MyClass& other) : pimpl{ new Impl(*other.pimpl) } {}
MyClass& MyClass::operator=(MyClass rhs) {
std::swap(pimpl, rhs.pimpl);
return *this;
}
MyClass::~MyClass() = default;
MyClass::Impl* MyClass::operator->()
{
return pimpl.get();
}
int MyClass::getNumber() {
return pimpl->m_data;
}
void MyClass::setNumber(int number) {
pimpl->m_data = number;
}
#include "myclass.h"
#include <iostream>
int main()
{
MyClass obj1{ 10 };
MyClass obj2{ 200 };
std::cout << obj1.getNumber() << "n";
std::cout << obj1->m_data << "n"; //compiler error
std::cout << obj1.getNumber() << "n";
std::cout << obj2.getNumber() << "n";
}
The errors are as shown here: