Variable within pointer of a class

11

I have several header files with GUI management functions that I did to create windows, similar to those libraries like GTK, QT and others, and I am transforming them into a library, but I have a problem that is going to be a bit complicated to explain.

I have a class called TD_Control that represents a control like button, textBox and others, inside it has a member named id which is an integer representing the object's id in loop of messages, basically so far my class looks like this:

class TD_Control
{
public:
    int id;
    ... // Esta classe é muito grande, por isso abreviei
}

And I have a function called TD_GetID () that generates a new id other than all generated and basically it adds the value of a variable returns a new value, like this:

// Esta variavel é global
int TD_ID_COUNTER = 5000;

int TD_GetID()
{
    TD_ID_COUNTER++;
    return TD_ID_COUNTER - 1;
}

And to create a control there is a function to create each type of control like the one that creates a TextBox :

TD_Control* TD_CreateControlTextBox()
{
    TD_Control* ec = new TD_Control();
    int nid = TD_GetID();
    ...// Esta classe é muito grande, por isso abreviei
    return ec;
}

All these functions are inside a static library, I compiled and did everything right, I created windows, controls and others, but when creating several controls and using events I had a problem, see this example:

// Tb1
TD_Control* TextBox1;
TextBox1 = TD_CreateControlTextBox();
// Tb2
TD_Control* TextBox2;
TextBox2 = TD_CreateControlTextBox();

When creating these controls, each one should have a different id, but all have the same id being all equal to 5002. Is it because the class object is a pointer and when using pointer object it has some characteristic different? Or is there something wrong with my code?

Unfortunately it is not possible to put the whole code as it is very large, only the main source code has 2156 rows.

    
asked by anonymous 06.12.2014 / 18:56

1 answer

1

With the information you gave, I can only try to guess the reason. I can try to improve my answer by clarifying the two questions below:

  • Your global variable declared like this: int TD_ID_COUNTER = 5000; is in a header or in a .cpp file?
  • Do you create two TextBox like this in your example there, or do you create them in separate files?
  • If the responses are: "1) in a header" and "2) in different files", I suspect that you create several different instances of the TD_ID_COUNTER variable by including the header in different .cpp files. If that is the problem, the solution is to put in the header only:

    extern int TD_ID_COUNTER;
    

    and within some .cpp (and only one), the variable declaration:

    int TD_ID_COUNTER = 5000;
    
        
    11.12.2014 / 23:16