Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe if a template contains virtual function?

Tags:

c++

virtual

Early binding for template and late binding for virtual function. Therefore, is it safe if a template contains virtual function?

template<typename T> 
class base {
public:
    T data;
    virtual void fn(T t){}
};
like image 751
user966379 Avatar asked Dec 28 '22 11:12

user966379


2 Answers

It is completely safe. Once you instantiate the class template, it becomes normal class just like other classes.

template<typename T> 
class base {
public:
    T data;
    virtual void fn(T t){}
};


class derived : base<int> {
public:
    virtual void fn(int t){} //override
};

base<int> *pBase = new derived();
pBase->fn(10); //calls derived::fn()

I would also like to point out that while it is allowed virtual function in a class template, it is not allowed virtual function template inside a class (as shown below):

class A
{
   template<typename T>
   virtual void f(); //error: virtual function template is not allowed
};
like image 141
Nawaz Avatar answered Jan 16 '23 15:01

Nawaz


Yes, it's quite safe. You'd use it by having a class derive from it:

class derived : public base<int> {
    virtual void fn(int) { std::cout << "derived"; }
};

Of course, if it contains any other virtual functions (i.e., is intended to be used as a base class) you generally want to make the dtor virtual as well.

like image 41
Jerry Coffin Avatar answered Jan 16 '23 15:01

Jerry Coffin