Why is the wrong function performed?

Today I came across a confusing situation that I hope someone can explain to me.

I have a C ++ program with 4 classes:

  • A Base, which just acts as a common interface,
  • A class Enrollthat subclasses Baseand has a pure virtual method enroll(),
  • A Verify, which is also subclassed Baseand has a pure virtual verify()method,
  • A Both, which subclasses both Enroll, Verifyand provides implementations for enroll()andverify()

Same:

 class Base {
    public:
       Base () { }
       virtual ~Base () { }
 };

 class Enroll : public virtual Base {
    public:
       virtual ~Enroll () { }
       virtual void enroll () = 0;
 };

 class Verify : public virtual Base {
    public:
       virtual ~Verify () { }
       virtual void verify () = 0;
 };

 class Both : public Enroll, public Verify {
    public:
       virtual ~Both () { }

       virtual void enroll () { printf ("Enrolling.\n"); }
       virtual void verify () { printf ("Verifying.\n"); }
 };

Instances Bothare created in a non-member function that simply creates a new one Bothand returns a pointer:

Both* createInstanceOfBoth () {
   return new Both();
}

, Registry, Enroll/Verify factory. createInstanceOfBoth(), Enroll Verify:

typedef Enroll* (*EnrollGenerator) ();
typedef Verify* (*VerifyGenerator) ();

class Registry {
   public:
      Registry () {
          enrollGenerator = (EnrollGenerator)&createInstanceOfBoth;
          verifyGenerator = (VerifyGenerator)&createInstanceOfBoth;              
      }

      Enroll* getEnroll () { return enrollGenerator (); }
      Verify* getVerify () { return verifyGenerator (); }

      EnrollGenerator enrollGenerator;
      VerifyGenerator verifyGenerator;
};

. getEnroll() Registry enroll() , : Enrolling.. getVerify() verify() , enroll() !

:

int main () {
   Registry registry;
   Enroll *enroller;
   Verify *verifier;

   enroller = registry.getEnroll ();
   verifier = registry.getVerify ();
   enroller->enroll ();
   verifier->verify ();
   return 0;
}

:

Enrolling.
Enrolling.

, Enroll Verify Both (class Both : public Verify, public Enroll {...}), :

Verifying.
Verifying.

, createInstanceOfBoth() Enroll Verify , :

Enroll* createInstanceOfEnroll () {
   return new Both();
}
Verify* createInstanceOfVerify () {
   return new Both();
}

:

Registry () {
    enrollGenerator = &createInstanceOfEnroll;
    verifyGenerator = &createInstanceOfVerify;        
}

, :

Enrolling.
Verifying.

: ? , - createInstanceOfBoth() , , . , : createInstanceOfBoth() , , ?

, , https://gist.github.com/833304 .

+3
1

- ( Both* Verify* Enroll*) ; , . , - Both* .

createInstanceOfBoth, Both*; , , .

+6

Source: https://habr.com/ru/post/1792974/


All Articles