CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Nov 2002
    Posts
    20

    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,

  2. #2
    Join Date
    Oct 2002
    Location
    Tx, US
    Posts
    208
    --------------------------------------------------------------------------------
    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

  3. #3
    Join Date
    May 2000
    Location
    Phoenix, AZ [USA]
    Posts
    1,347
    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

  4. #4
    Join Date
    Aug 2001
    Location
    Germany
    Posts
    1,384
    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
    Code:
    function();
    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
  •  





Click Here to Expand Forum to Full Width

Featured