Although a constructor cannot be virtual, a cloning method can be virtual. Let us consider the example in listing 3.
Listing 3: | virtualclone |
In this example, line 20 starts the definition of a overriden virtual cloning function. Note that there is no explicit cast. This is because it is a method of class B, so we know exactly the type of this is (B *). The return value is not explicitly casted because the compiler can handle an implicit static up cast.
With the class definitions in listing 3, we can test it with the code in listing 4.
Listing 4: | usevirtualclone |
The output of listing 4 is "A::m1", followed by "B::m1".