0

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

2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by ArkM
0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.