0
class A
{
private:
int x ;
int &y ;
static int z ;

};

How can initialize these 3 variable in this class

J. Murray
  • 1,460
  • 11
  • 19
suman
  • 1
  • So what have you tried already? – J. Murray Oct 06 '19 at 13:34
  • 1
    Do you want to initialize the variables from a constructor? It seem like you may need to provide more context to get a helpful answer. – Chris Pearce Oct 06 '19 at 13:36
  • There are many ways to initialize the variables, used in different contexts. Please provide more information about how this class is used. – L. F. Oct 06 '19 at 13:41
  • Possible duplicate of [How to initialize private static members in C++?](https://stackoverflow.com/questions/185844/how-to-initialize-private-static-members-in-c) – meirm Oct 06 '19 at 14:07

1 Answers1

0

The normal variable can be initialized in the constructor, in its member initializer list, but you don't have to:

A::A(int i) :
    x(i) { /* c'tor */ }

The reference can only be initialized from the constructor, and you must initialize it:

A::A(int& r) :
    y(r) { /* c'tor */ }

Now the y field of A will reference to the same variable as r, it is not a copy of it.

The static variable must be initialized outside the class, probably in a separate source file, you must do this if you want access that static variable.

int A::z = 0;