I'm still fairly new to C++ and templates and I had a question revolving them. I'm currently doing a tutorial on templates and wanted to mess around with the code. This is what I have so far:

//mypair.h

template <class T>
class mypair {
    T values [2];
  public:
    mypair (T first, T second)
    {
      values[0]=first; values[1]=second;
    }
	//T* operator->() { return &myT; };
	
	T getVal ()
	{
		return values[1];
	}
};
//main.cpp

#include <iostream>
#include "mypair.h"

using namespace std;

template <typename T> T GetMax (T a, T b);

int main()
{
	cout << GetMax(6, 7) << endl;
	mypair<int> myp(1, 2);
	
	mypair<int> *myp2 = new mypair<int>(4, 5);

	//cout << *myp2->getVal() << endl;

	return 0;
}

The above works fine (links/compiles/runs), but when I uncomment the //cout << *myp2->getVal() << endl; it fails to work and I receive the following error:
error C2100: illegal indirection

Any idea why? (autocomplete on *myp2-> seems to show getVal() correcly)

Thanks,

M

Yes, you are still fairly new to C++. The myp2 variable is a pointer to mypair<int> so must be

cout << myp2->getVal() << endl; // pointer->member
// or
cout << (*myp2).getVal() << endl;

The last code means: dereference pointer (get an object) then call member function for this object.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.