same object share same static variable???

M

Mug

hi, i have a strange problem on c++, can anyone explique to me:

here i have a class:
----------------------------------myclass.h--------------------
#ifndef MYCLASS_H
#define MYCLASS_H
#include <iostream>
class myclass
{
public:
myclass();
~myclass();
};
#endif

----------------------------myclass.cpp----------------------
#include "myclass.h"

myclass::myclass()
{
static bool cool=false;
if(!cool)
{
std::cout<<"hello world\n";
cool=true;
}
}
myclass::~myclass()
{
}

int main()
{
myclass *m1=new myclass();
myclass *m2=new myclass();
delete m1;
delete m2;
return 0;
}

the output of the program is quite intrigue me,
it print out just once "hello world", yet m1 and m2 are
two objects defferent, they are in defferent memory zone,for what
reason
they share the same static variable "static bool cool" ??
 
R

Ron

hi, i have a strange problem on c++, can anyone explique to me:

here i have a class:

This is the correct behavior. You get exactly ONE instance
of a static variable. In this case "cool" isn't even a member
variable. It doesn't belong to a class. It's just a local variable
to a function.

By the way you seem to have JAVA sickness. Do not use new/delete
unless you have good cause to do so. Your program is better written
as:

int main() {
myclass m1;
myclass m2;
}
 
J

Juha Nieminen

Mug said:
myclass::myclass()
{
static bool cool=false;

The only difference between a static variable inside a function and a
global variable is scope.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,062
Latest member
OrderKetozenseACV

Latest Threads

Top