static variable initialization problem
Aug 8, 2014 at 11:36am UTC
When I try to initialize static variable from within the constructor the compiler exits and return exit status 1,
Can't we initialize static variables from constructors?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
#include <iostream>
#include <string.h>
#include <iomanip>
using namespace std;
class nonsta{
public :
int a;
int b;
nonsta();
~nonsta();
};
nonsta::nonsta(){
cout << "nonsta constructor called" ;
a = 5;
b = 10;
}//---------constructor
nonsta::~nonsta(){
cout << "nonsta destructor called" ;
}//--------destructor
class statc{
public :
static int asta;
int bnsta;
statc();
~statc();
};
statc::statc(){
cout << "statc constructor called" ;
// asta = 15;
bnsta = 20;
}//-------constructor
statc::~statc(){
cout << "statc destructor called" ;
}//-------destructor
int main(){
}//--------main()
When I out comment line 48 then compiler give following error:
C:\Users\Dani\AppData\Local\Temp\ccx4c49w.o temp.cpp:(.text+0x92): undefined reference to `statc::asta'
E:\Education\cpp\temp\collect2.exe [Error] ld returned 1 exit status
Aug 8, 2014 at 12:00pm UTC
Can't we initialize static variables from constructors?
Yes and no.
Static member data will exist before the first instance of a class is created. So there must be a way to initize it seperately, and that's in its definition.
1 2 3 4 5 6 7
struct A
{
A();
static int s_a;
};
int A::s_a = 3;
But a constructor should be able to set the value.
Aug 8, 2014 at 7:14pm UTC
Thankyou kbw, I got it constructor could do with static member too but that static member must be initialized before the constructor
Topic archived. No new replies allowed.