C++ Polymorphism-Abstract classes- Interfaces-Data Encapsulation in C++
C++ Polymorphism-Abstract classes- Interfaces-Data Encapsulation in C++
In this case, it makes sense to create a function having the same name
calculateArea() in both the derived classes rather than creating
functions with different names, thus making our code more consistent.
outputs
The reason for the incorrect output is that the call of the
function area() is being set once by the compiler as the version
defined in the base class. This is called static resolution of the
function call, or static linkage - the function call is fixed before
the program is executed. This is also sometimes called early
binding because the area() function is set during the
compilation of the program.
We can change the virtual function area() in the base class to the following −
Abstract classes- Interfaces
• The C++ interfaces are implemented using abstract classes and these
abstract classes should not be confused with data abstraction which is
a concept of keeping implementation details separate from
associated data.
• A class is made abstract by declaring at least one of its functions
as pure virtual function. A pure virtual function is specified by placing
"= 0" in its declaration as follows −
• An interface describes the behavior or capabilities of a C++ class
without committing to a particular implementation of that class.
Abstract Class Example
Data Encapsulation in C++
• All C++ programs are composed of the following two fundamental
elements −
• Program statements (code) − This is the part of a program that
performs actions and they are called functions.
• Program data − The data is the information of the program which
gets affected by the program functions.
• Data encapsulation is a mechanism of bundling the data, and the
functions that use them and data abstraction is a mechanism of
exposing only the interfaces and hiding the implementation details
from the user.
C++ supports the properties of encapsulation and data hiding through
the creation of user-defined types, called classes. We already have
studied that a class can contain private,
protected and public members. By default, all items defined in a class
are private. For example −
The variables length, breadth, and height
are private. This means that they can be
accessed only by other members of the
Box class, and not by any other part of
your program. This is one way
encapsulation is achieved.