Re: Final keyword in C++
wkaras@yahoo.com wrote:
Alexei Alexandrov wrote:
Hi All!
Are there any plans regarding adding the "final" keyword in C++ for specifying leaf classes in inheritance hierarchy? I mean, similar to what they have in Java. I know that there some tricks to achieve this in C++ today, but those tricks don't allow compiler to do any optimizations because the information is implicit. Important optimization that could be achieved is eliminating the cost of virtual call for leaf class pointer:
class IDataManager
{
public:
virtual void doWork() = 0;
};
final class DataManagerImpl : public IDataManager
{
virtual void doWork()
{
}
};
void doSomething(DataManagerImpl *dataMgr)
{
// Compiler can perform statically resolved call here because
// the pointer is to final class and the call cannot be polymorphic
dataMgr->doWork();
}
I faced such patterns several times when exposing the interface to external clients, but using the direct implementation pointer internally. I always kinda worry about redundant virtual call in such cases - I understand that it's negligible on modern architectures but still - it might be interesting.
--
Alexei Alexandrov
What are the advantages of using "final" as opposed to doing this:
class A : public Base
{
.
int final_x(int i);
virtual int x(int i) { return(final_x(i)); }
.
};
and then calling final_x instead of x for instances of A ?
Because it's horrible? What happens if someone creates a B which
inherits from A. Then those calls to final_x would start behaving
differently to the calls to x, but they look as thought they won't.
It's clear that it would be desirable for the compiler to
simply generate a single function with the (decorated)
names A::final_x and A::x both tranlating to the start
address of this (single) function.
I don't think that's at all true. 'final' implies that the author does
NOT intend the class to be inherited from. Though I think there's an
argument for saying that using a non-virtual destructor implies that
you don't intend the class to be inherited from, so you wouldn't really
need a final keyword.
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]