Hi, I have was doing one exercise where I have to implement some kind of interface so Container with some stuff but I stopped here!
I got a bit confused what would be the best way to overload operator->() and operator*() and I started to test how things are looking when I overloaded them the way I did. And this was really confusing to me.
#include <vector>
#include <iostream>
template<typename Container>
class Interface
{
public:
explicit Interface(Container& cont) : ptr{ &cont } {}
Container& operator*() { return *ptr; }
Container* operator->() { return ptr; }
private:
Container* ptr;
};
int main()
{
std::vector<int> vec{ 1,2,3,4,5,6,7,8,9 };
Interface<std::vector<int>> p{ vec };
//BOTH LINES OF CODE ARE GETTING ME THE CORRECT SIZE OF VECTOR
int x = p->size(); //why is this accessing vector just with one operation?
int y = p.operator->()->size(); //this actually makes sence, 1st access pointer to vector and 2nd its member function
std::cout << x << std::endl;
std::cout << y << std::endl;
system("pause");
}
By what language rules is the 1st line actually working? (int x = p->size();)
Tnx for reply. Question is about thats its weird that if i overload these operatos like this so that they do the same thing
1 2 3
//both returning exactly the same thing : Container*
Container* operator*() { return ptr; }
Container* operator->() { return ptr; }
Doesn't make sence to me that
1 2 3 4 5 6 7 8
/*method one has to use
1. operator*() to access pointer to container
2. now use operator->() to get the desired member function*/
std::cout << " size = " << (*p)->size() << std::endl;
/*method 2 has to use
1. operator->() to access pointer to container
2. there are no step 2 coz access of Container* and its member function size() happens with one step */
std::cout << " size = " << p->size() << std::endl;
Tnx for replies. Ill try to explain the problem more clearly. This example was very cool, tnx a lot man! However I saw that it was working but didnt really understand why.
Maybe someone could explain a bit more this part
1 2 3
// p2 is not a pointer; resolve overload; p2->foo() == p2.operator->()->foo()
// p2.operator->() yields p1; p1 is not a pointer; resolve overload; p1->foo() == p1.operator->()->foo()
// ie. p2.operator->().operator->()->foo()
I see that p2->foo() == p2.operator->().operator->()->foo()
but exactly why that is happening. If I was compiler writer I would give the following error
error : ptr_1<T> doesnt have member function foo()
Better yet - when I'm actually creating function foo() for ptr_1<T> and im not modifying anything else in the JLBorges program