1

Possible Duplicate:
c++ publicly inherited class member cannot be used as default argument
Nonstatic member as a default argument of a nonstatic member function

LinkedInteger accessElement(int index, LinkedInteger *startElement=&DataArray[0]){ // Starting at *startElement*, returns the element which is at the index of *startElement+index

    LinkedInteger NullElement;
    if (index<0){
        cout << "Index degeri sifirdan buyuk olmalidir" << endl;
        NullElement.value=0;
        NullElement.nextPtr=0;
        return NullElement;
    }       
    for (int i=0; i<index; i++){
        if (startElement->nextPtr == NULL){ // Last elements index is null.
            cout << " Erismeye calistiginiz eleman dizi sinirlarinin disindadir " << endl;
            NullElement.value=0;
            NullElement.nextPtr=0;
            return NullElement;}
        else {
            startElement=startElement->nextPtr;
        }
    }
    return *startElement; 
}

This is a method in implementation of Linked Lists in c++, which simply lets access to lists elements I want to give the header as a default argument (which is indeed DataArray[0]). It fails because of the error "invalid use of non-static data member".

this->&DataArray[0]

also fails because of "this may not be used in this context" What should I do?

Also there are some issues with the context of the code. Please ignore them.

Community
  • 1
  • 1
cngkaygusuz
  • 1,228
  • 1
  • 11
  • 17

3 Answers3

5

Use an overload:

LinkedInteger accessElement(int index){
  return accessElement(index, &DataArray[0]);
}
Xeo
  • 123,374
  • 44
  • 277
  • 381
1

Try:

// 0 or NULL; your preference

LinkedInteger accessElement(int index, LinkedInteger *startElement = 0)
{
   if (startElement == 0)
       startElement = &DataArray[0];  // or just startElement = DataArray;
   // ...
}
Kate Gregory
  • 18,565
  • 8
  • 53
  • 85
Kaz
  • 48,579
  • 8
  • 85
  • 132
  • 2
    I like the overload answer better. But this does show one way you can get around the specific limitation about what can and cannot be used as an initializer for a default argument. – Kaz Mar 20 '12 at 17:47
-1

Default values for arguments have to be statically known. You cannot use a runtime value as default argument.

The latter fails because it's not a valid syntax and makes no sense pretty much.

q66
  • 195
  • 5