2

I have an arbitrary number of derived classes all inheriting from the same base class. These derived classes all have the same static variables and static methods, although the implementations may vary from class to class. I'm using pointers to the base class in order to interface with all these derived classes. Ex:

base pt_1 = new derived_3();
base pt_2 = new derived_5();

How do I use the appropriate static variables/methods (i.e., belonging to the right derived class) as I run through each of these pointers? It's easy to use the right methods of the object by just doing pt->*method_name()* but I'm not sure how to access the static stuff of the right class.

4
  • In which language? It's often times impossible to do this reliably.
    – Telastyn
    Commented Dec 28, 2018 at 19:44
  • Sorry forgot the tag, fixed now. Commented Dec 28, 2018 at 19:44
  • 2
    Well, just add some virtual methods for getting references to the most-derived classes statics, respectively delegating to them. Naturally you have to re-implement that for every derived class which has its own version. Commented Dec 28, 2018 at 20:01
  • @Deduplicator Makes sense, I've did that and it works well now. Commented Dec 28, 2018 at 23:14

1 Answer 1

5

Trying to access the correct static members of derived classes indicates that your current model is not a good fit for the C++ language. Consider more carefully why you need this approach, and whether any of the following may be more suitable:

  • using virtual methods instead of static members
  • using templates instead of pointers to the base type
  • using dynamic casts to discover the derived type

Neither of these will feel satisfactory, but at least they might be a feasible workaround. There is also the likely possibility that any use of inheritance here is entirely misleading and should be avoided, but it is impossible to tell without more context.

1
  • I coded in virtual methods for accessing the static members and it works nicely. It's a bit of a hack but I'm just writing a testing program for my project. Commented Dec 28, 2018 at 23:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.