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 ?

Recommended Answers

All 3 Replies

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.

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.