Question

Can I use the post-increment operator with initialization list arguments? For example something like this:

template <class T> struct MyClass
{
  MyClass(T& val): myvar(val++) {/*body*/}
  protected: T myvar;
};

And will code in the constructor body be affected by the change?

Was it helpful?

Solution

Yes you can. The myvar member will have the value of val before the increment.

We should considere that val will have a type supporting the post-increment operator.

template <class T> struct MyClass
{
    MyClass(T val): myvar(val++) {/*body*/}
//          ^
protected:
    T myvar;
};

MyClass<int> foo( 1 );

// Here myvar will have the value 1

And don't forget the type of val passed to the MyClass constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top