For standard data objects such like int, the following can be done
int number;
number = 0;
Basically, you can declare number before initializing it, useful if you initialize inside various if statements and you don't want number going out of scope.
Can something similar be done with custom classes?
I have a class called mem_array with constructor of the form
mem_array(int,int,std::string);
I would like to do the following
mem_array myData;
if(x==0) myData(1,1,"up");
if(x==1) myData(0,0,"down");
basically, so I can use myData outside of the scope of the if statements. Can something like this be done?
The main reason is that initialization applies to an object, or an instance, and in the declaration in the class there is no object or instance; you don't have that until you start constructing.
If you declare a variable as final, it is mandatory to initialize it before the end of the constructor. If you don't you will get a compilation error.
You should always initialize native variables, especially if they are class member variables. Class variables, on the other hand, should have a constructor defined that will initialize its state properly, so you do not always have to initialize them.
There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.
Your first line will give you an error since the constructor doesnt have default values and a constructor without parameters doesnt exist.
Just use a pointer (or even better a smart pointer, so you dont have to take care of deleting the object). But be sure to check afterwards that x was either 0 or 1, i.e. check that myData has been constructed.
mem_array* myData=0;
if(x==0) myData=new mem_array(1,1,"up");
if(x==1) myData=new mem_array(0,0,"down);
assert(myData!=0);
add a constructor to mem_array that takes an int
so that you can declare/use...
mem_array myData(x);
inside this constructor, add the initialization/condition code you want to use.
You can use a pointer:
unique_ptr<mem_array> myData;
switch (x) {
case 0:
myData.reset(new mem_array(1, 1, "up"));
break;
case 1:
myData.reset(new mem_array(0, 0, "down"));;
break;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With