Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Modifying class variables 1

Status
Not open for further replies.

Leibnitz

Programmer
Apr 6, 2001
393
0
0
CA
Is it possible to modify the value of a variable declared in a class by calling an object created outside that class?

here is an example:
Code:
class CMyClass {
public:
   CMyClass() { m_nNum = 0; }
   void OnPaint();
   void Draw();
   BOOL m_nNum;
...
..
};

.....

#include "myclass.h"
.....
void CMyClass::OnPaint() {
    ......
    if(m_nNum == 1) {
         Draw();
    }
}

....
...
#include "myclass.h"
// creating an object outside the class
CMyClass myObject;
// can i use "myObject" to modify the value of "m_nNum"?
 
First of all, your use of BOOL makes no sense here. BOOL should be used only for something that is true or false, not a number. Use int instead. I know MS made BOOL a typedef for int, but you should still call it an int.

You seem to not understand how classes work. Each object of CMyClass has its own value of m_nNum. If you want all objects to share a single value for m_nNum, m_nNum should be declared as static. Then to access the value, you can either use myObject.m_nNum or CMyClass::m_nNum. If you just want every object to have its own m_nNum like you have it hear, you can access it just using the myObject.m_nNum.
 
> BOOL should be used only for something that is true or false, not a number.

hmm,yes i know. Actualy,the variable "m_nNum" that i have use on the code sample only takes two values 0 and 1. Altought i have choose a name that might let you think that i'm treating this variable as an integer.
So,instead i could have use "m_bMyVariable".

> You seem to not understand how classes work

actualy,i know fairly well,how class's work,but lately i have been stuck with a problem, i was just looking for some advice.

>If you want all objects to share a single value for m_nNum, m_nNum should be declared as static.

alright,this part i didn't know it.
so,i'm going to try your subjestions and see if it works inside my program.

 
C++ added a real "bool" data type over a decade ago... Don't use BOOL, INT, LONG or any of that MS crap.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top