Tommy Lang wrote:
Hi !!
I am a c++ novice and I would appreciate any help with the following:
I have created a class called "Number". In the main function of my
program I call the class constructor twice like this(at start up)...
int main(){
Number no1;
Number no2;
......
Everything is fine so far.
Then in the class constructor I want to ask for two numbers and add
them to the private member variables m_no1 and m_no2...
Number::Number()
{
if (first_time) //first-time is a private boolean variable (how to
init it??)
You are right to worry about initializing this. If you execute this 'if'
without first initializing first_time, your program's behavior is
undefined (could do anything, including crashing, behaving
unpredictably, working as expected, making long-distance phone calls, etc.)
The thing is, this is a constructor. Initialization is what it *does*.
So whatever you set 'first_time' to, that's what it's going to be. It
doesn't make much sense to branch based on it, because the result will
always be the same:
first_time = true;
if (first_time)
{
// well, obviously this will be executed.
}
else
{
// this will never be executed.
}
{cout << "Enter number: ";
cin >> m_no1; cin.get();}
You might have to explain why you think you need cin.get() here.
else
{cout << "Enter next number: ";
cin >> m_no2; cin.get();}
}
I have tried this approach but I couldn't get it to work properly. And
when I got it to work it NEVER got to the else statement. First time I
want to get m_no1 next time m_no2. Any pointers???
You don't want to branch. You want 2 numbers, unconditionally, right?
cout << "Enter the first number: ";
cin >> m_no1;
cout << "Enter the second number: ";
cin >> m_no2;
No 'if' is necessary.
....
OK, but from the sound of it, this isn't what you *really* want to do.
You need to understand that the constructor will be invoked
*independently* for each object. In general, the constructor cannot (and
should not) know if it's already been invoked, or how many times. What
you really want is something like this:
#include <iostream>
using namespace std;
class Number
{
public:
Number() { cout << "Enter number: "; cin >> m_no; }
private
int m_no;
};
int main()
{
Number no1;
Number no2;
return 0;
}
This will work, but you can't change the text of the prompt, unless you
want to pass it in as a parameter to the constructor, but basically
doing I/O is a constructor is a bit screwy anyway (you can do it if you
really want to, but it's very unusual), so you should probably do
something like this instead:
#include <iostream>
using namespace std;
class Number
{
public:
void Read() { cin >> m_no; }
private:
m_no;
};
int main()
{
Number no1, no2;
cout << "Enter the first number: ";
no1.Read();
cout << "Enter the second number: ";
no2.Read();
return 0;
}
-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.