Override Method for a Subclass Family

Given outdated code, the system has the following class hierarchy:

          Base
          ^
          |
----------+---------------
^      ^     ^     ^     ^ 
|      |     |     |     |
A1     B1    C1    D1    E1
^      ^     ^     ^     ^ 
|      |     |     |     |
A2     B2    C2    D2    E2
.......
^      ^     ^     ^     ^ 
|      |     |     |     |
An     Bn    Cn    Dn    En

A hierarchy represents messages in a specific domain.

The base class is, of course, the base class of all messages. A1..E1 - messages related to version 1 of the domain, A2..E2 to version 2, etc. Note that An must inherit directly from An-1, since A overrides certain An-1 methods.

There are some functions common to all messages, so it is defined as Base :: PerformFunctionality. Some of the functionality is specific only to version n, so there is a virtual function Base :: SpecificPartOfFunctionality, which is called by the base :: PerformFunctionality.

, , Base:: SpecificPartOfFunctionality An..En.

2 , :

  • Base:: SpecificPartOfFunctionality An..En.

    , , .

    , Fn, SpecificPartOfFunctionality.

  • BaseN, Base, An..En BaseN:

    class BaseN : public Base {
       //...
       SpecificPartOfFunctionality() { ...}
    };
    
    class An: public An-1, public BaseN { .. }
    

    , .

    , , - m Base:: SpecificPartOfFunctionality. BaseM, Base:: SpecificPartOfFunctionality. , SpecificPartOfFunctionality An - of BaseN BaseN. .

?

+5
2
struct Base {
  virtual void PerformFunctionality() {
    stuff();
    SpecificPartOfFunctionality();
    more_stuff();
  }
private:
  virtual void SpecificPartOfFunctionality() {}
};

template<class Prev>
struct Version3 : Prev {
protected:  // Not private if v4 override might need to call this.
  virtual void SpecificPartOfFunctionality() {
    v3_specific_stuff();
  }
};

struct A1 : Base {};
struct A2 : A1 {};
struct A3 : Version3<A2> {};

struct B1 : Base {};
struct B2 : B1 {};
struct B3 : Version3<B2> {};

, ++ , , A2 B2 .

++ 0x, , :

template<class Prev>
struct Version3 : Prev {
  using Prev::Prev;
  //...
};

struct C2 : C1 {
  C2(int);  // No default constructor.
};
struct C3 : Version3<C2> {
  C3() : Version3<C2>(42) {}
};

, An An-1, A An-1.

- . An An-1. , :

struct Example {
  virtual void f();
};

template<class B>
struct Intermediate : B {};

struct Concrete : Intermediate<Example> {
  virtual void f();  // Overrides Example::f.
};

, , An SpecificPartOfFunctionality ! An Base .

+3

, , SpecificPartsOfFunctionality , . .

void FunctionalityN(Base* b)
{
    b->DoThings();
    ...
}

class An : public Base
{
    friend void FunctionalityN();
    virtual void SpecificPartOfFunctionality() { FunctionalityN(this); }
    ....
};

, N , . Fn, Gn .. FunctionalityN NewFunctionalityN .

+1

All Articles