0% found this document useful (0 votes)
8 views32 pages

Unit 4 ObjectsAD

Objects in object-oriented programming (OOP) are entities created from classes that encapsulate attributes and behaviors. Key characteristics of objects include identity, state, and behavior, and they can be categorized into various types such as function objects and immutable objects. OOP principles like inheritance, encapsulation, and polymorphism enhance code reusability and maintainability, while message classes facilitate communication between objects.

Uploaded by

Shameem Akhtar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views32 pages

Unit 4 ObjectsAD

Objects in object-oriented programming (OOP) are entities created from classes that encapsulate attributes and behaviors. Key characteristics of objects include identity, state, and behavior, and they can be categorized into various types such as function objects and immutable objects. OOP principles like inheritance, encapsulation, and polymorphism enhance code reusability and maintainability, while message classes facilitate communication between objects.

Uploaded by

Shameem Akhtar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Unit 4: objects

What are Objects in Programming?

In object-oriented programming (OOP), objects are the basic entities that actually exists
in the memory. Each object is based on a blueprint of attributes and behaviours
(variables and functions) defined as Class.
The basic purpose of a Class is to identify the common attributes and behaviours and
group them as an entity that can be reused again and again for similar purposes. The
Objects are such entities that are created based on these classes to follow that
purpose. All data members and member functions of the class can be accessed with the
help of objects. When a class is defined, no memory is allocated, but memory is
allocated when it is instantiated (i.e. an object is created).
Example of Object
For Example, the objects for the class Account are SBI Account, ICICI account, etc.

Characteristics of an object
As discussed above, every object has some attributes and behaviours, but it is very
important to understand what are the characteristics, that every object must have:
1. Identity: Every object must have a different identity from the other, known as the
object’s name. No two object must have the same name.
2. State: If there are some properties of a class, that is designed to be derived in an
object, it must have some values to get initiated (usually done with the help of
constructors).
3. Behaviour: Now since the object have a name and some properties, it must have
some purpose as well. So these purposes are defined with help of functions
(processes) and are known as behaviours.
Some of the things in programming that can be defined as objects include the following:

• variables, which hold values that can be changed;


• data structures, which are specialized formats used to organize and process data;
• functions, which are named procedures that perform a defined task; and
• methods, which are programmed procedures that are defined as components of a
parent class and are included in any instance of that class.

Objects can do things and can have things done to them. For example, a function or
method object can be programmed to modify the contents of a data structure or variable
object.

Object-based languages
Object-based languages support the full complement of features of object-oriented
programming. These features are as follows:

In object-oriented programming, objects have identity, state and behaviors associated


with them.

• Abstraction means that hiding implementation code that is not necessary for use by
other objects. This helps make it easier for developers to change or add to objects
over time.
• Polymorphism means that an object can mean or be used differently in different
contexts.
• Inheritance means that object classes can reuse code from other classes. For
example, relationships between objects can be assigned to create a class hierarchy,
which enables developers to reuse coding logic to create families of related objects.
• Data encapsulation means that objects contain everything they need to function,
including the object methods and any related data. The object can then make its
interfaces available to other objects to enable them to use the object.

Most modern programming languages are considered object-oriented languages, but


some are more object-oriented than others, depending on how the OOP principles are
implemented in the language and how they are used. Some languages that were
originally designed as procedural programming languages have, over the years, had
OOP features added.

Some of the most common languages that are considered to be object-oriented


currently in use include the following:

• Java
• Python
• C++
• C#
• Ruby
• PHP
• Lisp
• MATLAB
• R
• NET
• JavaScript
Benefits of using objects in programming
Using objects in programming has become commonplace, as most modern
programming languages now support some or all of the principles of object-oriented
programming. Some of the most important benefits of using objects in programming
include the following:

• Code reuse is simplified using objects. Objects can be reused as is or modified


slightly to enhance or modify object functions.
• Debugging is easier when objects are in use and a coding issue arises. Rather than
having to review all of a codebase, developers can identify the object that is causing
the issue. Debugging is simplified because a troublesome object can be replaced
with a simpler object.
• Objects can be deployed without revealing details of their implementations.
• Modularity of objects means that they can be easily developed, updated and shared.

That is not to say that programming with objects does not have a downside. Some of
the disadvantages of using objects in programming include the following:

• OOP concepts can be difficult to learn and learning to program with objects can be
more complicated than learning to program with procedure programming languages.
• OOP programs can be significantly larger than procedural programs.
• OOP programs can run more slowly than programs written in procedural
programming languages.

The differences between types of programming languages may not be as critical for
simple programs, but for more complex programming projects there are differences that
make one programming framework better than another.

Types of objects
Objects can be categorized based on what they do or how they work. Some of the most
commonly used types of objects include the following:

• Function objects contain a single function and are used similarly to operating
system or programming language functions.
• Immutable objects are not changed after their creation. Data and state of the object
are fixed and are not changed by use of functions.
• Container objects may contain other objects.
• Factory objects are designed to create other objects.

These and other types of objects are based on design patterns, which represent
repeatable solutions to common tasks or problems in programming. The patterns
themselves are not objects but are used to develop objects that fulfill the functions of
those patterns.

God objects are objects that break the rules by doing more than one thing. If you're still
learning object- oriented programming, find out how to refactor the God object class
antipattern. Otherwise, get started with this breakdown of object-oriented programming
concepts.
Messages classes: A Message Class is a programming concept used in object-
oriented languages, which represents a set of messages that objects can send, receive,
and process. It forms the basis for communication between objects in a system, making
it essential for designing software applications.
Definition

Message Class, in the context of technology, refers to a predefined category or type


assigned to a message in communication systems, such as email or messaging
applications. This classification allows for efficient organization, handling, and
processing of messages based on their function or purpose. Examples of message
classes include system notifications, user data, control signals, and error messages.

Key Takeaways
4. Message Class is a term used in Object-Oriented Programming (OOP) to define
a class or template that represents a message or communication exchanged
between objects in a system.
5. Message Classes encapsulate the data and behavior of messages, allowing for
structured and organized passing of information through various components of a
software application.
6. Implementing Message Classes can enhance code maintainability and increase
the overall effectiveness of communication between objects, making it easier to
manage complex systems and troubleshoot issues.
Importance

The technology term “Message Class” is important because it refers to the


categorization and organization of messages exchanged between different
communication systems or components within a network.

These classes allow streamlined processing, parsing, and interpretation of different


types of messages that conform to particular protocols, making it easier for developers
to design and implement software applications.

Additionally, message classes enable error detection and handling, ensuring the
intended information is exchanged correctly across diverse platforms.

Ultimately, they contribute to efficient communication and interoperability between


various systems, fostering development in the technology sector.
Examples of Message Class

Message Class is a term used in various technological contexts, referring to a category


or type of messages within a communication system. Here are three real-world
examples:

Email Systems: Message classes are used in email systems like Outlook to categorize
different types of email messages. For example, standard email messages have the
IPM.Note message class, while meeting requests have the
IPM.Schedule.Meeting.Request message class. This enables the email client to handle
and display different message types correctly.

Telecommunication Protocols: In the GSM mobile communication system, message


classes are used to differentiate between different types of SMS messages. There are
four classes: Class 0 (immediate display), Class 1 (stored on the mobile device), Class
2 (SIM card storage), and Class 3 (no storage). Each class has distinct handling and
storage rules.

Message-Oriented Middleware: Messaging systems like IBM MQ or Apache Kafka use


message classes to manage and route messages among different applications. Each
message sent to the system is assigned a class based on its content or intended
purpose so that it can be accurately processed and delivered to the appropriate
recipients.These examples demonstrate how message classes play a crucial role in
organizing and managing messages in a wide range of technological contexts, from
email communication to large-scale distributed systems.

What is a Message Class?

A Message Class is a programming concept used in object-oriented languages, which


represents a set of messages that objects can send, receive, and process. It forms the
basis for communication between objects in a system, making it essential for designing
software applications.

What are the key features of a Message Class?

Some of the key features of a Message Class are:


• Clear communication: A Message Class enables clear communication between
objects in a system by defining a set of messages that objects can send and
receive.
• Reusability: By defining a reusable and well-structured set of messages, a
Message Class can be used across different projects and applications to reduce
code duplication.
• Encapsulation: A Message Class abstracts the details of how a message is sent,
allowing objects to send messages without needing to know the underlying
implementation details.
• Flexibility: A Message Class can be easily modified or extended to accommodate
changes to the communication requirements between objects in a system.
How does a Message Class differ from a class in Object-Oriented Programming (OOP)?

While a Message Class focuses on the set of messages that objects can send, receive,
and process, a class in OOP is an abstraction that defines a blueprint for creating
objects. A class typically consists of attributes (data) and methods (actions), while a
Message Class solely focuses on the actions, specifically the communication, that
objects can perform.

In which programming languages can I implement Message Classes?

Message Classes can be implemented in a wide range of object-oriented languages,


such as Java, C++, Python, Ruby, and JavaScript. The concept of Message Class is
fairly universal and can be adapted to almost any language that supports object-
oriented programming.

How can I use a Message Class in my software project?

To use a Message Class in your software project, you should follow these steps:

7. Identify the communication requirements between objects in your system.


8. Define a Message Class that encapsulates the set of messages needed to fulfill
these requirements, keeping the set of messages as concise and descriptive as
possible.
9. Implement the Message Class in your chosen programming language, making
sure that it is easily reusable, extendable, and maintainable.
10. Incorporate the newly created Message Class into your project’s object hierarchy
to enable communication between objects and facilitate efficient message
processing.
What is Inheritance?
Inheritance is a mechanism of acquiring the features and behaviors of a class by another
class. The class whose members are inherited is called the base class, and the class that
inherits those members is called the derived class. Inheritance implements the IS-A
relationship.

In the above figure:


• A car is a Vehicle
• A bus is a Vehicle
• A truck is a Vehicle
• A bike is a Vehicle
Inheritance is one of the core aspects of Object-Oriented Programming (OOP) and it
provides a way of achieving code re-usability. It prevents the need to write the same code
multiple times.
Understand inheritence: To dig deep more into inheritance, firstly we need to understand
the two types of programming classes
• Sub Class: The class that inherits properties from another class is called Subclass
or Derived Class.
• Super Class: The class whose properties are inherited by a subclass is called Base
Class or Superclass.
Modes of Inheritance: There are 3 modes of inheritance.
11. Public Mode: If we derive a subclass from a public base class. Then the public
member of the base class will become public in the derived class and protected
members of the base class will become protected in the derived class.
12. Protected Mode: If we derive a subclass from a Protected base class. Then both
public members and protected members of the base class will become protected in
the derived class.
13. Private Mode: If we derive a subclass from a Private base class. Then both public
members and protected members of the base class will become Private in the
derived class.
Note: The private members in the base class cannot be directly accessed in the derived
class, while protected members can be directly accessed. For example, Classes B, C,
and D all contain the variables x, y, and z in the below example. It is just a question of
access.
The below table summarizes the above three modes and shows the access specifier of
the members of the base class in the subclass when derived in public, protected and
private modes:

Different Types of Inheritance


OOP supports six different types of inheritance as given below:
14. Single Inheritance
15. Multi-level Inheritance
16. Multiple Inheritance
17. Multipath Inheritance
18. Hierarchical Inheritance
19. Hybrid Inheritance
1. Single Inheritance

In this type of inheritance, a derived class is created from a single base class.
In the given figure, Class A is the parent class and Class B is the child class since Class
B inherits the features and behavior of the parent class A.

2. Multi-level inheritance

In this inheritance, a derived class is created from another derived class.

In the given figure, class C inherits the properties and behavior of class B and class B
inherits from class A. So, here A is the parent class of B and class B is the parent class
of C. So, here class C implicitly inherits the properties and behavior of Class A along with
Class B i.e. there is a multilevel inheritance.
3. Multiple inheritance

In this inheritance, a derived class is created from more than one base class. This
inheritance is not supported by .NET Languages like C#, F#, etc., and Java Language.

In the given figure, class C inherits the properties and behavior of classes B and A at the
same level. So, here A and B both are the parent classes for Class C.

Syntax for Multiple Inheritance

//Base Class
class A
{
public void fooA()
{
//TO DO:
}
}

//Base Class
class B
{
public void fooB()
{
//TO DO:
}
}

//Derived Class
class C : A, B
{
public void fooC()
{
//TO DO:
}
}

4. Multipath Inheritance

In this inheritance, a derived class is created from other derived classes and the same
base class of other derived classes. This inheritance is not supported by .NET Languages
like C#, F#, etc.

In the given figure, class D inherits the properties and behavior of classes C and B. Both
class C and class B inherit Class A. So, Class A is the parent for Class B and Class C as
well as Class D. So it's making a Multipath inheritance.

Syntax for Multipath Inheritance

//Base Class
class A
{
public void fooA()
{
//TO DO:
}
}

//Derived Class
class B: A
{
public void fooB()
{
//TO DO:
}
}

//Derived Class
class C: A
{
public void fooC()
{
//TO DO:
}
}

//Derived Class
class D: B, C
{
public void fooD()
{
//TO DO:
}
}

5. Hierarchical Inheritance

In this inheritance, more than one derived class is created from a single base class and
further child classes act as parent classes for more than one child class.

In the given figure, class C has two children class A and class B.
Syntax for Hierarchical Inheritance

//Base Class
class C
{
public void fooA()
{
//TO DO:
}
}

//Derived Class
class A: C
{
public void fooB()
{
//TO DO:
}
}

//Derived Class
class B: C
{
public void fooC()
{
//TO DO:
}
}

6. Hybrid Inheritance

This is a combination of more than one inheritance. Hence, it may be a combination of


Multilevel and Multiple inheritance or a combination of Hierarchical and Multilevel
inheritance.
Since .NET Languages like C#, F#, etc. do not support multiple and multipath inheritance.
Hence hybrid inheritance with a combination of multiple or multipath inheritances is not
supported by .NET Languages.
Syntax for Hybrid Inheritance

//Base Class
class A
{
public void fooA()
{
//TO DO:
}
}

//Derived Class
class C: A
{
public void fooC()
{
//TO DO:
}
}

//Base Class
class F
{
public void fooF()
{
//TO DO:
}
}

//Derived Class
class B: C, F
{
public void fooB()
{
//TO DO:
}
}

Advantages of Inheritance

20. Reduce code redundancy.


21. Provides better code reusabilities.
22. Reduces source code size and improves code readability.
23. The code is easy to manage and divided into parent and child classes.
24. Supports code extensibility by overriding the base class functionality within child
classes.
25. Code usability will enhance the reliability eventually where the base class code will
always be tested and debugged against the issues.

Disadvantages of Inheritance

26. In inheritance, both base and child classes are tightly coupled. Hence If you
change the code of the parent class, it will affect all the child classes.
27. In a class hierarchy, many data members remain unused and the memory
allocated is not utilized. Hence it affects the performance of your program if you
have not implemented inheritance correctly.
28. Inheritance increases the coupling between the base class and the derived class.
Any small change in the base class will directly affect all child classes that are
extending the parent class.

Polymorphism in OOPs
The word “polymorphism” means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A real-
life example of polymorphism is a person who at the same time can have different
characteristics. A man at the same time is a father, a husband, and an employee. So
the same person exhibits different behavior in different situations. This is called
polymorphism. Polymorphism is considered one of the important features of Object-
Oriented Programming.
Types of Polymorphism
• Compile-time Polymorphism
• Runtime Polymorphism

1. Compile-Time Polymorphism
This type of polymorphism is achieved by function overloading or operator overloading.

A. Function Overloading

When there are multiple functions with the same name but different parameters, then
the functions are said to be overloaded, hence this is known as Function Overloading.
Functions can be overloaded by changing the number of arguments or/and
changing the type of arguments. In simple terms, it is a feature of object-oriented
programming providing many functions that have the same name but distinct
parameters when numerous tasks are listed under one function name. There are certain
Rules of Function Overloading that should be followed while overloading a function.

Below is the C++ program to show function overloading or compile-time polymorphism:

• C++

// C++ program to demonstrate


// function overloading or
// Compile-time Polymorphism
#include <bits/stdc++.h>

using namespace std;


class Geeks {
public:
// Function with 1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}

// Function with same name but


// 1 double parameter
void func(double x)
{
cout << "value of x is " << x << endl;
}

// Function with same name and


// 2 int parameters
void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y
<< endl;
}
};

// Driver code
int main()
{
Geeks obj1;

// Function being called depends


// on the parameters passed
// func() is called with int value
obj1.func(7);

// func() is called with double value


obj1.func(9.132);

// func() is called with 2 int values


obj1.func(85, 64);
return 0;
}
Outputvalue of x is 7
value of x is 9.132
value of x and y is 85, 64

Explanation: In the above example, a single function named function func() acts
differently in three different situations, which is a property of polymorphism. To know
more about this, you can refer to the article – Function Overloading in C++.

B. Operator Overloading

C++ has the ability to provide the operators with a special meaning for a data type, this
ability is known as operator overloading. For example, we can make use of the addition
operator (+) for string class to concatenate two strings. We know that the task of this
operator is to add two operands. So a single operator ‘+’, when placed between integer
operands, adds them and when placed between string operands, concatenates them.

Below is the C++ program to demonstrate operator overloading:

• CPP

// C++ program to demonstrate


// Operator Overloading or
// Compile-Time Polymorphism
#include <iostream>
using namespace std;

class Complex {
private:
int real, imag;

public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}

// This is automatically called


// when '+' is used with between
// two Complex objects
Complex operator+(Complex const& obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};

// Driver code
int main()
{
Complex c1(10, 5), c2(2, 4);

// An example call to "operator+"


Complex c3 = c1 + c2;
c3.print();
}

Output12 + i9

Explanation: In the above example, the operator ‘+’ is overloaded. Usually, this
operator is used to add two numbers (integers or floating point numbers), but here the
operator is made to perform the addition of two imaginary or complex numbers. To
know more about this one, refer to the article – Operator Overloading.
2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding and
dynamic polymorphism are other names for runtime polymorphism. The function call is
resolved at runtime in runtime polymorphism. In contrast, with compile time
polymorphism, the compiler determines which function call to bind to the object after
deducing it at runtime.

A. Function Overriding

Function Overriding occurs when a derived class has a definition for one of the member
functions of the base class. That base function is said to be overridden.

Function overriding
Explanation
Runtime Polymorphism with Data Members
Runtime Polymorphism cannot be achieved by data members in C++. Let’s see an
example where we are accessing the field by reference variable of parent class which
refers to the instance of the derived class.

• C++

// C++ program for function overriding with data members


#include <bits/stdc++.h>
using namespace std;

// base class declaration.


class Animal {
public:
string color = "Black";
};

// inheriting Animal class.


class Dog : public Animal {
public:
string color = "Grey";
};

// Driver code
int main(void)
{
Animal d = Dog(); // accessing the field by reference
// variable which refers to derived
cout << d.color;
}

OutputBlack

We can see that the parent class reference will always refer to the data member of the
parent class.

B. Virtual Function

A virtual function is a member function that is declared in the base class using the
keyword virtual and is re-defined (Overridden) in the derived class.
Some Key Points About Virtual Functions:
• Virtual functions are Dynamic in nature.
• They are defined by inserting the keyword “virtual” inside a base class and are
always declared with a base class and overridden in a child class
• A virtual function is called during Runtime
Below is the C++ program to demonstrate virtual function:

• C++

// C++ Program to demonstrate


// the Virtual Function
#include <iostream>
using namespace std;

// Declaring a Base class


class GFG_Base {

public:
// virtual function
virtual void display()
{
cout << "Called virtual Base Class function"
<< "\n\n";
}

void print()
{
cout << "Called GFG_Base print function"
<< "\n\n";
}
};

// Declaring a Child Class


class GFG_Child : public GFG_Base {

public:
void display()
{
cout << "Called GFG_Child Display Function"
<< "\n\n";
}

void print()
{
cout << "Called GFG_Child print Function"
<< "\n\n";
}
};

// Driver code
int main()
{
// Create a reference of class GFG_Base
GFG_Base* base;

GFG_Child child;

base = &child;

// This will call the virtual function


base->GFG_Base::display();

// this will call the non-virtual function


base->print();
}

OutputCalled virtual Base Class function

Called GFG_Base print function

What is Aggregation in C++?

In C++, Aggregation is used to represent the ‘HAS-A’ relationship between two objects.
It is a type of association. If in a process, one class defines another class as any entity
reference then it is known as Aggregation. With the help of aggregation, you can also
reuse the class.

An object should define the following relationships to qualify as an aggregation:-

• Must be a part of the class.


• The member can belong to one or more classes at a time.
• Member is unknown about the existence of the object.
• The relationship is unidirectional.
NOTE:- For creating or destroying the members or parts, Aggregation is not
responsible.

Let’s understand through an example between a person and the home address. This
address may belong to other persons as well. The address existed before the man and
will exist for forever. The person knows where he lives but the address does not contain
any information about what person lives. It is an example of an aggregate relationship.

Syntax:-
To put it short, aggregation is a ‘HAS-A’ relationship between the objects of 2 individual
classes. Aggregation restricts some situations of associations.
Class ClassPart
{
//instance variables
//instance methods
}
class Tech
{
ClassPart* partclass;
}
In the above, the Tech class represents the class that is a container class for other
ClassPart. And it is included in the object of the Tech class. The Tech class’s each
object holds a reference pointer to the object of the ClassPart.

Working of Aggregation in C++

In the program, Aggregation helps to represent HAS-A relation between the objects of 2
individual classes. Aggregation is more restrictive compared to the association.
Aggregation helps in making your program code more readable and understandable to
represent the relation. Using a pointer variable, you can refer to the object of one class
in the container class object.

Implementing Aggregations in C++

Below are the points which will help you to understand the implementation of
aggregations:-

• Compositional Nature:– Aggregation resembles composition. With a small


difference in semantics, both are implemented identically.
• Member Constraints:– You can also add parts as member variables in
aggregation. It also takes constructor parameters.
• Existence:– The parts will exist consequently. Class destruction can lead you to
member variable destruction.

Difference between Aggregation and Association:

Aggregation Association

Aggregation describes a special type of an Association is a relationship


association which specifies a whole and part between two classes where one
relationship. class use another.
It in flexible in nature It is inflexible in nature

Special kind of association where there is It means there is almost always a


whole-part relation between two objects link between objects

It is represented by a “has a”+ “whole-part” It is represented by a “has a”


relationship relationship

Diamond shape structure is used next to the Line segment is used between the
assembly class. components or the class

29. #include <iostream>


30. using namespace std;
31. class Address {
32. public:
33. string addressLine, city, state;
34. Address(string addressLine, string city, string state)
35. {
36. this->addressLine = addressLine;
37. this->city = city;
38. this->state = state;
39. }
40. };
41. class Employee
42. {
43. private:
44. Address* address; //Employee HAS-A Address
45. public:
46. int id;
47. string name;
48. Employee(int id, string name, Address* address)
49. {
50. this->id = id;
51. this->name = name;
52. this->address = address;
53. }
54. void display()
55. {
56. cout<<id <<" "<<name<< " "<<
57. address->addressLine<< " "<< address->city<< " "<<address-
>state<<endl;
58. }
59. };
60. int main(void) {
61. Address a1= Address("C-146, Sec-15","Noida","UP");
62. Employee e1 = Employee(101,"Nakul",&a1);
63. e1.display();
64. return 0;
65. }

Output:

101 Nakul C-146, Sec-15 Noida UP


Advantages of Aggregations in C++

• Aggregation represents unidirectional relation between the objects of 2 classes. It is


a one-direction relation.
• Aggregation also helps in improving readability and reusability of the program code.
• It helps in initiating the relation between objects of 2 classes where one class is the
Whole class and other is the part of the class. It is useful in representing the HAS-A
relation.
• Aggregation helps in making your program code more readable and
understandable to represent the relation.
Abstract Clases: Abstract Class is a special type of class which has at least one
abstract method. Abstract method is that method which has only definition, this means it
does not contain implementation of the method Only a Declaration. We can create
object of only subclass of Abstract Class.

Abstract Class in c++

An interface describes the behavior or capabilities of a C++ class without committing to


a particular implementation of that class.

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

class Box {
public:
// pure virtual function
virtual double getVolume() = 0;

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The purpose of an abstract class (often referred to as an ABC) is to provide an
appropriate base class from which other classes can inherit. Abstract classes cannot be
used to instantiate objects and serves only as an interface. Attempting to instantiate an
object of an abstract class causes a compilation error.

Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the


virtual functions, which means that it supports the interface declared by the ABC.
Failure to override a pure virtual function in a derived class, then attempting to
instantiate objects of that class, is a compilation error.

Classes that can be used to instantiate objects are called concrete classes.

Abstract Class Example

Consider the following example where parent class provides an interface to the base
class to implement a function called getArea() −

#include <iostream>
using namespace std;

// Base class
class Shape {
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w) {
width = w;
}

void setHeight(int h) {
height = h;
}

protected:
int width;
int height;
};

// Derived classes
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};

class Triangle: public Shape {


public:
int getArea() {
return (width * height)/2;
}
};

int main(void) {
Rectangle Rect;
Triangle Tri;

Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;

Tri.setWidth(5);
Tri.setHeight(7);

// Print the area of the object.


cout << "Total Triangle area: " << Tri.getArea() << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result −

Total Rectangle area: 35


Total Triangle area: 17

You can see how an abstract class defined an interface in terms of getArea() and two
other classes implemented same function but with different algorithm to calculate the
area specific to the shape.

Designing Strategy

An object-oriented system might use an abstract base class to provide a common and
standardized interface appropriate for all the external applications. Then, through
inheritance from that abstract base class, derived classes are formed that operate
similarly.

The capabilities (i.e., the public functions) offered by the external applications are
provided as pure virtual functions in the abstract base class. The implementations of
these pure virtual functions are provided in the derived classes that correspond to the
specific types of the application.

This architecture also allows new applications to be added to a system easily, even
after the system has been defined.

Interface Abstract class

An interface can only inherit from With the Extended keyword, an abstract class
another interface. can enforce an interface and inherit from
another class.

Use of the implements keyword is Use the extends keyword to inherit from an
required in order to implement an abstract class.
interface.

You might also like