Base classes and virtual functions

Hi

I have a Base class that has quite a few functions which are virtual because I also want the Derived class to define them.

However, I am wrestling with some functions that are more of a *helper type* variety in the Base class. Should I make them virtual or not? Note: I am not planning to make them pure virtual (derived class may choose not to define them). If I make them virtual, the derived classes aren't even going to define them since they are suited to Base class.

However if i don't define them as virtual and just leave them in the Base class (int a; instead of virtual int a;), then i am worried that the derived class will inherit them

Is there a way for the derived class to *not inherit* these helper functions?

What is the best design in cases like this?
LuckyLucksAsked:
Who is Participating?
 
jkrCommented:
>>However, I am wrestling with some functions that are more of a *helper type* variety
>>in the Base class. Should I make them virtual or not?

Simple answer: Don't make these 'pure virtual' aka

class IMyInterface [
  public:
  virtual int AddTwoIntegers(const int a, const int b) = 0;
};

Open in new window


but rather like

class IMyInterface [
  public:
  virtual int AddTwoIntegers(const int a, const int b)  { return a + b;};
};

Open in new window


This will ensure that these functions can be overridden if that is required, but does not require them to be overidden, thus providing an infrastructure that can both be use and/or altered. The cost of a vtable (http://en.wikipedia.org/wiki/Virtual_method_table) has already been spent with the 1st method you declared as virtual and now won't add up to the bill enymore anyway.
0
 
sarabandeCommented:
functions that are more of a *helper type* variety in the Base class.
don't make them virtual. you even may think of making them static such that the could be used without an object as well.

class Base
{
     static std::vector<Base *> allBaseObjects;
     int number;
     std::string id;
public:
     // helper to create a new id
     static std::string createId() { .... };
     Base(int num) : number(num), id(createId) {}
     // get total number of Base Objects
     static int getTotalCount()  {  return allBaseObjects.size();   }
     // create a copy by virtual call
    static Base* CreateDerivedCopy(Base & derived)
    {
            return derived.CreateCopy();   // virtual call
    }  
    ...
};

Open in new window


Sara
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.