PDA

View Full Version : static keyword/string analogy


tricolaire
07-29-2005, 11:01 PM
first question applies to java and c++

What is the meaning of the java/c++ keyword static?

I can really find no difference when used or not used

second question refers to c++

the variable type string, is obviously, by dint of its methods, a class. How does the class string let you set it's internal values with '='? It doesn't seem like operator overloading would work. For that matter, how does the string class delineate which value to show in a cout<< statement or which value to set in a cin>> statement?

thanx

JPM
07-29-2005, 11:50 PM
1.

a static function/variable is shared by all instances of a class. It can (if it's public) also be called/set/whatever from outside the class without making an instance of the class.

ex

class Person
{
String name;
int age;
static int totalNrPersons;
}
Each person has it's own name and age, but the totalNrOfPersons variable is not bound to one instance of the class.

Hope that made sense :) Probarly better to just google a tutorial on it

oracleguy
07-30-2005, 04:45 AM
Expanding on the example just given:


Person p1;

p1.totalNrPersons = 10

cout << p1.totalNrPersons << endl; //Will output "10"
Person::totalNrPersons = 25;
cout << p1.totalNrPersons << endl; //Will output "25"

Person p2;
cout << p2.totalNrPersons << endl; //Will output "25"


Maybe that will help illustrate it better. Basically a static variable is the same in all instances like said before.