tags:

views:

25

answers:

1

I have multiple classes that are quite different in their behavior, but at the same time, share common functions that have to access the member variables.

So what I want to do, is to create a templated member function to avoid extra copy-paste code duplication.

The final result should be like:

ClassA::CallFoo()
ClassB::CallFoo()
ClassC::CallFoo()

where CallFoo() is defined in a shared file like [weirdo hypothetical syntax]

<template this* T>::CallFoo(){T->memberX->DoStuff();}

Is something like that possible with C++? I cant seem to find anything concerning code reuse and multiple classes.

EDIT: I have multiple classes, ClassA, ClassB, ClassC, ... ClassX, all of which have a member variable memberX. In order to use that member variable inside the member functions of the classes, I have to do some setup and preprocessing on that variable, which is equal for all of the classes. So ClassA can have a method DoCoolStuff1() which has to call [shared code] to get the updated shared variable, ClassB can have a method DoBoringStuff1() which also calls [shared code].

Unfortunately, memberX is not in my source code, but in library headers ClassA : public LibClass, so I cannot override it there.

+1  A: 

If what you are saying is that all of these classes inherit from LibClass, which contains memberX, then just add one more layer of inheritance:

class myLibClass : public LibClass
{
    void CallFoo() { // do stuff with memberX }
};

class classA : public myLibClass {};
class classB : public myLibClass {};
etc...
PigBen