I have a class Response
that has a public member which is of another class type ResponseData
. ResponseData
has a string
member.
What I've notice is that upon inspecting Response->responseData
and Response->responseData->data
, the value of ResponseData*
and the address of ResponseData->data
are the same.
Somehow the value of the pointer to the class is the same as the address of that class's string member.
https://onlinegdb.com/Bk-kJ3a_z
#include <iostream>
#include <string>
#include <vector>
// ResponseData
class ResponseData {
public:
std::string data;
ResponseData();
~ResponseData();
void PrintToConsole();
};
ResponseData:: ResponseData(){
data = "some data";
}
ResponseData::~ResponseData(){}
void ResponseData::PrintToConsole(){
std::cout << this->data << std::endl;
}
// Response
class Response {
public:
ResponseData *responseData;
Response();
~Response();
void SetResponseData(std::string data);
ResponseData* GetResponseData();
};
Response::Response():responseData(NULL){}
Response::~Response(){}
void Response::SetResponseData(std::string data){
this->responseData = new ResponseData();
this->responseData->data = data;
}
ResponseData* Response::GetResponseData(){
return this->responseData;
}
int main(){
Response response;
response.SetResponseData("hello");
ResponseData* responseData = response.GetResponseData();
// value of ResponseData* and address of ResponseData->data are the same..?
std::cout << responseData << std::endl;
std::cout << &responseData->data << std::endl;
responseData->PrintToConsole();
return 0;
}
I don't even know if this is a problem because my code runs fine. But it doesn't make sense to me. Maybe I still don't understand pointers. Calling PrintToConsole
shouldn't work because apparently responseData
is pointing to responseData->data
which is a string...!?