-3
#include<iostream.h>

int a;
class g{      
    cout<<a;
};

int main()
{
    cout<<a;
    return 0;
}

Why am I not able to print the global variable a inside of the class, but at same time, I am able to print a inside main? Is there no way to use cout in a class?

chris
  • 60,560
  • 13
  • 143
  • 205
user3690061
  • 118
  • 1
  • 3
  • 15

1 Answers1

3

you cannot write a statement like that in the middle of a class, it is essentially like doing

struct g
{
  cout << a;
};

which makes no sense, instead define a method in g in this case a static one would do since your variable is anyway global.

int a;
class g
{
public:
  static void printA()
  {
    cout<<a;
  }
};

// now you can print a

int main()
{
 cout<<a;
 g::printA();
 return 0;
}
AndersK
  • 35,813
  • 6
  • 60
  • 86
  • in c++ any variables declared inside a class are also global variables like in java? – user3690061 Jun 06 '14 at 04:56
  • @user3690061, What? There are no variables declared in a class here, and they are most certainly not global in Java. – chris Jun 06 '14 at 04:57
  • @chris what if i declare a variable in a class? what do you call that variable ,as in java they are called instance variable – user3690061 Jun 06 '14 at 04:59
  • 1
    @user3690061 declared variables in a c++ class are instance variables (if they are not declared static) – AndersK Jun 06 '14 at 05:00
  • @user3690061 i would suggest taking a look at http://mindview.net/Books/TICPP/ThinkingInCPP2e.html – AndersK Jun 06 '14 at 05:01
  • @user3690061, Data members would be a more appropriate C++ terminology, but same thing, really. – chris Jun 06 '14 at 05:01
  • @Claptrap so if they are declared public static like in java they would be called as global variable ? – user3690061 Jun 06 '14 at 05:02
  • @user3690061 yes, if the variable in the class is declared static then you can access it by prefixing with the class name since it is not an instance variable otherwise you need to create an instance of the class and access it via the instance – AndersK Jun 06 '14 at 05:04
  • @Claptrap my intentions are not to learn c++, i just want clarify the meaning of global variables with respect to c++ and java ,i am confused about global variables in java whether they exist in java or not ,i have posted a question regarding this hava a look http://stackoverflow.com/questions/24060921/is-there-anything-called-global-variable-in-java – user3690061 Jun 06 '14 at 05:06