Note that there are some explanatory texts on larger screens.

plurals
  1. POInitializing a member class of an object using a non-default constructor in C++
    primarykey
    data
    text
    <p>I have a specific situation where I've got an object that I want to use the boost random number generators on, and it has lead to a greater question which I cannot seem to answer. Here is the example code of what I'm trying to produce.</p> <p>First, my header:</p> <pre><code>Class MyObject { protected: double some variable; boost::random::mt19937 rgenerator; boost::uniform_real&lt;double&gt; dist_0_1; boost::variate_generator&lt; boost::mt19937&amp;, boost::uniform_real&lt;double&gt; &gt; rand01 } </code></pre> <p>Now what I want to do is:</p> <pre><code>Class MyObject { protected: double some variable; boost::random::mt19937 rgenerator(std::time(0)); //initialize to a "random" seed boost::uniform_real&lt;double&gt; dist_0_1(0,1); //set the distribution to 0-1 boost::variate_generator&lt; boost::mt19937&amp;, boost::uniform_real&lt;double&gt; &gt; rand01(rgenerator, dist_0_1);//tell it to use the above two objects } </code></pre> <p>But this doesn't work because it is in a header. I thought I could use the constructor of MyObject to somehow call the constructors on the various sub-objects (distribution, generator, but I can't figure out how. By the time the constructor of MyObject is called, the sub-objects' default constructors have already been called, and I haven't found that they have member methods to reset these properties... besides which, that isn't the point where I am confused. Now maybe there are too many things going on and I'm confusing issues, but as far as I can tell, my problem reduces to this following, childish example:</p> <pre><code>Class Tree { Tree(); Tree(int); protected: fruit apples(int); } Tree::Tree() { apples(0); //won't work because we can't call the constructor again? } Tree::Tree(int fruit_num) { apples(fruit_num); //won't work because we can't call the constructor again? } Class Fruit { public: Fruit(); Fruit(int); protected: int number_of_fruit; } Fruit::Fruit() { number_of_fruit = 0; } Fruit::Fruit(int number) { number_of_fruit = number; } </code></pre> <p>I'm sure this is second nature to everyone else out there, but I can't find an article that talks about the best practice for initializing member objects of an object to a non-default constructor value.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload