Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CSC 104 ASSIGNM-WPS Office

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

CSC 104 ASSIGNMENT.

NAME: Araoye Praise Omoaregba

DEPARTMENT: Computer Science

MATRIC NO : BU23CSC1155

LEVEL: 100LEVEL.
OBJECT ORIENTED PROGRAMMING (OOP)

Introduction to Object Oriented Programming (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.

Basically, OOP deals with clearing out the confusion and simplifying long, really long codes into
many different groups! It makes the program development easier and manageable. Moreover, it
helps you hide some parts of code from the others so that the only accessible thing remains the
feature and all its implementation details get safely hidden. This bit isn’t really possible with a
procedural style of programming.

There are some basic concepts that act as the building blocks of OOPs i.e.

1. Class

2. Objects

3. Encapsulation

4. Abstraction

5. Polymorphism

6. Inheritance

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. An Object simply means a real-world entity. It may be a phone, tablet, pen,
and so on. Object-Oriented Programming simply means designing a program or set of rules
consisting of objects and classes. An object contains both data and functionality.

Let’s try to further understand these concepts with the help of a program

1. #include<iostream>

2. using namespace std;

3.

4. class Country{

5. public:

6. string name;

7. int populationCount;

8.

9. void storeCountryInformation(string s, int n){

10. name = s;

11. populationCount = n;

12. }

13. };

14.

15. int main(){

16. Country c1;

17. c1.storeCountryInformation("India", 1300000000);

18. return 0;
19. }

Object&Class

In the above code, we created a class Country with a function to store its basic information such
as name and population count. The fields name and populationCount are called Data Members
of the class. Furthermore, the function storeCountryInformation is known as a Class Method.
Moreover, Country is a type and c1 is the reference variable that refers to the instance of class
Country.

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”.

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.

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.
Constructors & Destructors

A constructor is a unique method that is invoked at the time of object creation automatically. In
other words, a constructor constructs objects of a class. Also, an object is created at runtime
and is a runtime entity.

A destructor is a similar method with the opposite functioning. It destructs the objects within a
class and is also called automatically. They are declared similar to a default constructor except
it is preceded by tilde(~).

There can be multiple types of constructors like Default, Parameterized, Copy Constructor
declared within a class, but only one destructor function can be declared per class.

Let’s understand all of these through a code.

1 #include<iostream>

2 using namespace std;

4 class Country{

5 public:

6 string name;

7 int populationCount;

9 //Constructor

10 Country(){

11 cout<<"Country constructor envoked"<<endl;

12 }

13

14 //Destructor

15 ~Country();

16

17 //Parameterized Counstructor
18 Country(string s, int n){

19 this->name = s; // or name = s

20 populationCount = n; // or this->populationCount = n

21 }

22

23 void storeCountryInformation(string s, int n){

24 name = s;

25 populationCount = n;

26 }

27

28 void printCountryDetails(){

29 cout<<"Country Name: "<<this->name<<endl;

30 cout<<"Population Count: "<<this->populationCount<<endl;

31 }

32 };

33

34 Country::~Country(){

35 cout<<"Destructor envoked"<<endl;

36 }

37

38 int main(){

39 Country c1;

40 c1.storeCountryInformation("India", 1300000000);

41 c1.printCountryDetails();

42 Country c2 = Country("USA", 327200000);


43 c2.printCountryDetails();

44 return 0;

45 }

46 /*

47 Output:

48 Country constructor envoked

49 Country Name: India

50 Population Count: 1300000000

51 Country Name: USA

52 Population Count: 327200000

53 Destructor envoked

54 Destructor envoked

55 */

Along with the use of Default Constructor and Parameterized Constructor, a special keyword,
this has been used. It refers to nothing but the current instance of the class Country.

Benefits of OOP include:

 Modularity. Encapsulation enables objects to be self-contained, making troubleshooting


and collaborative development easier.

 Reusability. Code can be reused through inheritance, meaning a team does not have to
write the same code multiple times.

 Productivity. Programmers can construct new programs quicker through the use of
multiple libraries and reusable code.

 Easily upgradable and scalable. Programmers can implement system functionalities


independently.

 Interface descriptions. Descriptions of external systems are simple, due to message


passing techniques that are used for objects communication.

 Security. Using encapsulation and abstraction, complex code is hidden, software


maintenance is easier and internet protocols are protected.
 Flexibility. Polymorphism enables a single function to adapt to the class it is placed in.
Different objects can also pass through the same interface.

Criticism of OOP

The object-oriented programming model has been criticized by developers for multiple reasons.
The largest concern is that OOP overemphasizes the data component of software development
and does not focus enough on computation or algorithms. Additionally, OOP code may be more
complicated to write and take longer to compile.
ARRAYS IN C++
What are Arrays?

Before we start, let us first discuss what variables are. Variable is the name given to a memory
location where we want to store our values or data of any datatype.

For Example,

1 #include <iostream>

2 using namespace std;

3 int main() {

4 int num;

5 boolean myBool;

6 char let;

7 String word;

8 return 0;

9}

Here ‘num’, ‘myBool’, ‘let’, and ‘word’ are called variables.

Suppose we want to store more than one value or data of the same datatype. We have to create
multiple variables of that datatype. It creates redundancy in our code. So to store multiple data
of the same datatype in one variable only, we use arrays.

An array is a data structure that stores multiple data of the same datatype in a contiguous block
of memory. An array is a collection of elements of the same data type stored in contiguous
memory locations. It is a derived data type in C++ that can store a group of values of the same
type.

Characteristics of an Array in C++

 Homogeneous: All elements of an array must be of the same data type.

 Fixed Size: The size of an array is fixed and cannot be changed during runtime.

 Contiguous Memory Locations: Elements of an array are stored in contiguous memory


locations.

 Indexed: Each element of an array is indexed, and the index of the first element is 0.
Types of Arrays in C++

 One-Dimensional Array (1D Array): A 1D array is a collection of elements of the same


data type stored in contiguous memory locations. One-dimensional arrays in C++ are
collections of elements of the same data type arranged in a linear sequence. They are
also known as flat arrays. You can declare a one-dimensional array using the following
syntax:-

Syntax

datatype arrayName[arraySize];

Example:

1 #include <iostream>

2 using namespace std;

3 int main() {

4 int nums[3];

6 nums[0] = 10;

7 nums[1] = 20;

8 nums[2] = 30;

10 for (int i = 0; i < 3; ++i) {

11 cout<<nums[i]<<" ";

12 }

13

14 return 0;

15 }

This code declares an array of integers, traverses over this array using a for loop and
prints the elements.
 Multidimensional Array: A multidimensional array is an array of arrays. It can be 2D, 3D,
or more. Multi-dimensional arrays in C++ are used for representing data organized in
multiple dimensions such as matrices.

You can declare a multi-dimensional array using the following syntax:-

Syntax

datatype arrayName[dimension1Size][dimension2Size];

When you initialize a 2D array, you must always specify the second dimension(no. of
cols), but providing the first dimension(no. of rows) may be omitted.

Example:

1 #include <iostream>

2 using namespace std;

3 int main() {

4 int nums[][2] = {{1, 2}, {3, 4}};

6 for (int i = 0; i < 2; ++i) {

7 for(int j = 0; j < 2; ++j){

8 cout<<nums[i][j]<<" ";

9 }

10 cout<<"\n";

11 }

12

13 return 0;

14 }

Declaration of an Array in C++

The general syntax for declaring an array in C++ is:

data_type array_name[array_size];

Here,
 data_type is the type of elements to be stored in the array.

 array_name is the name of the array.

 array_size is the number of elements the array can hold.

Example of Array Declaration

int myArray[5]; // declares an integer array of size 5

Initialization of an Array in C++

Arrays can be initialized in several ways:

1. Static Initialization: The array is initialized at the time of declaration

int myArray[5] = {1, 2, 3, 4, 5};

2. Dynamic Initialization: The array is initialized using a loop or other methods during
runtime.

int myArray[5];

for (int i = 0; i < 5; i++) {

myArray[i] = i + 1;

Accessing Array Elements in C++

Array elements can be accessed using their index. The index of the first element is 0.

int myArray[5] = {1, 2, 3, 4, 5};

cout << myArray[0] << endl; // outputs 1

cout << myArray[4] << endl; // outputs 5

Operations on Arrays in C++

 Traversal: Traversing an array means accessing each element of the array.

 Insertion: Inserting an element into an array.

 Deletion: Deleting an element from an array.

 Searching: Searching for an element in an array.

 Sorting: Sorting the elements of an array in a specific order.


Advantages of Arrays in C++

 Efficient Memory Usage: Arrays store elements in contiguous memory locations, making
efficient use of memory.

 Fast Access: Array elements can be accessed quickly using their index.

 Easy Implementation: Arrays are easy to implement and use.

Disadvantages of Arrays in C++

 Fixed Size: The size of an array is fixed and cannot be changed during runtime.

 Homogeneous: All elements of an array must be of the same data type.

 Prone to Errors: Arrays are prone to errors, such as out-of-bounds access.

You might also like