Discussion:
How to restrict inheritance in C++
(too old to reply)
Alamelu
2008-04-14 05:55:00 UTC
Permalink
I want to write a class, which by itself should restrict inheritance,
something like final class in java. Is it possible to write one in c++?

Regards,
Alamelu N
M. Shoaib Surya
2008-04-14 06:06:32 UTC
Permalink
http://www.research.att.com/~bs/bs_faq2.html#no-derivation

Regards,
Shoaib.
Post by Alamelu
I want to write a class, which by itself should restrict inheritance,
something like final class in java. Is it possible to write one in c++?
Regards,
Alamelu N
Alamelu
2008-04-15 12:11:00 UTC
Permalink
Hi,

I do not understand the concept behind it. Can you please tell how making
the class constructor private and by having a derived class with virtual base
can restrict inheritance?

And there is also a constrain of having a derived class for a class not to
be inherited

Regards,
Alamelu N
Post by M. Shoaib Surya
http://www.research.att.com/~bs/bs_faq2.html#no-derivation
Regards,
Shoaib.
Post by Alamelu
I want to write a class, which by itself should restrict inheritance,
something like final class in java. Is it possible to write one in c++?
Regards,
Alamelu N
M. Shoaib Surya
2008-04-15 12:57:09 UTC
Permalink
This is Stroustrup's solution to restrict inheritance of a class, as C++
does not have a final/sealed keyword like Java/C#.

The key idea is that, if you declare your base class constructor as private,
any class derived from it can not access that constructor. But, then it also
makes the base class itself uninstantiatable. The first workaround for that
is to use a named constructor, but that makes it not-so-clean for the client
class. And you would most probably want declare a class as final/sealed when
someone else would be the user of the class. So, here comes Stroustrup's
solution which is a little more complex for you , but makes it with a better
abstraction level for the user of your class.

You can find a little more explanation on that here:
http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.11

Read more on Private inheritance here:
http://www.parashift.com/c++-faq-lite/private-inheritance.html

Read more on Virtual inheritance here:
http://www.parashift.com/c++-faq-lite/multiple-inheritance.html#faq-25.9

Hope that will help you understand how that works.

Regards,
Shoaib.
Post by Alamelu
Hi,
I do not understand the concept behind it. Can you please tell how making
the class constructor private and by having a derived class with virtual base
can restrict inheritance?
And there is also a constrain of having a derived class for a class not to
be inherited
Regards,
Alamelu N
Post by M. Shoaib Surya
http://www.research.att.com/~bs/bs_faq2.html#no-derivation
Regards,
Shoaib.
Post by Alamelu
I want to write a class, which by itself should restrict inheritance,
something like final class in java. Is it possible to write one in c++?
Regards,
Alamelu N
Loading...