Using C++ Abstract Class Declarations for Hiding Private Methods and Members
Introduction
In the C++ application development, sometimes, we would like to hide the private methods and member variables so that the users will not try to get access to those member methods and variables.
In this blog post, I would like to briefly discuss how to do it using abstract class declarations.
Abstract Class
An abstract class is a class that either defines or inherits at least one function for which the final overrider is pure virtual.
To understand virtual and pure virtual, we have to understand what C++ polymorphisms are. I have a blog post “C++ Polymorphisms” on this topic. Some of its simple examples could also be found on CPP Reference.
Example
Here we would create a bot application which will simply introduce itself and say hello to the user. All the source code could be found on my GitHub.
We would like to create an implementation for class Bot
. The following declaration was used for building the library libbot.so
.
1 |
|
However, sometimes, we don’t want the users to know the private methods and members. In more complex cases, the number of private methods and members could be huge. Only the public methods are designed to be useful for the users. If we provide the following simplified header to the users, and ask the users to use the header in their application implementations, the users will run into problems.
1 |
|
This is because C++ has to know all the methods and the members of an object during compile-time. The size of such object is thus determined during compile-time. Using an object declaration that does not contain the private methods and members that it should have will result in the building of an incomplete object during runtime. Thus running those applications will run into errors if any private methods and members were accessed by the public methods.
So what could we do if we would like to only expose the public methods and the program is still executable? We could use abstract class. The following header is used for building the library libvirtual_bot.so
.
1 |
|
The following header is given to the user for creating the application.
1 |
|
With this header, the users do not know the existence of Bot
yet they can still call all the public methods of Bot
. All they should deal with is the abstract class IBot
. An instance of Bot
could be created by calling the createBot
method and returning a base IBot
pointer.
References
Using C++ Abstract Class Declarations for Hiding Private Methods and Members
https://leimao.github.io/blog/CPP-Public-Header-Abstract-Class-Declarations/