Advertisement

Problem with a getter function

Started by January 02, 2015 04:17 AM
3 comments, last by TheStudent111 10 years ago

My getter function keeps returning the same constant value, despite it changing over time.

Main


#include <iostream>

#include "Moo.h"



using std::cout;

using std::endl;



int main()

{



    bool running = true;

    Foo foo;

    Moo moo;

    while(running)

    {

        foo.Update();  <-- m_r is updated

        

        moo.Show();    <--- m_r remains zero

    }



    system("Pause");

  return 0;

}
 
 

Foo.h


#ifndef FOO_H_

#define FOO_H_


class Foo

{

public:

    int getR();

    void Update();

    Foo();

private:

    int m_r;

};



#endif
 

Foo.cpp


#include "Foo.h"


Foo::Foo()

{

   m_r = 0;

}



int Foo::getR()

{

    return m_r;

}



void Foo::Update()

{
    m_r++;
}

Moo.h


#ifndef MOO_H_

#define MOO_H_



#include "Foo.h"



class Moo

{

public:

    void Show();


private:

    Foo foo;

};



#endif
 

Moo.cpp


#include <iostream>

#include "Moo.h"



using std::cout;

using std::endl;



void Moo::Show()

{

    cout << foo.getR() << endl;  //<-- The following returns zero, despite being updated in Foo Update

}

Why isn't the getter function updating, what am I missing? Thanks in advance

EDIT: Nevermind.

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

My journals: dustArtemis ECS framework and Making a Terrain Generator

Advertisement

You're not updating the 'foo' that exists in 'moo'. You're updating the 'foo' that exists in main(). The objects of type 'Foo' are not the same object. Each one has its own value.

If you want this to work correctly you'll need to either make moo.foo public and then update it, or else create an update method for Moo that updates its instance of Foo.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

The foo in your main function is *not* the same instance as the foo in your Moo instance. They are two different objects. Change your main method to this to see what I mean:

[source]

#include <iostream>

#include "Moo.h"

using std::cout;

using std::endl;


int main()
{
bool running = true;
Foo foo;
while(running)
{
foo.Update();
foo.Show();

}

system("Pause");

return 0;
}[/source]

You will need to call moo.foo.Update() to do what you want, either by adding an update method to Moo that calls it internally or some other means.

Thanks everyone, for the input! Can't believe it was that simple.

@TheChubu, I tried to give a simplified version of my real problem.

This topic is closed to new replies.

Advertisement