Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++ have a static polymorphism implementation of interface that does not use vtable?

Does C++ have a proper implementation of interface that does not use vtable?

for example

class BaseInterface{
public:
virtual void func() const = 0;
}

class BaseInterfaceImpl:public BaseInterface{
public:
void func(){ std::cout<<"called."<<endl; }
}

BaseInterface* obj = new BaseInterfaceImpl();
obj->func();

the call to func at the last line goes to vtable to find the func ptr of BaseInterfaceImpl::func, but is there any C++ way to do that directly as the BaseInterfaceImpl is not subclassed from any other class besides the pure interface class BaseInterface?

Thanks. Gil.

like image 377
gilbertc Avatar asked Apr 06 '10 19:04

gilbertc


People also ask

In which of the following is an example of static polymorphism?

Hence according to the question- Which of the following is a mechanism of static polymorphism? Operator overloading, Function overloading, and Templates are the mechanisms of static polymorphism.

What is static and dynamic polymorphism in C++?

Dynamic polymorphism happens at run time and static polymorphism at compile time. Dynamic polymorphism requires typically a pointer indirection at run time (read the post "Demystifying virtual functions, Vtable, and VPTR in C++"), but static polymorphism has no performance costs at run time.

What is the difference between static polymorphism and dynamic polymorphism?

Static polymorphism is polymorphism that occurs at compile time, and dynamic polymorphism is polymorphism that occurs at runtime (during application execution).

What is static polymorphism?

Static polymorphism is a type of polymorphism that collects the information to call a method during compile time while dynamic polymorphism is a type of polymorphism that collects information to call a method at run time. Thus, this is the main difference between static and dynamic polymorphism.


1 Answers

Yes. It goes by the moniker CRTP. Have a gander.

like image 98
wheaties Avatar answered Oct 06 '22 22:10

wheaties