Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to declare class without initialization?

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?

like image 313
user788171 Avatar asked Jul 01 '11 01:07

user788171


People also ask

Why can't we initialize class members at their declaration?

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.

What happens if I forget to initialize a variable Java?

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.

Do class variables need to be initialized?

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.

How do you initialize a class attribute in C++?

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.


3 Answers

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);
like image 196
pokey909 Avatar answered Sep 27 '22 21:09

pokey909


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.

like image 35
MessyHack Avatar answered Sep 27 '22 21:09

MessyHack


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;
}
like image 22
Chris Jester-Young Avatar answered Sep 27 '22 23:09

Chris Jester-Young