[C ++ Basics] 037_write classes that cannot be inherited

Source: Internet
Author: User

1. Current scenario

In many movies and TV series, the Most martial arts is often eunuch. The so-called "to practice this skill, you must first go to the palace." Why is the martial arts of eunuch so high? I think it should be idle. If there are fathers and sons in the object-oriented world, the eunuch class should be a class that cannot have children. They cannot be inherited, but they can inherit from others.

2. Technical Issues

To implement a class that cannot be inherited, Java provides us with a keyword final, but not in C ++, how can I write a class that cannot be inherited AS A C ++ programmer? Constructor and destructor.

Why can c ++ constructor and destructor achieve this? Because c ++ has a rule in class inheritance, that is, when the subclass is instantiated, it must first call the constructor of the parent class. When the object is destroyed, you must also call the destructor of the parent class. So if we can prevent the subclass from calling the constructor and destructor of the parent class, we can.

So how can we make the constructor and destructor of a class not called by the quilt class? Private permission. Yes, members and functions with the private permission can only be used internally by the class itself. In this way, we can implement the class we want to be unable to be inherited.

Let's take a look at the code we implemented!

 1 #include <iostream> 2 using namespace std; 3  4 class Taijian{ 5 public: 6      void publicFunc(){ 7  8      } 9 10 private:11     Taijian(){}12     ~Taijian(){}13 };14 15 int main(){16     return 0;17 }

For the taijian class, if you try to inherit it, it will not pass through the compilation phase.

3. Supplement

What is the order in which c ++ classes call constructor and destructor when Inheritance occurs?

Constructor: Grandpa constructor → father constructor → son Constructor

Destructor: son destructor → father destructor → Grandpa destructor

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.