2

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))
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • `function()` returns `void`. And yeah, you can't convert `void` to a non-`void` type because it doesn't make sense. This code uses the comma operator to first call the function, then throw away its void return value, yield `NULL` and assign that to `_data` member function. – The Paramagnetic Croissant Mar 05 '15 at 15:23
  • please don't do this, if you need complex construction please consider a static factory function. The benefits are far outweighed by the undefined behavior – Mgetz Mar 05 '15 at 15:31

2 Answers2

3

It's the comma operator.

... a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

So (int *)(function(), NULL) first calls function() and then returns NULL.

The NULL is then cast to int* and used to initialize _data.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
0

This construct uses the comma operator to achieve its effect.

When evaluating (function(), NULL) it first evaluates function, then NULL. The overall result of the expression is NULL, which is then casted to int *. Hence, _data is initialised to NULL.

Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283