Why does the compiler enable this virtual function in the template class?

I know that there are few threads in this thread. But what really confused me - the result I got is different from what everyone says.

Check out this code below (compiled using GCC441):

#include <iostream> using namespace std; template<class T> class A { public: A(T &t) : _a(t) {}; virtual ~A() { cout << "Dtor-A" << endl;}; virtual void print () { cout << "A: " << _a << endl; } T _a; }; class B : public A<int> { public: B(int t) : A<int>(t) {} ~B() { cout << "Dtor-B" << endl;}; void print() { cout << "B: " << endl; } }; int main() { B b(2); A<int> *a = &b; a->print(); A<int> *a2 = new B(4); a2->print(); delete a2; } 

Result:

 B: B: Dtor-B Dtor-A Dtor-B Dtor-A 

If the virtual function is not allowed in the template class, why did I get this result?

+6
source share
2 answers

You cannot have a virtual function template in a class - That would be pointless - but the virtual function in the class template is beautiful.

After creating an instance of the Foo class, the resulting Foo<T> class has virtual functions that can be used as if they were part of any other type.

Let's look at the difference between the two:

Out of order

 struct Foo { template <typename T> virtual void bar() {} // Foo::bar<T> - prohibited, as marked "virtual" }; // Impossible to resolve calls to Foo::bar<T>() at runtime, since // such calls may require template instantiation, which may only occur // at compile-time. 

Ok

 template <typename T> struct Foo { virtual void bar() {} // Foo<T>::bar }; // If Foo<T> is used in the program, then it will exist, in entirety. // Foo<T>::bar() may thus be used as noraml. 
+13
source

The behavior is correct. The virtual member function template is what you mention.

0
source

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


All Articles