-2

I have a header in which I declare a function. Then I create the function and try to use it but i get an error. It is by reference but I don't know why it is not working.

struct.h

#ifndef LISTSTRUC_H_
#define LISTSTRUC_H_


template <class T> struct Array{
    int days;
    T * M;

Array( int size ) : days(size), M(new T[size])
{
}
~Array()
{
   delete[] M;
}
};

void currentDay();

template <class Expe>
void dummyData(Array<Expe> &);

#endif /* LISTSTRUC_H_ */

struct.cpp

void dummyData(Array <Expe> &A){
for(int i=0; i<31; i++){
    A.M[i].Expe::setObj((i*3),(i*1),(i*6),(i*2),(i*4),(i*5));
}
 }

M.cpp(Main cpp)

int main(){
//Main function of the program. no pre/ post condition.

    Array <Expe> A(31);   // Work space
    Array <Expe> B(31);   // Backup space

    dummyData(&A);         // error
 }

ERROR:

..\M.cpp:22:14: error: no matching function for call to 'dummyData(Array<Expe>*)'
Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
Bogdan Maier
  • 663
  • 2
  • 13
  • 19

4 Answers4

4
dummyData(&A);

should be:

dummyData(A); 

Rationale:
Your function takes a reference not a pointer, &A means you are passing address of the type which can only be received in by a pointer to that type and you don't have that overloaded version of the function, hence the error.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
2

If passing object by reference, don't pass its address, like you did here:

dummyData(&A); 

Just pass the object itself (as reference is its alias):

dummyData(A); 
Bojan Komazec
  • 9,216
  • 2
  • 41
  • 51
  • changed dummyData(A); but still D:\c++\Begin\Lab3-5_OOP\Debug/../M.cpp:22: undefined reference to `void dummyData(Array&)' – Bogdan Maier Apr 18 '12 at 16:16
  • @BogdanMaier That's a whole other question, which is answered here: http://stackoverflow.com/questions/1724036/splitting-templated-c-classes-into-hpp-cpp-files-is-it-possible – Robᵩ Apr 18 '12 at 16:24
  • you need to move template function implementation to header file, as Rob noticed + in `main()` you need to state exact type instead of `Expe`, which is just the name of the template parameter – Bojan Komazec Apr 18 '12 at 16:27
1

You shouldn't put reference & to pass a variable by reference, simply pass it.

dummyData(A);

Passing by reference means that you are not copying the object, instead you are using the object itself and, if passed as variable (not const) changes will affect it.

Tamer Shlash
  • 9,314
  • 5
  • 44
  • 82
1
dummyData(&A);    

should be

dummyData(A);

The & operator in this context is taking the address of A which is a pointer. To pass a reference you just use the actual variable name.

Nick
  • 25,026
  • 7
  • 51
  • 83
  • changed dummyData(A); but still D:\c++\Begin\Lab3-5_OOP\Debug/../M.cpp:22: undefined reference to `void dummyData(Array&)' – Bogdan Maier Apr 18 '12 at 16:15