c++ - Virtual Function During Construction Workaround -


I have found a base class that has a virtual function; I want to call that class as it is because I want to The function for each of the derived classes is called. I know that I can not call a virtual function during the creation, but I can not think of an elegant solution (i.e., avoid repetitive code) solution.

What are some things around to do a virtual function call during construction?

The reason for this is that I want to avoid it because I do not want to make consultants who just call the base class. Class A {Public: A () {read (); } // read it at anytime Virtual Zero () = 0; } Class B: A {Public: B (): A () {}; Read () {/ * Do something special for B *}} Category C: A {Public: C (): A () {}; To read () {/ * something special to C PSY:

Python way to do this: raiseImplementedError raise in one :: read () . I'm returning to C ++ and I thought it was worse than that.

This is the factory method approach, putting the factory in the base class:

  class A {public: read the virtual zero () = 0; Template & lt; Class X & gt; Static X * Create () {X * R = New X; X- & gt; Read (); Return X;} Virtual A * Clone () const = 0; }; Class B: Public A (B): A () {}; Friend class A; Public: Read NOW () {/ * Do something special for B. * /} B * clone () const {returns new b (* this);}}; Category C: Public A (C): A () {}; Friend class A; Public: Read Zero () {/ * something special for C * /} C * clone () const {new C (* this);}};   

Added a clone -method with covariant return type as a bonus.

Usage:

  Class A {Public: // It should never be read from Virtual Z () = 0; Virtual A * Clone () const = 0; }; Template & lt; Class D, Class B & gt; Struct CRTP: B {D * Clone () {New D (* this);} Fixed D * Create () {New D (;)}} Return; Class B: Public CRTP & lt; B, A & gt; {B () {}; Public: Read Zero () {/ * Do something special for B *}}; Class C: Public CRTP & lt; C, A & gt; { C() { }; Public: Read Zero () {/ * something special for C *}};    

Comments

Popular posts from this blog

c - Mpirun hangs when mpi send and recieve is put in a loop -

python - Apply coupon to a customer's subscription based on non-stripe related actions on the site -

java - Unable to get JDBC connection in Spring application to MySQL -