Sign in to follow this  

Help with weird code

Recommended Posts

#include <iostream>
#include <vector>

using namespace std;

class Obj {
  static int i, j;
  void f() const { cout << i++ << endl; }
  void g() const { cout << j++ << endl; }

// Static member definitions:
int Obj::i = 47;
int Obj::j = 11;

// Container:
class ObjContainer {
  vector<Obj*> a;
  void add(Obj* obj) { a.push_back(obj); }
  friend class SmartPointer;

class SmartPointer {
  ObjContainer& oc;
  int index;
  SmartPointer(ObjContainer& objc) : oc(objc) {
    index = 0;
  // Return value indicates end of list:
  bool operator++() { // Prefix
    if(index >= oc.a.size()) return false;
    if(oc.a[++index] == 0) return false;
    return true;
  bool operator++(int) { // Postfix
    return operator++(); // Use prefix version
  Obj* operator->() const {
    return oc.a[index];

int main() {
  const int sz = 10;
  Obj o[sz];
  ObjContainer oc;
  for(int i = 0; i < sz; i++)
    oc.add(&o[i]); // Fill it up
  SmartPointer sp(oc); // Create an iterator
  do {
    sp->f(); // Pointer dereference operator call
  } while(sp++);
} ///:~


The code compiles,in case you want to know.Now,the problem:

when the function for the overloaded -> is called,it returns a pointer.I don't understand how an UNDEREFERENCED pointer can acces a function.



right there,the -> function is called,it returns a pointer and it immediatly has acces to functions,why? Shouldn't it be dereferenced first? Or it got dereferenced somewhere else,but I can't see where?

Share this post

Link to post
Share on other sites

Did you get this code from here? If so, the answer is right at the top. If not, let me quote:


The dereferencing operator-> can be defined as a unary postfix operator. That is, given a class:


class Ptr{
X * operator->();


Objects of class Ptr can be used to access members of class X in a very similar manner to the way pointers are used. For example:


void f(Ptr p )
p->m = 10 ; // (p.operator->())->m = 10

The statement p->m is interpreted as (p.operator->())->m. Using the same concept, following example explain how a class access operator -> can be overloaded.

Share this post

Link to post
Share on other sites
When the -> operator is overloaded the returned value is then used as the left hand side of another application of -> with the previous right hand side. This is why -> is overloaded as a unary operator rather than a binary operator. So your smart pointer returns a pointer and that pointer then has -> applied to it with f() or g() on the right hand side.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this