JunkMechanic
JunkMechanic

Reputation: 438

Cannot pass a pointer to a function

I have removed all the unwanted segments. I am trying to pass pointers to an overloaded operator and use templates too. But this is still not working.

#include<iostream.h>
#include<conio.h>

class Test{
      private:
             int a;
      public:
             Test (){}
             Test(int k){
                a=k;
             }
             Test* operator +(Test *p){
                  Test *temp=new Test(this->a+p->geta());
                  return temp;
             }
             int geta(){
                  return a;
             }
};

template<class T>  
   T* sum(T* a,T* b){
   return a+b;
}

int main(){
    Test *t1,*t2;
    t1=new Test(5);
    t2=new Test(7);
    Test *z=sum(t1,t2);
    cout<<z->geta();
    getch();
}

Upvotes: 0

Views: 183

Answers (3)

Manoj R
Manoj R

Reputation: 3247

As Nim has already answered correctly. I will simply give some suggestions.

No need for this->a. Only a will suffice.

int d=a+p->geta();   
int k=sum(2,4); is again wrong as this is going to return class and not int.   

Moreover operator+ is not right. Please learn about the reference and try to learn from some good book. This is a nice try as a first program.

Upvotes: 0

CashCow
CashCow

Reputation: 31445

Who teaches people to program C++ this way? iostream.h??? And an overload of operator+ that takes and returns a pointer?

sum will therefore fail if you are trying to use it for Test objects. As it is, it is adding ints, not Tests.

You have a pointer so when you call add you must use -> to invoke the function, but really this is a big mess.

Upvotes: 1

Nim
Nim

Reputation: 33655

Firstly, t1 is a pointer, and you are calling the add method incorrectly - should be t1->add(t2). Secondly, the sum() methods takes arguments which are not pointers, i.e. the template parameter is deduced as Test rather than Test*, hence you need to change the signature to something like:

template <typename T>
T* sum(T* a, T* b)
{
  return a->add(b); // or some variant...
}

Upvotes: 3

Related Questions