Click to See Complete Forum and Search --> : get accessor returns uninitialized value


seekinganswer
December 5th, 2002, 07:00 PM
** 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,

vinodp
December 5th, 2002, 07:06 PM
--------------------------------------------------------------------------------
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

PaulWendt
December 6th, 2002, 06:10 AM
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:

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

usman999_1
December 6th, 2002, 08:53 AM
or do something like

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

function();


Hope This Helps,
Regards,
Usman.