Is it possible to have pointers to references in c++? I'm asking because in my simple code:
#include "stdafx.h"
#include "Nunu.h"
int _tmain(int argc, _TCHAR* argv[])
{
Nunu* p = new Nunu[5];
Nunu a("a");
Nunu b("b");
Nunu c("c");
p[0] = a; //critical line/s
p[1] = b; //
p[2] = c; //
for (int i = 0; i < 3; ++i)
{
cout << p->name() << '\n';
}
return 0;
}
////////class Nunu
#pragma once
#include "stdafx.h"
class Nunu
{
private:
const string& _my_name;
public:
Nunu():_my_name("UNNAMED"){};
Nunu(const string& the_name):_my_name(the_name)
{
}
string name()const
{
return _my_name;
}
};
I'm getting this message:
"Error 2 error C2582: 'operator =' function is unavailable"
which would suggest that in "critical lines" assignment is taking place instead of setting out pointer. But when I change in class Nunu _my_name from reference to pointer this whole code works. Why?
//class Nunu after applying those changes
#pragma once
#include "stdafx.h"
class Nunu
{
private:
const string* _my_name; //now pointer<-------------------------------------------------
public:
Nunu():_my_name(nullptr){};
Nunu(const string& the_name):_my_name(&the_name)
{
}
string name()const
{
return *_my_name;
}
};
after this little change rest of the code works as intended (in main when constructing those object I obviously have to provide pointer to string instead of ref to string);
Thank you for any reply.