Solved

How do I make my bBool variable global?

Posted on 2011-02-14
24
421 Views
Last Modified: 2013-12-14
As the title says...how do I make bBool in Functions.h a global variable?
--------------------------------------
ExampleDlg.cpp
--------------------------------------
#include "stdafx.h"
#include "Example.h"
#include "ExampleDlg.h"
#include "Functions.h"

void CExampleDlg::OnBnClickedButton2()
{
	// TODO: Add your control notification handler code
	Functions::SetBoolToTrue();
}
--------------------------------------
Functions.cpp
--------------------------------------
#include "Functions.h"
 
void Functions::SetBoolToTrue() 
{	 		
	 bBool = true;
}

--------------------------------------
Functions.h
--------------------------------------
class Functions
{
private:
	bool bBool;

public:  
	void SetBoolToTrue();
};

Open in new window

0
Comment
Question by:shaolinfunk
  • 7
  • 7
  • 4
  • +2
24 Comments
 
LVL 32

Accepted Solution

by:
phoffric earned 500 total points
ID: 34887352
class Functions  
{  
private:  
        static bool bBool;  
  
public:    
        static void SetBoolToTrue();  
}; 

Open in new window


In you .cpp file:
bool Functions::bBool = false;

Open in new window

0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 34887353
#include "stdafx.h"
#include "Example.h"
#include "ExampleDlg.h"
#include "Functions.h"
bool bBool;


BUT - using global variables is strongly not recommended.  (And to answer the next question look at the extern keyword in the help files)
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34887367
Now you can say:
Functions::SetBoolToTrue();

Open in new window

0
 
LVL 32

Expert Comment

by:phoffric
ID: 34887397
AndyAinscow's does give a true global definition of bBool. It is outside of all classes, and outside of all functions.

What I provided was a bBool that is part of the Functions class. It is global in the sense that all objects of the Functions class share this single bBools static member of the class. Notice that since bBool is private, it is not possible to access it directly outside of the Functions class (unless you have friends, of course). You can only modify the static bBool by using your Functions::SetBoolToTrue() static method.

BTW, I made SetBoolToTrue() static because in your related post, it looked like that is what you wanted; but it does not have to be static. But then, to use SetBoolToTrue(), you need either a pointer to a Functions object, or a Functions object to access SetBoolToTrue().
0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 34887417
Another way to use a 'global' variable is via a singleton class.

There is an example of how to implement one of those here:
http://www.experts-exchange.com/Programming/System/Windows__Programming/MFC/A_3825-Sudoku-a-complete-MFC-application-Part-6.html

it is one of a suite of articles I authored about coding an MFC application.
0
 
LVL 32

Expert Comment

by:sarabande
ID: 34887421
a static member variable is a member variable that belongs to the class and was not bound to an instance (object) of that class. if it is private you not only need a set function but a get function as well  (or at least another member function - static or non-static - that uses the member variable somehow) cause otherwise the set function makes little sense.

look at the static Functions::Add function we recently had. here the arguments x and y were passed to the function and the sum was returned. so it was not dependend on any member variable and therefore 'naturally' was a static member function.

Sara
0
 
LVL 32

Expert Comment

by:sarabande
ID: 34887528
global variables can be accessed from everywhere without needing access to a class or struct object they were bound to.

So if you see code

   whatever.x

the x is a member of class object 'whatever'. if the x is a static member it is a global shared variable and you wouldn't need variable whatever to access it but could access by

  class_of_whatever::x

so normally if you see

    whatever.x

the x is not a static member and so not global.

the other kind of global variables is that what andy_ainscow showed. whenever you define a variable outside of class scope and function scope it is global. all functions in the same cpp can use it without restriction and even from other cpp you could access it by declaring same variable with keyword extern. that kind of globalness is looked on 'not recommendable' in c++ as already told cause it is regarded as against OO (object orientation) principles of encapsulation and abstraction.

Sara
0
 
LVL 1

Author Comment

by:shaolinfunk
ID: 34887548
Ok, thank you for your answers..but the answers beget more confusion and questions.  I am taking this 1 step at a time, starting with Phoffric's 1st post.

I didn't know which cpp file you wanted me to put this in "bool Functions::bBool = false;".

Here's my code...but it doesn't compile..the error snapshot is attached..what am I missing?

--------------------------------------
ExampleDlg.cpp
--------------------------------------
#include "stdafx.h"
#include "Example.h"
#include "ExampleDlg.h"
#include "Functions.h"

void CExampleDlg::OnBnClickedButton2()
{
	// TODO: Add your control notification handler code
	Functions::SetBoolToTrue();
}
--------------------------------------
Functions.h
--------------------------------------
class Functions
{
public:  
	static void SetBoolToTrue();

private:
	static bool bBool;
};
--------------------------------------
Functions.cpp
--------------------------------------
#include "Functions.h"
 
void Functions::SetBoolToTrue() 
{	 		
	 bBool = true;
}

Open in new window

Noname.jpg
0
 
LVL 1

Author Comment

by:shaolinfunk
ID: 34887565
Disregard last snapshot..that is old..this is the current error message I am getting....something about "'#include "Functions.h"': skipped when looking for precompiled header use
1>        Add directive to 'stdafx.h' or rebuild precompiled header"
Noname.jpg
0
 
LVL 1

Author Comment

by:shaolinfunk
ID: 34887578
I am going to methodically go through all of your responses and make sure I understand each one...right now grasping the two different kinds of global variables brought up by Phoff and Andy, and the explanation Sara is offering to explain the difference between the 2 kinds of global.  Also, I have Google and my book by my side for reference..so please be patient with me as I try to absorb all of this.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34887623
Two points:

1. In addition to accessing your static member function using
     Functions::SetBoolToTrue();
you can also access it by using an object of the Functions class; for example:
    Functions abc;
    Functions * p_abc = & abc;
    abc.SetBoolToTrue();
    // or
    p_abc->SetBoolToTrue();

Open in new window

2. If you access bBool only within the Functions class; and if you use it as a latch (initially set to false, and then set to true via your setter function, SetBoolToTrue), then it is quite possible that your application will not require a get function as well. The need for the get is application dependent. I just wanted to clarify this to make sure that you didn't think there was an absolute rule that if you have a setter function, then you must have a getter function.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34887751
I would put the
   bool Functions::bBool = false;
in your Functions.cpp file.

BTW - don't forget to use wrappers around all your .h files (as standard practice).

Somehow, I got your:
   #include "Functions.h"': skipped when looking for precompiled header us
error.

Here is what I did to get it to compile:
Go to project Configuration Properties -> C/C++ -> Precompiled HeadersChange Precompiled Header to another setting. For starters, you can even try "Not Using Precompiled Headers", and then use others. The pre-compiled headers are for build efficiency, which may not be an issue for you. If the build takes 20 minutes, then using it is very important. (One odd thing.. I tried to go back to the original settings, but I can't get that compiler error any more - it's been awhie since I've used pre-compiled headers, so I'm a little rusty.)
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 40

Expert Comment

by:evilrix
ID: 34887756
I'm just wondering - to what ends do you want to make it global? Depending on your reasoning and what the runtime environment will be (for example, is it going to be used in multiple threads) there are a number of other factors you may need to consider. In other words, just making a variable global (generally not considered a good design practice) may be only the first step in a series of steps required to actually resolve the issue you are trying to deal with. More information on why you want/need to do this will allow the experts to provide better guidance and, maybe, a better alternative approach to solving your problem.
0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 34887770
@evilrix
The questioner has indicated in a previous question he is learning MFC / C++.
It probably isn't a real problem requiring solving
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34887811
This whole business of making bBool static stems from your usage in your OP:
     Functions::SetBoolToTrue();

Open in new window

Now, if the idea of a shared bBool across all objects of the Functions class does not satisfy your design, then you can declare object(s) of the Functions class; and then keep both bBool and SetBoolToTrue() as non-static members.

In this case, each Functions object will have its own independent bBool member with independent values per object.
0
 
LVL 1

Author Comment

by:shaolinfunk
ID: 34887854
As Andy states, this isn't a real problem.  I am just teaching myself MFC and trying to create programs that will compile and work without error.
0
 
LVL 40

Expert Comment

by:evilrix
ID: 34887876
>> As Andy states, this isn't a real problem.
Ok, that's fine... just wanted to be sure :)

For what's it's worth I think the thing you should take from this discussion (already mentioned before by the other experts) is that global variables are generally a bad idea and normally show a flaw in the design process. There are some exceptions to this but not many. It is often a better idea to review your design and see if you can lose the dependency on a global, but that is probably a matter for another discussion.

I'll step out and leave you and the other experts to it. Good luck.
0
 
LVL 40

Expert Comment

by:evilrix
ID: 34887887
Oh, and you might find this worth reading.
http://www.c2.com/cgi/wiki?GlobalVariablesAreBad
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34887934
I don't see how a static data member absolutely represents a flaw in the design.
0
 
LVL 40

Expert Comment

by:evilrix
ID: 34887970
phoffric, I said, "...normally...". The reasons for avoiding globals (and globals disguised as singletons and static members) are well known and well documented so I won't bother to enter into a lengthy debate with you about that here but feel free to discuss it further with me in the C++ Experts thread if you so wish.
0
 
LVL 1

Author Comment

by:shaolinfunk
ID: 34906634
Hi all,

I haven't abandoned this thread...I just put down this personal project for awhile because I got busy at work finishing up last minute stuff as I'm going on vacation today.  I get back next Thursday and will then pick up where I left off.  Please don't fret as I will surely get this done and award the points when I get back.  Learning this stuff is very interesting for me.
0
 
LVL 1

Author Comment

by:shaolinfunk
ID: 34906659
...and I appreciate ALL of your help in guiding me along thus far.  I'm extremely grateful!
0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 34906714
Have a nice holiday
0
 
LVL 1

Author Closing Comment

by:shaolinfunk
ID: 35016699
Sorry for the delay.  Was on vacation, and then got caught up with work after vacation.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
Update (December 2011): Since this article was published, the things have changed for good for Android native developers. The Sequoyah Project (http://www.eclipse.org/sequoyah/) automates most of the tasks discussed in this article. You can even fin…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now