Can I use virtual functions in a template class? Can a template member function be a virtual function? __ function

Source: Internet
Author: User

Content reproduced from the CSDN forum.

1, you can use virtual functions in a template class.

Exactly the same,
How to use virtual functions in non-template classes,
How to use it in the template class.

Template class<t>
Class A
{
Public
virtual void F1 () {cout<< "A is called" <<ENDL;} virtual function
virtual void F2 () =0{cout<< "a=0" <<ENDL;} Pure virtual function
};

Template class<t>
Class B:public A<t>
{
Public
void F1 () {cout<< "B is called" <<ENDL;}
void F2 () {cout<< "b!=0" <<ENDL;}
};

void Main ()
{
a<int>* p=new b<int>;
P->F1 (); Output B is called, virtual function succeeded
}

The only thing to note is:
A<int> and a<char> are two completely different classes.

The top code cannot be a<int>* p = new b<char>;

Because A<int> is not a base class for b<char>.

So we conclude that the template does not affect the polymorphism of the class.

2, a template member function may not be a virtual function.

Explanation 1:

The compiler expects to be able to determine the size of the virtual function table for this class when dealing with the definition of the class. If you allow a virtual member template function for a class, you must ask the compiler to know in advance all calls to that virtual member template function for that class in the program, which is not feasible.

Explanation 2:

When instantiating a template class, you need to create a vertual table.
It is not possible to determine how many function templates, including virtual function templates, join support, can be instantiated before the template class is instantiated.
The normal member function template doesn't matter what time you need to instantiate it, the compiler doesn't have to know how many to instantiate, the number of virtual functions must be known, otherwise the class cannot be instantiated (because you want to create virtual table). Therefore, virtual function templates are not currently supported.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.