0

How would it be possible to use tabEmployes[0].Function ???

CEmploye **tabEmployes[NB_EMPLOYES] = new CEmploye[NB_EMPLOYES];
int main()
{
    for (int i = 0; i < NB_EMPLOYES - 1; i++)
{
    int j = 0;
    string sNom = *LES_EMPLOYES[i, j];
    int iNum = atol(*LES_EMPLOYES[i, j + 1]);
    int iNiv = atol(*LES_EMPLOYES[i, j + 2]);
    CEmploye* unEmploye = new CEmploye(sNom, iNum, iNiv);
    tabEmployes[i] = &unEmploye;
}
3
  • Use the "->" operator. tabEmplyes[0]->doSomething(); Commented Apr 19, 2015 at 6:45
  • it doesn't let me see any functions when I do it... it let me sees them when I do unEmploye-> thought... Commented Apr 19, 2015 at 6:47
  • That sounds like a problem with you IDE. You have many lines above that won't compile so that may be the cause of the IDE not recognizing the functions. Commented Apr 19, 2015 at 6:50

1 Answer 1

1

tabEmployees is an array of pointers to pointer. This means that tabEmployees[0] is a pointer to a pointer. To access the class methods you would have to dereference the pointer. You could use

(*(tabEmployees[0]))->methodName();

However, your current code points tabEmployees[0] to the memory address of a local variable, which will go out of scope at the end of the loop. This is undefined behavior and will most likely lead to undesired results (such as a crash, or all your pointers being the same).

I think you don't really want tabEmployees to be an array of pointers to pointers, especially as your code shouldn't compile right now.

This line:

CEmploye **tabEmployes[NB_EMPLOYES] = new CEmploye[NB_EMPLOYES];

should not compile, as you are assigning an array of pointers to an array of pointers to pointers.

As you are creating your pointers during the loop, it seems to me you don't need to assign any value to this array. If you change it to:

CEmploye **tabEmployes[NB_EMPLOYES];

Your code will now compile.

However, as I said above, you still have the problem that you are pointing to a local variable that will be going out of scope. I would suggest that your tabEmployees should be defined as:

CEmploye *tabEmployes[NB_EMPLOYES];

and assigned later as

tabEmployes[i] = unEmploye;

(note the removed &).

Now your array contains pointers to the newly allocated objects, rather than to the variable that pointed to that object. You would then access methods as follows

tabEmployes[i]->methodName();
Sign up to request clarification or add additional context in comments.

2 Comments

THANK YOU SO MUCH, if I use your second method is it still wrong to create them during a loop? tyvm again!!!
If you use the second method then you have to create the objects in your loop, as you only have an array of uninitialized pointers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.