Reputation: 15
I have written a class where the objects and class attributes are immutable - however each time I attempt to update a class attribute I get the following error;
"Unhandled exception ... in ConsoleApplication.exe ... Stack overflow"
Some details on the class object. The header file of the class,
class AnObject {
public:
//constructor
AnObject();
AnObject(
const std::string AttributeA,
const __int32 AttributeB
)
const AnObject AnObject::SetAttributeA(const std::string AttributeA) const;
const AnObject AnObject::SetAttributeB(const __int32 AttributeB) const;
const AnObject AnObject::SetMyAttributes (const std::string AttributeA, const __int32 AttributeB) const;
private:
const std::string AttributeA;
const __int32 AttributeB;
};
The class file,
AnObject::AnObject() : AttributeA("1002"), AttributeB(1) {};
AnObject::AnObject( const std::string AttributeA, const __int32 AttributeB) : AttributeA("1002"), AttributeB(1)
{
SetMyAttributes("1002", 1);
};
const AnObject AnObject::SetMyAttributes(const std::string AttributeA, const __int32AttributeB)
const
{
try {
return AnObject
(
// base fields
AttributeA, AttributeB
)
}
catch (exception e)
{
throw e;
}
};
The object is immutable and hence all parameters set when changing a parameter by the setter class. However the code generates an error when I call the methods within main.
Upvotes: 0
Views: 63
Reputation: 21576
THis constructor of yours:
AnObject::AnObject( const std::string AttributeA, const __int32 AttributeB)
calls
SetMyAttributes("1002", 1);
which calls the constructor again...
const AnObject AnObject::SetMyAttributes(const std::string AttributeA, const __int32AttributeB) const
{
try {
return AnObject(AttributeA, AttributeB); // recursive call
}
...
SetMyAttributes
seems to be a useless function since all your data members are const
and the fact that you return a const
object by value.
Normally, You can only initialize a const
data member in the constructor initialization list. You can't modify them afterwards.
Same uselessness applies to these (except if you have something else, out of the norm, up your sleeves:
const AnObject AnObject::SetAttributeA(const std::string AttributeA) const;
const AnObject AnObject::SetAttributeB(const __int32 AttributeB) const;
const AnObject AnObject::SetMyAttributes (const std::string AttributeA, const __int32 AttributeB) const;
If you are talking of a completely immutable class, you wouldn't have any setters. However, I suggest you read everything here: const correctness
.
Upvotes: 1