Reputation: 495
i have a base class
class DLL_IMPORTEXPORT Base
{
public:
explicit Base(Base *parentItem = NULL);
virtual ~Base();
virtual bool initFromXml(const pugi::xml_node &xml_node);
//....
};
as well as a derived class
class DLL_IMPORTEXPORT Derived : public Base
{
public:
Derived(Base *parentItem = 0);
~Derived();
bool initFromXml(const pugi::xml_node &xml_node);
//...
};
now i want to call the base class method
virtual bool initFromXml(const pugi::xml_node &xml_node);
from the derived class method
bool Derived::initFromXml(const pugi::xml_node &xml_node)
{
bool all_ok = false;
// .... do some specific things
// then run the base class method
all_ok = all_ok && Base::initFromXml(xml_node);
return all_ok;
}
It all compiles fine, however, when i execute the code the base class methode is not executed and when i try to step into it in the debugger it does't step into it and just ignores it. I'm a bit confused. where is my brain-bug?
Upvotes: 3
Views: 81
Reputation: 24788
The expression:
all_ok && Base::initFromXml(xml_node)
uses the logical operator &&
which has short-circuit evaluation, i.e.: if all_ok
is false Base::initFromXml()
won't called, since the result of the whole expression can be already determined: false.
If you really want to call Base::initFromXml()
regardless of the value of all_ok
, then you can either swap the order of the operands in the expression above, that is:
Base::initFromXml(xml_node) && all_ok
or call the function in a separate statement and save its return value:
...
bool res_init = Base::initFromXml(xml_node);
all_ok = all_ok && res_init;
As suggested in this comment, using the bitwise and-operator (&
) instead of the logical and-operator (&&
) would be also a solution, since it does not short-circuit:
all_ok = all_ok & Base::initFromXml(xml_node);
Upvotes: 8