Hello everyone! I have an error in my class. I'm suspect it's something simple, maybe me failing to understand how strings are created and passed to my constructor. In getName() my function prints 1 and then segfaults before printing 2. I'll include the code below. Thank you in advance for providing such a helpful forum. - Craig
Line 71 will never execute because the function will return first. ;o)
You need to set the name *before* you add your child in the constructor:
1 2 3 4 5 6 7 8 9 10
Taxon::Taxon(string name_, Taxon* parent_)
{
parent = parent_;
name = name_; // here - before the name is used in the children vector
if(parent != NULL)
{
parent->addChild(this);
}
// name = name_; // not here - too late
}
But those variable should really be set in the ctor-initializer:
1 2 3 4 5 6 7 8 9 10 11
Taxon::Taxon(string name_, Taxon* parent_)
: parent(_parent)
, name(_name)
{
// now the object integrity is intact allowing more complex
// operations to be performed safely.
if(parent != NULL)
{
parent->addChild(this);
}
}