Reputation: 59
I'm trying to find out the problem with my logic in this function and I can't find it. When stepping through the program, it keeps stopping at the classes constructor, where it gets to the if statement and goes straight to the else which sets the object to a safe empty state. problem is, that the values should pass validation(in this case it's being passed 345 and "Jim") and the compiler should go through the block of code following the if. If anyone can spot where my code is off that would be great
Vacation::Vacation(int n, const char* b) {
if(num > 0 && num < 999999 && b != nullptr) {
num = n;
vtime = 0.0;
vname = new char[strlen(b) + 1];
strcpy(vname, b);
}
else {
*this = Vacation();
}
}
Upvotes: 0
Views: 63
Reputation: 49
I am assuming you missed out n instead of num. The class has n as a passed value. num is nt declared. Is num already declared s a global variable? i suggest you look at the problem.It could have been 'n'
Upvotes: 0
Reputation: 2624
Assuming num && vname are memebers of Vacation
Vacation::Vacation(int n, const char* b) : num(n), vname(nullptr) {
if(num > 0 && num < 999999 && b != nullptr) {
...
}
}
As with all other answers the key is to initialize members before you use them..
And since you allocate memory you should also build a destructor, copy-ctor and operator= to avoid memory leaks
Upvotes: 0
Reputation: 75565
Perhaps you meant to put the assignment above the if
statement?
num = n;
if(num > 0 && num < 999999 && b != nullptr)
I will say though, R Sahu's fix is better. Less variables. :)
Upvotes: 0
Reputation: 206577
I suspect you meant to say:
if(n > 0 && n < 999999 && b != nullptr) {
Remember, num
is not initialized yet.
Upvotes: 1