|
-
December 5th, 2002, 08:00 PM
#1
get accessor returns uninitialized value
** confused **
// example.h
class example
{
public:
inline const int getValue()
{
return theeAnswer;
}
private:
int theeAnswer;
void function();
}
//example.cpp
void example::function()
{
theeAnswer = 5;
cout << getValue(); // its 5 like it should be
}
// another_file.cpp
#include "example.h"
void function()
{
example eo;
int retval = eo.getValue();
cout << retval; // its NOT 5 like it should be
retval comes back as other numbers, mostly large but never as 5. Its very much acting like an uninitialized variable, but I don't see how this can be.
Anyone have an idea?
Thanks,
-
December 5th, 2002, 08:06 PM
#2
--------------------------------------------------------------------------------
example eo;
int retval = eo.getValue();
cout << retval; // its NOT 5 like it should be
---------------------------------------------------------------------------------
Why do u think that it should be 5?
ur assigning the value 5 in void example::function()
In above case that function is not getting called. so the geValue is returning uninitialized value.
if u want to initialized the value each time the object is created put it in C'tor.
Vinod
-
December 6th, 2002, 07:10 AM
#3
vinodp is correct. Each instance of a class is different; therefore,
each object that you create will have a different value for its
internal members. If you want ALL objects of a class to have the
SAME value for a member item, make that member item static.
This can be useful for reference counting or whatever:
Code:
class Martian
{
public:
static int getNumMartians() { return m_numMartians; }
Martian() { ++m_numMartians; }
~Martian() {--m_numMartians; }
private:
static int m_numMartians;
};
That's just a simple example to illustrate what I'm talking about.
--Paul
-
December 6th, 2002, 09:53 AM
#4
or do something like
Code:
example eo;
eo.function();
int retval = eo.getValue();
and make function public & may be change the name from function to setValue.
or
put that line in the Constructor
Hope This Helps,
Regards,
Usman.
Last edited by usman999_1; December 6th, 2002 at 10:05 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|