Sign in to follow this  
Merlino

Class / Pointers Question

Recommended Posts

Hi, I have a question about pointers to classes: It's kind of hard for me to explain so here's an example I've made up: I have 3 classes: Instruments, Window, and Main. Instruments is a class that stores info about the time (say time = time elapsed since program startup); Window is a class that stores the info of one window and it needs acces to the value time of the Instruments class. Main is a class that stores pointers to all the other classes.. it's the root class.
class Instruments
{
    public:
    long int time;
    short mouseX;
}

class Window
{
   public:
   short x;
   short y;
   short width;
   shory height;
   void Animate();
}

class main
{
   public:
   Instruments * instr;
   Window * window;
   main() {allocate memory for the class pointers};
}

Now, here is my problem. How do I get the window class to acces the time value of the Instruments class? I thought about 2 solutions: 1- replace the Animate() function by Animate(long int time) and, when using the function like this: window->Animate(instr->time). But this can get kind of messy if, in this case, the window class has to acces members from lots of other classes. 2- create a pointer to Instruments class in the Window class and acces the values this way. In this case I don't want to create another Instruments object but make the pointer to point the same thing as the main pointer. In code this would equal to:
class Window
{
   public:
   short x;
   short y;
   short width;
   shory height;
   Instruments * instr;
   void Animate(); { acces instr->time ... }
}

main::main()
{
...
window = new Window;
instr = new instr;
window->instr = this->instr;
}

I tried this in my program but it does not seem to work because if i modify the values through main->instr->time, and then acces it through main->window->instr->time it is not the same. Did I do something wrong or is it normal? If so, is there any other way to do this ? Thanks in advance, Merlino.

Share this post


Link to post
Share on other sites
Argh, I'm sooo stupid.. actually it works. SORRY !!

But anyway, is "case 2" a good way of structuring classes if using class pointers?

Thanks, and again, sorry.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this