I have seen something like the following code used to call a member function before the constructor is called. The constructor initialization for _data calls member function 'function()' before the constructor.
class foo
{
public:
foo();
private:
int *_data;
void function();
};
foo::foo() :
_data((int *)(function(), NULL))
{
std::cout << "foo::constructor called" << std::endl;
}
void foo::function()
{
std::cout << "foo::function called" << std::endl;
}
int main()
{
foo * _foo = new foo;
delete _foo;
return 0;
}
Output:
foo::function called
foo::constructor called
I don't really understand the syntax for the _data constructor initialization. If you do the following:
foo::foo() :
_data((int *)function())
you get a type cast error: C2440: 'type cast' : cannot convert from 'void' to 'int *'
Could anyone explain the what is going on here?
foo::foo() :
_data((int *)(function(), NULL))