User input in default constructor?

Hi,

I've been struggling for a while with an issue.

My default constructor looks like this:

Runner::Runner()
{
this->name = "?";
this->numHeats = 1;
this->heats = new int[this->numHeats];
for (int i = 0; i < this->numHeats; i++)
{
this->heats[i] = 0;
}
}

As the code tells us, numHeats is used to set the size of the heats array when creating the array.

Over in main, the user will put in the number of heats for the runner. However, I am not allowed to use another constructor, but only the default one, so I can't pass the user input as an argument to the constructor.

So - how can I let the user input decide the size of the heats array, using only the default constructor?
By providing a resize function or as a very ugly hack, passing the size through a global variable.
Thanks Athar.

Global variables are no-nos in this case. Was kind of hoping that there was some other solution than doing a resize (still a beginner).
The default constructor can take a parameter, it just has to be able to be called without any arguments.

ie:

 
Runner(int heats = 1); // <- is a perfectly valid default constructor 


Here, passing 'heats' to the constructor is optional.


Also, you don't need to prefix all your members with this->.
Thanks Disch for pointing out the possibility of passing a parameter to a default constructor that way. However, this seems to be a static parameter value, bringing about the same result as my line "this->numHeats = 1" does, or? Which wouldn't solve my trouble of passing the value given by the user in the main function to the default constructor, for setting the size of the heats array with that value.

If I'm missing your point or misinterpreting your code, bear with me, I am rather new to all this.



It means the parameter is optional, and if it is not given, a value of 1 is used.

Here's an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class MyClass
{
public:
  MyClass(int param = 1);
};

//...

MyClass::MyClass(int param)  // default constructor
{
  cout << param << endl;
}

//...

int main()
{
  MyClass* a = new MyClass;  // use default ctor, prints "1"
  MyClass* b = new MyClass(5);  // passes the optional parameter.  prints "5" 

Ok, I see what you mean, thanks Disch.
So this is how I solved it at last:
--------------------------------------

Runner::Runner()
{
this->name = "?";
this->numHeats = numHeats;
this->heats = 0;
}


-------------
And then...
-------------

void Runner::setNumHeats(int numHeats) //User input comes here...
{
this->numHeats = numHeats;
this->heats = new double[numHeats];
for (int i = 0; i < numHeats; i++)
{
this->heats[i] = 0;
}

}

Works great.
Thanks for all input.
Topic archived. No new replies allowed.