Search code examples
c++syntaxfunction-prototypes

Declaring method with extended classes


quick question on declaring functions. Lets say I have the following code:

class a{
    int var;
    /* stuff*/
}

class b : a{
    /* other stuff*/
}

class c : a{
    /* more other stuff*/
}

class d{
    myFunctionThatWantsTheIntNamedVar(SubClassOfClassA SomeClassUnknownAtCompileTime);
}

and myFunctionThatWantsTheIntNamedVar() wants just that, the integer(called var) declared in the base class of a. The function in class d may be passed an instance of class b or class c, which is not known at compile time (only at run time).

Is there a way I can concisely declare a function that could take either class b or c and get that same base variable?

What I have done in the mean time is declare two methods in class d, as follows:

class d{
    myFunctionThatWantsTheIntNamedVar(c aClassCInstance);
    myFunctionThatWantsTheIntNamedVar(b aClassBInstance);
}

which is fine and all, but the code in the two methods is IDENTICAL... And from my understanding of object oriented programming, if the code is identical you should be able to combine it into a better function.

Any thoughts on this? Just looking for best practices or other advice here, as I work at a small company and getting feedback can be hard at times.

EDIT: sorry, I had an error in my code, changed it from:

myfunctionThatWantsTheInNamedVar(a aClassAInstance);

to:

myfunctionThatWantsTheInNamedVar(c aClassCInstance);

my bad.


Solution

  • Provide a public accessor method that gives access to the variable, and make sure you don't hide its name in class b and class c.

    class a{
        int var;
        /* stuff*/
     public:
      const int& getVar() const { return var; }
      int& getVar() { return var; }
    };
    

    Then take a reference to an a in oyur function:

    class d{
     public:  // you probably want a public member function
        myFunctionThatWantsTheIntNamedVar(const a& theA) {
          int n = theA.getVar();
    }
    

    Then you can call it with b or c instances:

    b b0;
    c c0;
    d d0;
    d0.myFunctionThatWantsTheIntNamedVar(b0);
    d0.myFunctionThatWantsTheIntNamedVar(c0);
    

    Bear in mind that in your code, the variable var is private, as well as the inhericance in classes b and c. For this to work, you would need to make the inheritance public:

    class b : public a { .... };
    class c : public a { .... };