how to call a constructor from another one with stuff between ?

Hi all,
With Cx11, we can call a constructor of a class from another one from the same class like this :

1
2
3
4
5
6
class Foo  {
     int d;         
public:
    Foo  (int i) : d(i) {}
    Foo  () : Foo(42) {} //new to c++11
};


But I need to make some stuff in between. Here is some pseudo code :

1
2
3
4
5
6
7
8
9
class Foo  {
     int d;         
public:
    Foo  (int i) : d(i) {}
    Foo  () {
      int a = rand() % 100;
      this->Foo(a);
    }
};


But it does not compile. I get :

error: invalid use of ‘Foo::Foo’


It would be fine to be able to do it. How do you manage this kind of need ? Is there a chance to have it in the norm ?
Foo () : Foo(rand() % 100) {}
Thanks, but this was a simple example. In real life, rand() % 100 may be replaced by more complex operation, requiring control structures.
Put them when you are calling the constructor in the code:

1
2
3
4
5
if(rand() < 10) {
    x = new Foo(10);
} else {
    x = new Foo(0);
}//... 
In C++, you cannot call a constructor on a currently existing object. When you call this->Foo(a); , the object this has already been created.

You need to use different constructors.

1
2
3
4
5
6
7
8
class Foo  {
     int d;         
public:
    Foo  (int i) : d(i) {}
    Foo  () {
      d = rand() % 100;
    }
};
Thanks all.
Topic archived. No new replies allowed.