Hello;

can we give the variable in struct an initial values ?

ex:
struct example{
int id;
float gpa;
string name;
};


can we but this inside the structure :
int id=34440;


the same Q is for the Class ? can we intialize the variable when definr it for the first time ?

Edited 6 Years Ago by Zay: n/a

It's got to be a static variable:

struct example{
static int id;
float gpa;
string name;
};
int example::id=34440;

Should be identical for the class (static variable/defined after the declaration).

In the case of a class, you could do it within the constructor(s) as well if you don't want it static.

Header:

class example {
private:
  int someVar;

public:
  example();    /* default constructor */
  example(int);/* overloaded constructor */
};

Implementation file:

example::example(){  /* default constructor */
  someVar = 34440;
}

example::example(int initValue){  /* overloaded constructor */
  someVar = initValue;
}

Main file:

#include "example.h"

int main() {
  example aDefaultExample;  /* using default constructor */
  example anOverloadedExample(34440); /* using overloaded constructor */

/* ... */
}

There are also initialization lists if you are familiar with those.

Edited 6 Years Ago by Fbody: n/a

You might be looking for constructor with default value :

struct Int{
 int var;
 Int(const int& initValue = 0) { var = initValue; }
};

Therefore when you do this :

Int num = Int(); //num = 0 for now
Int num2 = Int(2); // num = 2 for now
This article has been dead for over six months. Start a new discussion instead.