0% found this document useful (0 votes)
4 views

unit1C++

Uploaded by

partho5958
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

unit1C++

Uploaded by

partho5958
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Object Oriented Programming in C++

Unit-I Introduction

What is Procedural Language?


Procedural Language is also known as 3GL which means third generation language. It is a type of
programming language that follows a procedure; set of commands or guidelines that must be
followed for smooth execution of the program. It works on step by step basis. It requires the user to
tell not only What to do but also How to do it. Its basic idea is to have a program specify the
sequence of steps that implements a particular algorithm. Hence, Procedural languages are based on
algorithms.
In this developers use variables, loops, and functions to create a program performing a specific task
which does calculations and displays a desired output.
It follows a top-down approach. It is carried out in a fixed sequence with a start and end point. The
entire program is divided into functions and its main focus is on functions only. The program’s code
executes linearly with logical steps. In this, the code is written first and executed with some
conditions. The procedure calls to decide the conditions.
There are no data-hiding features in procedural language. It is command command-driven language.
It is operated by means of commands keyed in by the user or issued by the program. In procedural
language, both iterative and recursive calls are used. It works through the state of the machine. It
returns only restricted data types and allowed values. It is highly efficient despite the fact the size of
the program is quite large and is not suitable for critical applications with complex code. It takes a lot
of time but it needs very less memory.
In procedural language, no access specifiers are used. For eg: In structure all the members are
public.
Types of Procedural Language
 FORTRAN: FORTRAN stands for FORmula TRANslation. It is used for scientific engineering
computations and high-performance computing.
 C: It is a middle-level language. It is basically designed to write System software and requires
advanced programming skills to read and write the desired code.
 BASIC: BASIC stands for Beginner All Purpose Symbolic Instruction Code. It is a high level
programming language designed for ease of use.
 Pascal: Pascal is easy to learn. It produces transparent, efficient and reliable programs.
 ALGOL: ALGOL stands for Algorithmic Language. It is mostly used for scientific calculations.
 COBOL: COBOL stands for COmmon Business Oriented Language. It is easy to read, write and
understand. It is basically designed for Business Applications.
 Java: Java is a platform independent language. It generates a machine code from source
code with the help of Just In Time compiler.
Features of Procedural Programming Language
 Local Variables: A local variable is a variable that is accessible within a specific part of a
program and in procedural language local variable is accessible only in the function in which
it is declared.
 Global Variables: A global variable is the one that is declared outside any function and can
be accessed by any function of the program written. It is opposite of local variables.
 Modularity: The process of breaking a program into several modules or functions in such a
way that each function performs a specific task is called modularity.
 Pre-defined Functions: Pre-defined function as the name suggests are the functions that are
defined beforehand and doesn’t require programmer to define it. It is basically built in
function and are already defined in the system libraries hence they are also called as library
functions.
 Parameter Passing: Parameter passing is referred as a technique used to transfer data
between various functions of the program. The data is passed in the form of parameters
between the called function and the calling function.
Advantages of Procedural Language
 Easy to understand: Procedural programming simplifies the code and makes it easy to
understand by the programmer.
 Reusability: It increases reusability of code.
 Modularity: It divides the programs into modules or functions and these functions use
different parts of the memory.
 Simplification: It simplifies the algorithm and makes it understandable by the programmer.
 Top-down approach: The program flows in linear direction.
 Versatile: Developers can use Procedural language for most basic programming projects.
Disadvantages of Procedural Language
 One can’t solve real world problem.
 Encapsulation, Inheritance, Abstraction etc can’t be performed.
 It is less secure as there is no security of data.
 Its semantics are tough and difficult to understand.
 It returns only restricted data types and allowed values.
Conclusion
Procedural programming is used to describe the way in which a computer writes a program. It
specifies chain of steps that implements a particular algorithm. In Procedural Programming,
programs are divided into small codes that are easier to understand and modify.

What is 'Object Oriented Programming'?


Definition: OOP is an object-oriented programming technique that combines data and instructions
for processing that data into an object that can be used within the program. Object-oriented
programming provides concepts that help modelling complicated systems of real world into
manageable software solutions.

Description: OOP concepts are:

1) Objects: Objects are structures that contain both data and procedures. For example, a student is
an object which has name and age,

2) Class: A class is a template that explains the details of an object,

3) Inheritance: Inheritance is a technique to re-use existing code again and again. Class that is
inherited is called base class and a class which it inherits is called derived class,

4) Polymorphism: Polymorphism means many, which is requesting the same operation to perform
differently,

5) Abstractions: It refers to displaying only essential features of the application and covering the
details,
6) Encapsulation: It means wrapping the data and functions together into a class.

Examples of object-oriented languages are Java, C++, PHP, C, Python etc.

Key features of object-oriented programming are:

· better programming designs

· emphasis on security and access

· reduction code duplication

· real world application is modelled well

Advantages of OOPs over procedure-oriented programming (POP): With the help of OOPs, it will be
easier for developing and maintaining the software compared to POP. It will be difficult for the
procedure-oriented programming language when the code grows along with the growth of the
project size. Data hiding is enabled in the OOPs whereas the global data could be accessed anywhere
using the procedure-oriented programming language. So this process is risky. Simulating the real
world event effectively is easier with OOPs. Thus, the real-word problem can be solved using this
method. The procedure-oriented programming language is less effective compared to OOPs.
Characteristics of an Object-Oriented Programming Language
Class
C++ Classes/Objects
C++ is an object-oriented programming language.
Everything in C++ is associated with classes and objects, along with its attributes and methods. For
example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.
Attributes and methods are basically variables and functions that belongs to the class. These are
often referred to as "class members".
A class is a user-defined data type that we can use in our program, and it works as an object
constructor, or a "blueprint" for creating objects.

Create a Class
To create a class, use the class keyword:
Example
Create a class called "MyClass":
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

Example explained
 The class keyword is used to create a class called MyClass.
 The public keyword is an access specifier, which specifies that members (attributes and
methods) of the class are accessible from outside the class. You will learn more about access
specifiers later.
 Inside the class, there is an integer variable myNum and a string variable myString. When
variables are declared within a class, they are called attributes.
 At last, end the class definition with a semicolon ;

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++ Object
In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
In other words, object is an entity that has state and behavior. Here, state means data and
behavior means functionality.
Object is a runtime entity, it is created at runtime.
Object is an instance of a class. All the members of the class can be accessed through object.

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.
To know more about C++ Objects and Classes, refer to this article – C++ Classes and Objects
Encapsulation
In normal terms, Encapsulation is defined as wrapping up data and member function in a single unit
called class. 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.
To know more about encapsulation, refer to this article – Encapsulation in C++
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 all
unnecessary 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.
To know more about C++ abstraction, refer to this article – Abstraction in C++

Polymorphism
C++ Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms. It is
a greek word. In object-oriented programming, we use 3 main concepts: inheritance,
encapsulation, and polymorphism.
Polymorphism in C++ is a key concept in object-oriented programming (OOP) that describes an
object's ability to have multiple forms or representations. It's a way to reuse and extend code by
allowing the same code to act differently depending on the context.
polymorphism refers to the ability of a C++ function or object to perform in different ways,
depending on how the function or object is used.

There are two types of polymorphism in C++:

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++
To know more about polymorphism, refer to this article – Polymorphism in C++
Inheritance
When properties and member functions of Base class are passed on to the derived class.
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 without virtual function
#include <iostream>
using namespace std;

class GFG {
public:
void call_Function() // function that calls print
{
print();
}
void print() // the display function
{
cout << "Printing the Base class Content" << endl;
}
};

class GFG2 : public GFG // GFG2 inherits publicly from GFG


{
public:
void print() // GFG2's display
{
cout << "Printing the Derived class Content" << endl;
}
};

int main()
{
GFG* geeksforgeeks = new GFG(); // Creating GFG's object using pointer
geeksforgeeks->call_Function(); // Calling call_Function

GFG* geeksforgeeks2 = new GFG2(); // creating GFG2 object using pointer


geeksforgeeks2->call_Function(); // calling call_Function for GFG2 object
delete geeksforgeeks;
delete geeksforgeeks2;
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.
Above Example with virtual Function:
C++
// C++ Program to Demonstrate the Concept of Dynamic binding
// with the help of virtual function

#include <iostream>
using namespace std;

class GFG
{
public:
// using "virtual" for the display function
virtual void print()
{
cout << "Printing the Base class Content" << endl;
}
// function that calls print
void call_Function()
{
print();
}
};
// GFG2 inherits publicly from GFG
class GFG2 : public GFG
{
public:
// GFG2's display
void print() override
{
cout << "Printing the Derived class Content" << endl;
}
};

int main()
{
// Creating GFG's object using pointer
GFG *geeksforgeeks = new GFG();
// Calling call_Function
geeksforgeeks->call_Function();

// creating GFG2 object using pointer


GFG *geeksforgeeks2 = new GFG2();
// calling call_Function for GFG2 object
geeksforgeeks2->call_Function();

delete geeksforgeeks;
delete geeksforgeeks2;

return 0;
}

Output
Printing the Base class Content
Printing the Derived class Content
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.
Example:
C++
#include <iostream>
using namespace std;
// Define a Car class with a method to display its speed
class Car {
public:
void displaySpeed(int speed) {
cout << "The car is moving at " << speed << " km/h." << endl;
}
};

int main() {
// Create a Car object named myCar
Car myCar;

// Send a message to myCar to execute the displaySpeed method


int currentSpeed = 100;
myCar.displaySpeed(currentSpeed);

return 0; }
Advantage of OOPs over Procedure-oriented programming language
Here are key advantages of Object-Oriented Programming (OOP) over Procedure-Oriented
Programming (POP):
1. Modularity and Reusability: OOP promotes modularity through classes and objects,
allowing for code reusability.
2. Data Encapsulation: OOP encapsulates data within objects, enhancing data security and
integrity.
3. Inheritance: OOP supports inheritance, reducing redundancy by reusing existing code.
4. Polymorphism: OOP allows polymorphism, enabling flexible and dynamic code through
method overriding.
5. Abstraction: OOP enables abstraction, hiding complex details and exposing only essential
features
Difference between OOP and POP:

OOP POP

Object oriented. Structure oriented.

Program is divided into objects. Program is divided into functions.

Bottom-up approach. Top-down approach.

Inheritance property is used. Inheritance is not allowed.

It uses access specifier. It doesn’t use access specifier.

Encapsulation is used to hide the data. No data hiding.

Concept of virtual function. No virtual function.

Object functions are linked through Parts of program are linked through
message passing. parameter passing.

Expanding new data and functions is


Adding new data and functions is easy
not easy.

The existing code can be reused. No code reusability.

use for solving big problems. Not suitable for solving big problems.

C++, Java. C, Pascal.


Below is a table of some of the more obvious and general differences between C and C++. There
are many more subtle differences between the languages and between versions of the languages.

C C++

C was developed by Dennis Ritchie between C++ was developed by Bjarne Stroustrup in
the year 1969 and 1973 at AT&T Bell Labs. 1979.

C does no support polymorphism,


C++ supports polymorphism, encapsulation,
encapsulation, and inheritance which means
and inheritance because it is an object oriented
that C does not support object oriented
programming language.
programming.

C is (mostly) a subset of C++. C++ is (mostly) a superset of C.

Number of keywords in C: Number of keywords in C++:


* C90: 32 * C++98: 63
* C99: 37 * C++11: 73
* C11: 44 * C++17: 73
* C23: 59 * C++20: 81

C++ is known as hybrid language because C++


For the development of code, C
supports both procedural and object oriented
supports procedural programming.
programming paradigms.

Data and functions are separated in C because Data and functions are encapsulated together
it is a procedural programming language. in form of an object in C++.

Data is hidden by the Encapsulation to ensure


C does not support information hiding. that data structures and operators are used as
intended.

Built-in & user-defined data types is supported


Built-in data types is supported in C.
in C++.

C is a function driven language because C is a C++ is an object driven language because it is


procedural programming language. an object oriented programming.
C C++

Function and operator overloading is not Function and operator overloading is


supported in C. supported by C++.

C is a function-driven language. C++ is an object-driven language

Functions in C are not defined inside


Functions can be used inside a structure in C++.
structures.

Namespace features are not present inside Namespace is used by C++, which avoid name
the C. collisions.

Standard IO header is stdio.h. Standard IO header is iostream.h.

Reference variables are not supported by C. Reference variables are supported by C++.

Virtual and friend functions are not supported Virtual and friend functions are supported by
by C. C++.

C does not support inheritance. C++ supports inheritance.

Instead of focusing on data, C focuses on C++ focuses on data instead of focusing on


method or process. method or procedure.

C provides malloc() and calloc() functions C++ provides new operator for memory
for dynamic memory allocation, and free() for allocation and delete operator for memory de-
memory de-allocation. allocation.

Direct support for exception handling is not


Exception handling is supported by C++.
supported by C.

scanf() and printf() functions are used for


cin and cout are used for input/output in C++.
input/output in C.
C C++

C structures don’t have access modifiers. C ++ structures have access modifiers.

Strict type checking in done in C++. So many


There is no strict type checking in C programs that run well in C compiler will result
programming language. in many warnings and errors under C++
compiler.

C does not support overloading C++ does support overloading

Type punning with unions is undefined


Type punning with unions is allows (C99 and
behavior (except in very specific
later)
circumstances)

Named initializers must match the data layout


Named initializers may appear out of order
of the struct

File extension is “.cpp” or “.c++” or “.cc” or


File extension is “.c”
“.cxx”

Meta-programming: templates (macros are still


Meta-programming: macros + _Generic()
supported but discouraged)

There are 32 keywords in the C There are 97 keywords in the C++


Difference Between Class And Object:
There are many differences between object and class. Some differences between object and class
are given below:

Class Object

Class is used as a template for declaring and


An object is an instance of a class.
creating the objects.

When a class is created, no memory is Objects are allocated memory space


allocated. whenever they are created.

An object is created many times as per


The class has to be declared first and only once.
requirement.

A class can not be manipulated as they are not


Objects can be manipulated.
available in the memory.

A class is a logical entity. An object is a physical entity.

It is created with a class name in C++ and


It is declared with the class keyword
with the new keywords in Java.

Class does not contain any values which Each object has its own values, which are
can be associated with the field. associated with it.

A class is used to bind data as well as methods


Objects are like a variable of the class.
together as a single unit.

Syntax: Instantiating an object for a Class in


C++ is as follows:
class Student {
Syntax: Declaring Class in C++ is as follows:
public:
class <classname> {};
void put(){
cout<<“Function Called”<<endl;
}
Class Object

}; // The class is declared here


int main(){
Student s1; // Object created
s1.put();
}

Example: Bike Example: Ducati, Suzuki, Kawasaki

Difference Between Structure and Class in C++

S. No. Class Structure

Members of a class are private by Members of a structure are public by


1 default. default.

It is declared using
It is declared using the struct keyword.
2 the class keyword.

It is normally used for data It is normally used for the grouping of


3 abstraction and inheritance. different datatypes.

Syntax: Syntax:
class class_name { struct structure_name {
data_member; structure_member1;
member_function; structure_member2;
4 }; };

A structure is a grouping of In C++, a class is defined as a collection


variables of various data types of related variables and functions
Definition referenced by the same name. contained within a single structure.

If no access specifier is specified, If no access specifier is defined, all


Basic all members are set to 'public'. members are set to 'private'.
S. No. Class Structure

struct structure_name{
type struct_member 1;
class class_name{
type struct_member 2;
data member;
type struct_member 3;
member function;
.
};
type struct_memberN;
Declaration };

Structure instance is called the


A class instance is called 'object'.
Instance 'structure variable'.

Inheritance It does not support inheritance. It supports inheritance.

Memory
Memory is allocated on the stack. Memory is allocated on the heap.
Allocated

Nature Value Type Reference Type

Data abstraction and further


Grouping of data
Purpose inheritance.

It is used for smaller amounts of


It is used for a huge amount of data.
Usage data.

Null values Not possible It may have null values.

Requires
It may have only parameterized It may have all the types of
constructor and
constructor. constructors and destructors.
destructor

You might also like