Link to home
Start Free TrialLog in
Avatar of shaolinfunk
shaolinfunkFlag for United States of America

asked on

How do I make my bBool variable global?

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

ASKER CERTIFIED SOLUTION
Avatar of phoffric
phoffric

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
#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)
Avatar of phoffric
phoffric

Now you can say:
Functions::SetBoolToTrue();

Open in new window

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().
Another way to use a 'global' variable is via a singleton class.

There is an example of how to implement one of those here:
https://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.
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
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
Avatar of shaolinfunk

ASKER

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
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
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.
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.
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.)
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.
@evilrix
The questioner has indicated in a previous question he is learning MFC / C++.
It probably isn't a real problem requiring solving
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.
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.
>> 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.
Oh, and you might find this worth reading.
http://www.c2.com/cgi/wiki?GlobalVariablesAreBad
I don't see how a static data member absolutely represents a flaw in the design.
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.
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.
...and I appreciate ALL of your help in guiding me along thus far.  I'm extremely grateful!
Have a nice holiday
Sorry for the delay.  Was on vacation, and then got caught up with work after vacation.