Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ensure that a class has no virtual methods?

I have a class whose objects are used in shared memory. Therefore, I must be sure that they do not have virtual methods (which crash the program when called via vtable).

I would like to guard against anybody accidentally adding a virtual method in violation of this requirement. Ideally, the compiler would refuse to even compile the class if it contains virtual methods.

Solutions do not necessarily need to be standards compliant, it is sufficient if they work on Apple's gcc-4.2 or MSVC.

How can I achieve this?

like image 896
Tobias Avatar asked Nov 04 '25 10:11

Tobias


2 Answers

Well, I really think this doesn't make sense to enforce, but you could use boost type traits' is_polymorphic or std::is_polymorphic from C++11 onward.

EDIT: Example:

#include <iostream>
#include <boost/type_traits.hpp>

struct Base
{
    virtual void MyMethod() { std::cout << "My method called."; }
    virtual ~Base() {}
};

class Derived : Base
{
    virtual void MyMethod() { std::cout << "Derived"; }
};

struct POD
{
    int data;
};

int main()
{
    std::cout << boost::is_polymorphic<Base>::value << std::endl;
    std::cout << boost::is_polymorphic<Derived>::value << std::endl;
    std::cout << boost::is_polymorphic<POD>::value << std::endl;
}

//Output is
// 1
// 1
// 0
// 
like image 191
Billy ONeal Avatar answered Nov 07 '25 05:11

Billy ONeal


Add a rule to your source control that rejects check-ins that contain the word 'virtual', sends an email to a senior developer, and docks the pay of the offending party.

like image 25
Bill Avatar answered Nov 07 '25 06:11

Bill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!