Unit 1
Paradigm can also be termed as method to solve some problem or do some task.
Programming paradigm is an approach to solve problem using some programming
language or also we can say it is a method to solve a problem using tools and
techniques that are available to us following some approach. There are lots for
programming language that are known but all of them need to follow some strategy
when they are implemented and this methodology/strategy is paradigms. Apart from
varieties of programming language there are lots of paradigms to fulfill each and
every demand. They are discussed below:
1. Imperative programming paradigm: It is one of the oldest programming
paradigm. It features close relation to machine architecture. It is based on Von
Neumann architecture. It works by changing the program state through assignment
statements. It performs step by step task by changing state. The main focus is on
how to achieve the goal. The paradigm consist of several statements and after
execution of all the result is stored.
Advantages:
Very simple to implement
It contains loops, variables etc.
Disadvantage:
Complex problem cannot be solved
Less efficient and less productive
Parallel programming is not possible
Examples of Imperative programming paradigm:
C : developed by Dennis Ritchie and Ken ThompsonFortran : developed by John
Backus for IBMBasic : developed by John G Kemeny and Thomas E Kurtz
C
// average of five number in C
int marks[5] = { 12, 32, 45, 13, 19 } int sum = 0;
float average = 0.0;
for (int i = 0; i < 5; i++) {
sum = sum + marks[i];
}
average = sum / 5;
Imperative programming is divided into three broad categories: Procedural, OOP
and parallel processing. These paradigms are as follows:
Procedural programming paradigm –
This paradigm emphasizes on procedure in terms of under lying machine model.
There is no difference in between procedural and imperative approach. It has the
ability to reuse the code and it was boon at that time when it was in use because of
its reusability.
Examples of Procedural programming paradigm:
C : developed by Dennis Ritchie and Ken ThompsonC++ : developed by Bjarne
StroustrupJava : developed by James Gosling at Sun MicrosystemsColdFusion :
developed by J J AllairePascal : developed by Niklaus Wirth
Object oriented programming –
The program is written as a collection of classes and object which are meant for
communication. The smallest and basic entity is object and all kind of computation
is performed on the objects only. More emphasis is on data rather procedure. It can
handle almost all kind of real life problems which are today in scenario.
Advantages:
Data security
Inheritance
Code reusability
Flexible and abstraction is also present
Examples of Object Oriented programming paradigm:
Simula : first OOP languageJava : developed by James Gosling at Sun
MicrosystemsC++ : developed by Bjarne StroustrupObjective-C : designed by Brad
CoxVisual Basic .NET : developed by MicrosoftPython : developed by Guido van
RossumRuby : developed by Yukihiro Matsumoto Smalltalk : developed by Alan
Kay, Dan Ingalls, Adele Goldberg
Parallel processing approach –
Parallel processing is the processing of program instructions by dividing them
among multiple processors. A parallel processing system posses many numbers of
processor with the objective of running a program in less time by dividing them.
This approach seems to be like divide and conquer. Examples are NESL (one of the
oldest one) and C/C++ also supports because of some library function.
2. Declarative programming paradigm:
It is divided as Logic, Functional, Database. In computer science the declarative
programming is a style of building programs that expresses logic of computation
without talking about its control flow. It often considers programs as theories of
some logic.It may simplify writing parallel programs. The focus is on what needs to
be done rather how it should be done basically emphasize on what code is actually
doing. It just declares the result we want rather how it has be produced. This is the
only difference between imperative (how to do) and declarative (what to do)
programming paradigms. Getting into deeper we would see logic, functional and
database.
Logic programming paradigms –
It can be termed as abstract model of computation. It would solve logical problems
like puzzles, series etc. In logic programming we have a knowledge base which we
know before and along with the question and knowledge base which is given to
machine, it produces result. In normal programming languages, such concept of
knowledge base is not available but while using the concept of artificial intelligence,
machine learning we have some models like Perception model which is using the
same mechanism.
In logical programming the main emphasize is on knowledge base and the problem.
The execution of the program is very much like proof of mathematical statement,
e.g., Prolog
predicates
sumoftwonumber(integer, integer).
clauses
sumoftwonumber(0, 0).
sumoftwonumber(N, R) :-
N > 0,
N1 is N - 1,
sumoftwonumber(N1, R1),
R is R1 + N.
Functional programming paradigms –
The functional programming paradigms has its roots in mathematics and it is
language independent. The key principle of this paradigms is the execution of series
of mathematical functions. The central model for the abstraction is the function
which are meant for some specific computation and not the data structure. Data are
loosely coupled to functions.The function hide their implementation. Function can
be replaced with their values without changing the meaning of the program. Some
of the languages like perl, javascript mostly uses this paradigm.
Examples of Functional programming paradigm:
JavaScript : developed by Brendan EichHaskell : developed by Lennart Augustsson,
Dave BartonScala : developed by Martin OderskyErlang : developed by Joe
Armstrong, Robert VirdingLisp : developed by John MccarthyML : developed by
Robin MilnerClojure : developed by Rich Hickey
The next kind of approach is of Database.
Database/Data driven programming approach –
This programming methodology is based on data and its movement. Program
statements are defined by data rather than hard-coding a series of steps. A database
program is the heart of a business information system and provides file creation,
data entry, update, query and reporting functions. There are several programming
languages that are developed mostly for database application. For example SQL. It
is applied to streams of structured data, for filtering, transforming, aggregating (such
as computing statistics), or calling other programs. So it has its own wide
application.
CREATE DATABASE databaseAddress;
CREATE TABLE Addr (
PersonID int,
LastName varchar(200),
FirstName varchar(200),
Address varchar(200),
City varchar(200),
State varchar(200)
);
Charatetristics of oop
Object-oriented programming – As the name suggests uses objects in programming.
Object-oriented programming aims to implement real-world entities like inheritance,
hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together
the data and the functions that operate on them so that no other part of the code can
access this data except that function.
There are some basic concepts that act as the building blocks of OOPs i.e.
Class
Objects
Encapsulation
Abstraction
Polymorphism
Inheritance
Dynamic Binding
Message Passing
Characteristics of an Object-Oriented Programming Language
Class
The building block of C++ that leads to Object-Oriented programming is a Class. It is
a user-defined data type, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class. A class is like a
blueprint for an object. For Example: Consider the Class of Cars. There may be many
cars with different names and brands but all of them will share some common
properties like all of them will have 4 wheels, Speed Limit, Mileage range, etc. So
here, the Car is the class, and wheels, speed limits, and mileage are their properties.
A Class is a user-defined data type that has data members and member functions.
Data members are the data variables and member functions are the functions used to
manipulate these variables together these data members and member functions define
the properties and behavior of the objects in a Class.
In the above example of class Car, the data member will be speed limit, mileage, etc
and member functions can apply brakes, increase speed, etc.
We can say that a Class in C++ is a blueprint representing a group of objects which
shares some common properties and behaviors.
Object
An Object is an identifiable entity with some characteristics and behavior. An Object
is an instance of a Class. When a class is defined, no memory is allocated but when it
is instantiated (i.e. an object is created) memory is allocated.
C++
// C++ Program to show the syntax/working of Objects as a
// part of Object Oriented PProgramming
#include <iostream>
using namespace std;
class person {
char name[20];
int id;
public:
void getdetails() {}
};
int main()
{
person p1; // p1 is a object
return 0;
}
Objects take up space in memory and have an associated address like a record in
pascal or structure or union. When a program is executed the objects interact by
sending messages to one another. Each object contains data and code to manipulate
the data. Objects can interact without having to know details of each other’s data or
code, it is sufficient to know the type of message accepted and the type of response
returned by the objects.
, Encapsulation
In normal terms, Encapsulation is defined as wrapping up data and information under
a single unit. In Object-Oriented Programming, Encapsulation is defined as binding
together the data and the functions that manipulate them. Consider a real-life example
of encapsulation, in a company, there are different sections like the accounts section,
finance section, sales section, etc. The finance section handles all the financial
transactions and keeps records of all the data related to finance. Similarly, the sales
section handles all the sales-related activities and keeps records of all the sales. Now
there may arise a situation when for some reason an official from the finance section
needs all the data about sales in a particular month. In this case, he is not allowed to
directly access the data of the sales section. He will first have to contact some other
officer in the sales section and then request him to give the particular data. This is
what encapsulation is. Here the data of the sales section and the employees that can
manipulate them are wrapped under a single name “sales section”.
Encapsulation in C++
Encapsulation also leads to data abstraction or data hiding. Using encapsulation also
hides the data. In the above example, the data of any of the sections like sales,
finance, or accounts are hidden from any other section.
Abstraction
Data abstraction is one of the most essential and important features of object-oriented
programming in C++. Abstraction means displaying only essential information and
hiding the details. Data abstraction refers to providing only essential information
about the data to the outside world, hiding the background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerator will increase the speed of the car or applying brakes will stop
the car but he does not know how on pressing the accelerator the speed is actually
increasing, he does not know about the inner mechanism of the car or the
implementation of an accelerator, brakes, etc. in the car. This is what abstraction is.
Abstraction using Classes: We can implement Abstraction in C++ using classes. The
class helps us to group data members and member functions using available access
specifiers. A Class can decide which data member will be visible to the outside world
and which is not.
Abstraction in Header files: One more type of abstraction in C++ can be header files.
For example, consider the pow() method present in math.h header file. Whenever we
need to calculate the power of a number, we simply call the function pow() present in
the math.h header file and pass the numbers as arguments without knowing the
underlying algorithm according to which the function is actually calculating the
power of numbers.
Polymorphism
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
person 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 possesses different behavior
in different situations. This is called polymorphism. An operation may exhibit
different behaviors in different instances. The behavior depends upon the types of
data used in the operation. C++ supports operator overloading and function
overloading.
Operator Overloading: The process of making an operator exhibit different behaviors
in different instances is known as operator overloading.
Function Overloading: Function overloading is using a single function name to
perform different types of tasks. Polymorphism is extensively used in implementing
inheritance.
Example: Suppose we have to write a function to add some integers, sometimes there
are 2 integers, and sometimes there are 3 integers. We can write the Addition Method
with the same name having different parameters, the concerned method will be called
according to parameters.
Polymorphism in C++
Inheritance
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object-
Oriented Programming.
Sub Class: The class that inherits properties from another class is called Sub class or
Derived Class.
Super Class: The class whose properties are inherited by a sub-class is called Base
Class or Superclass.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are
reusing the fields and methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
Inheritance in C++
To know more about Inheritance, refer to this article – Inheritance in C++
Dynamic Binding
In dynamic binding, the code to be executed in response to the function call is decided
at runtime. C++ has virtual functions to support this. Because dynamic binding is
flexible, it avoids the drawbacks of static binding, which connected the function call
and definition at build time.
Example:
C++
// C++ Program to Demonstrate the Concept of Dynamic binding
// with the help of virtual function
#include <iostream>
using namespace std;
class GFG {
public:
void call_Function() // function that call print
{
print();
}
void print() // the display function
{
cout << "Printing the Base class Content" << endl;
}
};
class GFG2 : public GFG // GFG2 inherit a publicly
{
public:
void print() // GFG2's display
{
cout << "Printing the Derived class Content"
<< endl;
}
};
int main()
{
GFG geeksforgeeks; // Creating GFG's pbject
geeksforgeeks.call_Function(); // Calling call_Function
GFG2 geeksforgeeks2; // creating GFG2 object
geeksforgeeks2.call_Function(); // calling call_Function
// for GFG2 object
return 0;
}
Output
Printing the Base class Content
Printing the Base class Content
As we can see, the print() function of the parent class is called even from the derived
class object. To resolve this we use virtual functions.
Message Passing
Objects communicate with one another by sending and receiving information. A
message for an object is a request for the execution of a procedure and therefore will
invoke a function in the receiving object that generates the desired results. Message
passing involves specifying the name of the object, the name of the function, and the
information to be sent.
Class:
Class in C++ is the building block that leads to Object-Oriented
programming. It is a user-defined data type, which holds its own data
members and member functions, which can be accessed and used by
creating an instance of that class. A C++ class is like a blueprint for an
object. For Example: Consider the Class of Cars. There may be many cars
with different names and brands but all of them will share some common
properties like all of them will have 4 wheels, Speed Limit, Mileage
range, etc. So here, Car is the class, and wheels, speed limits, and mileage
are their properties.
A Class is a user-defined data type that has data members and member
functions.
DATA MEMBER & MEMBER FUNCTION:
Data members are the data variables and member functions are the
functions used to manipulate these variables together, these data members
and member functions define the properties and behavior of the objects in
a Class.
In the above example of class Car, the data member will be speed
limit, mileage, etc, and member functions can be applying
brakes, increasing speed, etc.
An Object is an instance of a Class. When a class is defined, no memory
is allocated but when it is instantiated (i.e. an object is created) memory is
allocated.
Defining Class and Declaring Objects
A class is defined in C++ using the keyword class followed by the name
of the class. The body of the class is defined inside the curly brackets and
terminated by a semicolon at the end.
Declaring Objects
When a class is defined, only the specification for the object is defined;
no memory or storage is allocated. To use the data and access functions
defined in the class, you need to create objects.
Syntax
ClassName ObjectName;
Accessing data members and member functions: The data
members and member functions of the class can be accessed using the
dot(‘.’) operator with the object. For example, if the name of the object
is obj and you want to access the member function with the
name printName() then you will have to write obj.printName().
Accessing Data Members
The public data members are also accessed in the same way given
however the private data members are not allowed to be accessed directly
by the object. Accessing a data member depends solely on the access
control of that data member. This access control is given by Access
modifiers in C++. There are three access modifiers: public, private, and
protected.
C++
// C++ program to demonstrate accessing of data members
#include <bits/stdc++.h>
using namespace std;
class Geeks {
// Access specifier
public:
// Data Members
string geekname;
// Member Functions()
void printname() { cout << "Geekname is:" << geekname; }
};
int main()
{
// Declare an object of class geeks
Geeks obj1;
// accessing data member
obj1.geekname = "Abhi";
// accessing member function
obj1.printname();
return 0;
}
Output
Geekname is:Abhi
Member Functions in Classes
There are 2 ways to define a member function:
Inside class definition
Outside class definition
To define a member function outside the class definition we have to use
the scope resolution:: operator along with the class name and function
name.
C++
// C++ program to demonstrate function
// declaration outside class
#include <bits/stdc++.h>
using namespace std;
class Geeks
{
public:
string geekname;
int id;
// printname is not defined inside class definition
void printname();
// printid is defined inside class definition
void printid()
{
cout <<"Geek id is: "<<id;
}
};
// Definition of printname using scope resolution operator ::
void Geeks::printname()
{
cout <<"Geekname is: "<<geekname;
}
int main() {
Geeks obj1;
obj1.geekname = "xyz";
obj1.id=15;
// call printname()
obj1.printname();
cout << endl;
// call printid()
obj1.printid();
return 0;
}
Output
Geekname is: xyz
Geek id is: 15
Note that all the member functions defined inside the class definition are
by default inline, but you can also make any non-class function inline by
using the keyword inline with them. Inline functions are actual functions,
which are copied everywhere during compilation, like pre-processor
macro, so the overhead of function calls is reduced.
ACCESS SPECIFIERS:
Access specifiers in C++ are used to define the level of access that
a class member variable or function can have. In C++, there are
three access specifiers: public, private, and protected. The public
access specifier is used to specify that a class member can be
accessed from anywhere, both inside and outside the class. This
means that any function or object can access the public members of
the class. The public members of a class are typically used to
represent the interface of the class. The private access specifier is
used to specify that a class member can only be accessed from
within the class. This means that any function or object outside the
class cannot access the private members of the class. The private
members of a class are typically used to represent the
implementation of the class and are hidden from the outside world.
The protected access specifier is used to specify that a class
member can be accessed from within the class and its derived
classes. This means that any function or object outside the class
hierarchy cannot access the protected members of the class. The
protected members of a class are typically used to represent the
implementation of a class that should be accessible to its derived
classes. The choice of access specifier to use for a class member
depends on the intended use of the member. If a member variable
or function needs to be accessed from outside the class, it should be
declared as public. If a member variable or function needs to be
used only within the class, it should be declared as private. If a
member variable or function needs to be used within the class
hierarchy, it should be declared as protected. One important aspect
of access specifiers is encapsulation. Encapsulation is the process of
hiding the implementation details of a class from the outside world.
By using access specifiers, a class can control the level of access to
its members and thus control the level of encapsulation.
C++ Code
1. #include <iostream>
2. using namespace std;
3. class MyClass {
4. public:
5. int publicVar; // can be accessed from anywhere
6. void publicFunc() { // can be accessed from anywhere
7. cout << "This is a public function" << endl;
8. }
9. private:
10. int privateVar; // can only be accessed from within the class
11. void privateFunc() {// can only be accessed from within the class
12. cout << "This is a private function" << endl;
13. }
14. protected:
15. int protectedVar; // can only be accessed from within the class a
nd its derived classes
16. void protectedFunc(){// can only be accessed from within the cla
ss and its derived classes
17. cout << "This is a protected function" << endl;
18. }
19. };
20. class DerivedClass : public MyClass {
21. public:
22. void derivedFunc() {
23. // can access protectedVar and protectedFunc() from base class
24. cout << "Derived function accessing protectedVar: " << protec
tedVar << endl;
25. protectedFunc();
26. }
27. };
28. int main() {
29. MyClass obj;
30. obj.publicVar = 10;
31. obj.publicFunc();
32.
33. //obj.privateVar = 20; // error: private member cannot be accesse
d
34. //obj.privateFunc(); // error: private member cannot be accessed
35. //obj.protectedVar = 30; // error: protected member cannot be acc
essed
36. //obj.protectedFunc(); // error: protected member cannot be acce
ssed
37. DerivedClass dObj;
38. //dObj.privateVar = 40; // error: private member cannot be access
ed
39. //dObj.privateFunc(); // error: private member cannot be accesse
d
40. dObj.publicVar = 50;
41. dObj.publicFunc();
42. //dObj.protectedVar = 60; // error: protected member cannot be a
ccessed
43. dObj.derivedFunc(); // okay: can access protected member fro
m derived class
44. return 0;
45. }
Explanation:
In this example, we have a class called MyClass with three member
variables and three member functions. The member variables and
functions are declared with different access specifiers. We also have
a derived class called DerivedClass that inherits from MyClass. In
the main function, we create an object of MyClass called obj and
demonstrate that we can access the public member variables and
functions, but not the private or protected ones.
Then, we create an object of DerivedClass called dObj and
demonstrate that we can access the public member variables and
functions, as well as the protected ones from within the derived
class. However, we cannot access the private member variables or
functions from the derived class. Overall, this example
demonstrates how access specifiers control the level of accessibility
of class members in C++.
Structures in C++ are user defined data types which are used to
store group of items of non-similar data types.
What is a structure?
A structure is a user-defined data type in C/C++. A structure creates
a data type that can be used to group items of possibly different
types into a single type.
Structures in C++
How to create a structure?
The ‘struct’ keyword is used to create a structure. The general
syntax to create a structure is as shown below:
struct structureName{
member1;
member2;
member3;
memberN;
};
Structures in C++ can contain two types of members:
Data Member: These members are normal C++ variables. We can
create a structure with variables of different data types in C++.
Member Functions: These members are normal C++ functions.
Along with variables, we can also include functions inside a
structure declaration.
Example:
C++
// Data Members
int roll;
int age;
int marks;
// Member Functions
void printDetails()
cout<<"Roll = "<<roll<<"\n";
cout<<"Age = "<<age<<"\
n";
cout<<"Marks = "<<marks;
In the above structure, the data members are three integer
variables to store roll number, age and marks of any student and
the member function is printDetails() which is printing all of the
above details of any student.
How to declare structure variables?
A structure variable can either be declared with structure
declaration or as a separate declaration like basic types.
C++
// A variable declaration with structure declaration.
struct Point
int x, y;
} p1; // The variable p1 is declared with 'Point'
// A variable declaration like basic data types
struct Point
int x, y;
};
int main()
{
struct Point p1; // The variable p1 is declared like a normal
variable
Note: In C++, the struct keyword is optional before in declaration of
a variable. In C, it is mandatory.
How to initialize structure members?
Structure members cannot be initialized with declaration. For
example the following C program fails in compilation.
But is considered correct in C++11 and above.
C++
struct Point
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
The reason for above error is simple, when a datatype is declared,
no memory is allocated for it. Memory is allocated only when
variables are created.
Structure members can be initialized with declaration in C++. For
Example the following C++ program Executes Successfully without
throwing any Error.
C++
// In C++ We can Initialize the Variables with Declaration in
Structure.
#include <iostream>
using namespace std;
struct Point {
int x = 0; // It is Considered as Default Arguments and no Error is
Raised
int y = 1;
};
int main()
struct Point p1;
// Accessing members of point p1
// No value is Initialized then the default value is considered. ie
x=0 and y=1;
cout << "x = " << p1.x << ", y = " << p1.y<<endl;
// Initializing the value of y = 20;
p1.y = 20;
cout << "x = " << p1.x << ", y = " << p1.y;
return 0;
// This code is contributed by Samyak Jain
x=0, y=1
x=0, y=20
Structure members can be initialized using curly braces ‘{}’. For
example, following is a valid initialization.
C++
struct Point {
int x, y;
};
int main()
// A valid initialization. member x gets value 0 and y
// gets value 1. The order of declaration is followed.
struct Point p1 = { 0, 1 };
How to access structure elements?
Structure members are accessed using dot (.) operator.
C++
#include <iostream>
using namespace std;
struct Point {
int x, y;
};
int main()
struct Point p1 = { 0, 1 };
// Accessing members of point p1
p1.x = 20;
cout << "x = " << p1.x << ", y = " << p1.y;
return 0;
Output
x = 20, y = 1
What is an array of structures?
Like other primitive data types, we can create an array of
structures.
C++
#include <iostream>
using namespace std;
struct Point {
int x, y;
};
int main()
// Create an array of structures
struct Point arr[10];
// Access array members
arr[0].x = 10;
arr[0].y = 20;
cout << arr[0].x << " " << arr[0].y;
return 0;
Output
10 20
What is a structure pointer?
Like primitive types, we can have pointer to a structure. If we have a
pointer to structure, members are accessed using arrow ( -> )
operator instead of the dot (.) operator.
C++
#include <iostream>
using namespace std;
struct Point {
int x, y;
};
int main()
struct Point p1 = { 1, 2 };
// p2 is a pointer to structure p1
struct Point* p2 = &p1;
// Accessing structure members using
// structure pointer
cout << p2->x << " " << p2->y;
return 0;
Output
12
Array of objects
An array in C/C++ or be it in any programming language
is a collection of similar data items stored at contiguous
memory locations and elements can be accessed
randomly using indices of an array. They can be used to
store the collection of primitive data types such as int,
float, double, char, etc of any particular type. To add to it,
an array in C/C++ can store derived data types such as
structures, pointers, etc. Given below is the picture
representation of an array.
Example:
Let’s consider an example of taking random integers from
the user.
Array
Array of Objects
When a class is defined, only the specification for the
object is defined; no memory or storage is allocated. To
use the data and access functions defined in the class, you
need to create objects.
Syntax:
ClassName ObjectName[number of objects];
The Array of Objects stores objects. An array of a class
type is also known as an array of objects.
Example#1:
Storing more than one Employee data. Let’s assume there
is an array of objects for storing employee data emp[50].
Below is the C++ program for storing data of one
Employee:
C++
// C++ program to implement
// the above approach
#include<iostream>
using namespace std;
class Employee
int id;
char name[30];
public:
void getdata();//Declaration of function
void putdata();//Declaration of function
};
void Employee::getdata(){//Defining of
function
cout<<"Enter Id : ";
cin>>id;
cout<<"Enter Name : ";
cin>>name;
void Employee::putdata(){//Defining of
function
cout<<id<<" ";
cout<<name<<" ";
cout<<endl;
int main(){
Employee emp; //One member
emp.getdata();//Accessing the function
emp.putdata();//Accessing the function
return 0;
}
Let’s understand the above example –
In the above example, a class named Employee with id
and name is being considered.
The two functions are declared-
getdata(): Taking user input for id and name.
putdata(): Showing the data on the console screen.
This program can take the data of only one Employee.
What if there is a requirement to add data of more than
one Employee. Here comes the answer Array of Objects.
An array of objects can be used if there is a need to store
data of more than one employee. Below is the C++
program to implement the above approach-
C++
// C++ program to implement
// the above approach
#include<iostream>
using namespace std;
class Employee
int id;
char name[30];
public:
// Declaration of function
void getdata();
// Declaration of function
void putdata();
};
// Defining the function outside
// the class
void Employee::getdata()
cout << "Enter Id : ";
cin >> id;
cout << "Enter Name : ";
cin >> name;
// Defining the function outside
// the class
void Employee::putdata()
cout << id << " ";
cout << name << " ";
cout << endl;
// Driver code
int main()
// This is an array of objects having
// maximum limit of 30 Employees
Employee emp[30];
int n, i;
cout << "Enter Number of
Employees - ";
cin >> n;
// Accessing the function
for(i = 0; i < n; i++)
emp[i].getdata();
cout << "Employee Data - " <<
endl;
// Accessing the function
for(i = 0; i < n; i++)
emp[i].putdata();
Output:
Explanation:
In this example, more than one Employee’s details with an
Employee id and name can be stored.
Employee emp[30] – This is an array of objects having a
maximum limit of 30 Employees.
Two for loops are being used-
First one to take the input from user by calling
emp[i].getdata() function.
Second one to print the data of Employee by calling the
function emp[i].putdata() function.
Example#2:
C++
// C++ program to
implement
// the above approach
#include<iostream>
using namespace std;
class item
char name[30];
int price;
public:
void getitem();
void printitem();
};
// Function to get item
details
void item::getitem()
cout << "Item Name = ";
cin >> name;
cout << "Price = ";
cin >> price;
}
// Function to print item
// details
void item ::printitem()
cout << "Name : " <<
name <<
"\n";
cout << "Price : " << price
<<
"\n";
const int size = 3;
// Driver code
int main()
item t[size];
for(int i = 0; i < size; i++)
cout << "Item : " <<
(i + 1) << "\n";
t[i].getitem();
for(int i = 0; i < size; i++)
cout << "Item Details : "
<<
(i + 1) << "\n";
t[i].printitem();
Output:
Advantages of Array of Objects:
The array of objects represent storing multiple
objects in a single name.
In an array of objects, the data can be accessed
randomly by using the index number.
Reduce the time and memory by storing the data in
a single variable.