Thursday, May 11, 2017

How to create a final class in C ++? Do you know?

Hi, my dear hackers!

We continue to talk about C++.
I assume you know the Java programming language. And also I assume you know keyword final. But do you think we can use it in C++? I mean the standard of the 98-th year (ISO/IEC 14882:1998). It turns out you can!

Look at this!


I'm trying to compile and run this code. I use GNU compiler and GNU/Linux as the operation system. I know and like them!

$ g++ -Wall -Wextra -Werror -o final final.cpp
$ ./final 
cons Lock
cons A
$ g++ -Wall -Wextra -Werror -o final final.cpp -DI_WANT_ERROR
final.cpp: In constructor 'B::B()':
final.cpp:13:2: error: 'Lock::Lock()' is private
  Lock() { cout << "cons Lock" << endl; }
  ^
final.cpp:26:6: error: within this context
  B() { cout << "cons B" << endl; }
      ^
$

You can see that we have an error when we use macro I_WANT_ERROR. Why?

The constructor of the class Lock cant't be called by the child classes. However class A is a friend of class Lock. So we can create an instance of class A because the constructor of class A can call the constructor of class Lock. Do you agree with me? I continue. But if we don't use a virtual inheritance we can create an instance of class B, because the constructor of class B can call the constructor of class A and the constructor of class A can call the constructor of class Lock. It's confusing and difficult, isn't it? But if you understand everything is simple.

Look at this: B -> A -> Lock.
It's OK? Do you understand me?

But if we use the virtual inheritance the constructor of class B must call the constructor of class Lock directly! But it can't do it because it doesn't have access to it (I mean the constructor of class Lock) because the constructor of class Lock is private and class B isn't a friend of class Lock. It's a very simple, my dear friend! And it's great!

This reaction as the final keywords applied to the class, isn't it? Do you agree with me? :)


Best regards,
Vasiliy V. Bodrov aka Bodro,
the 10-11-th of May, 2017 year.

No comments:

Post a Comment

How to reverse singly linked list in C (trivial way)

There is a beautiful morning. It's snowing. And I decided to write one more article. Today it will be just simple article where I would...