Reputation: 11
How do I create a class setter member function that uses const reference as its parameters? I wrote the definition of the setter of how I thought it should be, but upon running it breaks and returns a "read access violation" exception.
//==== Start of Main.cpp ====
int main()
{
std::string temp="test";
NodeData thingy;
thingy.setname(temp);
return 0;
}
//==== End of Main.cpp ====
//==== Start of NodeData.hpp====
class NodeData
{
public:
void setname(const std::string &newName);
private:
std::string *mpName;
};
//==== End of NodeData.hpp ====
//==== Start of NodeData.cpp====
void NodeData::setname(const std::string &newName)
{
*(this->mpName)=newName;//this here is what causes compiler error I think
//mpName=newName; Doesn't work because "no suitable conversion function from "const std::string" to "std::string *" exists"
}
Upvotes: 0
Views: 455
Reputation: 87957
The obvious answer is to not use a pointer in your class.
class NodeData
{
public:
void setname(const std::string &newName);
private:
std::string mpName;
};
void NodeData::setname(const std::string &newName)
{
mpName = newName;
}
Newbies often use pointers inappropriately, did you have a good reason for using a pointer in your class?
Upvotes: 1