Yes, but why do you want to? There are two common answers:
- for efficiency: to avoid my function calls being virtual
- for safety: to ensure that my class is not used as a base class (for example, to be sure that I can copy objects without fear of slicing)
If there is a genuine need for "capping" a class hierarchy to avoid virtual function calls, one might ask why those functions are virtual in the first place. I have seen examples where performance-critical functions had been made virtual for no good reason, just because "that's the way we usually do it".
The other variant of this problem, how to prevent derivation for logical reasons, has a solution. Unfortunately, that solution is not pretty. It relies on the fact that the most derived class in a hierarchy must construct a virtual base. For example:
class Usable;
class Usable_lock {
friend class Usable;
private:
Usable_lock() {}
Usable_lock(const Usable_lock&) {}
};
class Usable : public virtual Usable_lock {
// ...
public:
Usable();
Usable(char*);
// ...
};
Usable a;
class DD : public Usable { };
DD dd; // error: DD::DD() cannot access
// Usable_lock::Usable_lock(): private member
本文探讨了C++中虚函数调用的实际效率,并解释了为何通常无需担心其带来的性能开销。此外,还介绍了一种防止类被继承的方法,以确保对象复制的安全性。
2023

被折叠的 条评论
为什么被折叠?



