I have several bool validation methods in a class that will set data if it is valid, otherwise it does not change anything and returns false.
I need to write a method that will set all of the classes data using these bool validation methods but only if ALL of them return true. If even one of them returns false the entire class instance must remain unchanged.
I was thinking of a creating a temp instance of the class inside the method and if all of the validation methods return true than I would copy the temp instance into the current instance.
But I'm not sure how to do that without manually copying member by member. Is there a way to use the copy constructor on the current class from within itself?
I know it's dumb but it's my first program in OOP in C++.
You would think that this would be a top-level function because it makes so much more sense that way but I guess I will just have to copy each data member one by one because it doesn't seem that you can copy a class into the current class inside that current class.
If only the keyword "this" could be used for assignment purposes I could just write:
if (all validation methods return true) {
this = temp_class;
return true;
}
else
return false;
if (all validation methods return true) {
this = temp_class;
return true;
}
else
return false;
can't you just use the assignment operator?
1 2 3 4 5 6 7
Class tmp = temporary_instance;
if (/*validation all checks out*/) {
*this = tmp;
returntrue;
}
returnfalse;
You may neeed to implement your own operator=() for your class if it manages dynamic memory -- if it does you should have already done this. If it doens't manage any dynamic memory, the compiler will automatically generate an assignment operator for you.