1

for whatever reason coding in the main(): className[index]= 2. triggers the constructor of className instead of the coded overloading method where The right hand operand is passsed as parameter(2 in this case). Obscure behavior that needs your clarifications. Why is the method operator[] is ignored ?

Here's a sample of dynamic arrayClass :

class dTableau
{
public:
    dTableau(int taille);
    int& operator  [](int index) ;
    dTableau &operator =(int val);
    // other methods

private:
    int *m_tab;
    int m_taille;

};


dTableau::dTableau(int taille)
{
    m_taille = taille;
    m_tab = new int[taille];
    for (int cnt = 0; cnt < m_taille;cnt++) {
        m_tab[cnt] = cnt;
    }
}

int& dTableau::operator[](const int index) {

    return m_tab[index];
}

 void main(){
     int taille=2;
     dTableau *t = new dTableau(taille);
     // this line triggers the constructor with 1 as parameter 
     t[1]=1;

}
  • 4
    Well, `t` is a *pointer* so you have to dereference it someway, like `(*t)[1]` or `t->operator[](1)`. Or not make `t` a pointer to begin with. Perhaps you should take a few steps back, [get a couple of good beginners books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and start over. – Some programmer dude Oct 22 '17 at 18:04
  • 2
    It's a bit hard to follow your explanation and your code..Read the post. – gsamaras Oct 22 '17 at 18:04
  • You can initialize table as `dTableau t(taille);` and everything will be fine. Please follow @Someprogrammerdude's advice. C++ is not an everyday Java like language. It bites you. – zahir Oct 22 '17 at 18:16
  • @zahir that worked well. – Nizar Sousse Oct 23 '17 at 00:06
  • A constructor that can be called with exactly one argument (and is not a copy or move constructor) should be marked `explicit` unless you have a really good reason to want implicit conversions: `explicit dTableau(int taille);` – aschepler Oct 23 '17 at 00:08

1 Answers1

0

C++ will only try applying overloaded operators when one of the operands is of class type. Take a look at this code:

 dTableau *t = new dTableau(taille);
 t[1] = 1;

Here, the variable t is a pointer to a dTableau, not an honest-to-goodness dTableau object. As a result, the line

t[1] = 1;

is interpreted as "access the element at index 1 pointed at by the t pointer, then assign it the value 1." This then causes your conversion constructor to be used to convert the 1 on the right-hand side to a dTableau before ultimately assigning it to the (nonexistent) object at the (invalid) array index of 1 in the t array.

Since t is a pointer, if you want to use the overloaded selection operator, you'd need to reference it first:

(*t)[1] = 1;

Alternatively, if t doesn't need to be a pointer, don't declare it as such:

dTableau t(taille);
t[1] = 1;
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065