mercredi 12 mai 2021

Calling parent struct inherited methods

I have a struct A that inherits from other classes (which I'm not allowed to change). Inside A and it's methods I can call inherited methods (lets say A_method(int i), for example) without problem but when I tried to write a nested struct (lets say In) and call A_method(int i) and there is were I'm stuck.

The initial code looks like this, and I can't change it, is some kind of college assigment.

#include "Player.hh"
struct A : public Player {
  static Player* factory () {
    return new A;
  }

  virtual void play () {
  }
};

RegisterPlayer(PLAYER_NAME);

Then I tried this:

#include "Player.hh"
struct A : public Player {
  static Player* factory () {
    return new A;
  }

  //My code
  struct In {
    int x;
    void do_smthing() {
      A_method(x);
    }
  }

  virtual void play () {
  }
};

RegisterPlayer(PLAYER_NAME);

Ok, from a beginning I knew I could't do this, for In to see it's parent class it should have a pointer to it but In is a often instantiated object in my code and I wanted to avoid passing this constantly to a constructor so I tried this aproach:

#include "Player.hh"
struct A : public Player {
  static Player* factory () {
    return new A;
  }

  //My code

  static struct Aux
        A* ptr;
        Aux(A* _p) { ptr = _p; }
    } aux;

  struct In {
    int x;
    void do_smthing() {
      aux.ptr->A_method(x);
    }
  }

  virtual void play () {
    //the idea is to call do_smthing() here.
  }
};

RegisterPlayer(PLAYER_NAME);

What I want to avoid (if possible) is something like this:

struct In {
  int x;
  A* ptr;

  In (A* _p) : ptr(_p) {}

  void do_smthing() {
    ptr->A_method(x);
  }
}

The main reason for this: I have more struct definitions and they they are instantiated multiple times through the rest of the (omitted) code, and I don't like the idea of seeing In(this) so many times.

I don't know if I'm completly missing something or what I want to do it's just not possible... Please ask for clarifications if necessary.

(Also, performance is kind of critical, my code will be tested with limited CPU time so I kinda have to avoid expensive approachs if possible. Using C++11)

Aucun commentaire:

Enregistrer un commentaire