I have defined an overloading dereference operator. But when I try to use -> , I expected that the overloading dereference operator is called and return me the pointer to a specific object. After that I want to access the member of the class of this object. However seems that when I use -> the overloading operator does not be called. It is need to explicity call the olverloading operator -> Have a look in the following example
#include <iostream>
#include <string>
using namespace std;
template<typename T>
class GenericRequest
{
public:
GenericRequest()
{
m_request = new T();
}
~GenericRequest()
{
if (m_request)
{
delete m_request;
}
}
T& operator *()
{
return *m_request;
}
T* operator ->()
{
return m_request;
}
private:
T* m_request;
};
class SpecificRequest
{
public:
inline const std::string& getRequest() const {
return m_request;
}
inline void setRequest(const std::string& request) {
m_request = request;
}
private:
std::string m_request;
};
template<typename T>
class ReqData
{
public:
ReqData()
:request(NULL)
{
}
~ReqData()
{
if (NULL != request)
{
delete request;
}
}
GenericRequest<T>* request;
};
int main()
{
ReqData<SpecificRequest> q;
//(q.request)->getRequest();-->This call generates error
q.request->operator->()->getRequest();
return 0;
}
Firstly, (q.request)->getRequest();
leads to UB. Because q.request
is a pointer and is initialized to null pointer.
For your question, q.request
shouldn't be pointer. e.g.
template<typename T>
class ReqData
{
public:
GenericRequest<T> request;
};
then you can
(q.request)->getRequest();