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

Unit 1 C++

Uploaded by

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

Unit 1 C++

Uploaded by

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

Introduction to C++ Programming Unit 1

Unit 1
Introduction to Object Oriented Programming: Software Evolution, A Look at procedure-oriented
programming, Object-oriented programming paradigm, Basic Concepts of Object-oriented programming:
Objects, Classes, Data Abstraction and Encapsulation, Inheritance, Polymorphism, Dynamic Binding,
Message passing, Benefits of OOP, Application of OOP, C++ overview, A simple C++ Program, Structure
of C++ Program (Textbook 1)

Procedure Oriented Programming Language


 In the procedure oriented approach, the problem is viewed as sequence of things to be done
such as reading, calculation and printing.
 Procedure oriented programming basically consist of writing a list of instruction or
actions for the computer to follow and organizing these instruction into groups known
as functions.
 A typical structure for procedural programming is shown
 in fig. below

 The technique of hierarchical decomposition has been used to specify the tasks to be
completed for solving a problem.
 In a multi-function program, many important data items are placed as global so that they
may be accessed by all the functions. Each function may have its own local data.
 Global data are more vulnerable to an inadvertent change by a function.
 In a large program it is very difficult to identify what data is used by which function.
 In case we need to revise an external data structure, we also need to revise all functions
that access the data. This provides an opportunity for bugs to creep in.

Brunda G, Lecturer, Dept. of CSE, MSRIT


Introduction to C++ Programming Unit 1

 Another serious drawback with the procedural approach is that we do not model real world
problems very well

Relationship of data and the function In Procedural oriented

Some Characteristics exhibited by procedure-oriented programming are:

 Emphasis is on doing things (algorithms).


 Large programs are divided into smaller programs known as functions.
 Most of the functions share global data.
 Data move openly around the system from function to function.
 Functions transform data from one form to another.
 Employs top-down approach in program design.

Object Oriented Paradigm

 Object-oriented programming (OOP) is a programming paradigm that organizes


code around objects, which are instances of classes that encapsulate data and
behavior. It is a widely used programming approach that provides a way to structure
and design software systems by modeling real-world entities as objects.
 The major motivating factor in the invention of object-oriented approach is to remove some
of the flaws encountered in the procedural approach.
 OOP treats data as a critical element in the program development and does not allow it to
flow freely around the system.
 It ties data more closely to the function that operate on it, and protects it from accidental
modification from outside function.
 OOP allows decomposition of a problem into a number of entities called objects and then
builds data and function around these objects.

Brunda G, Lecturer, Dept. of CSE, MSRIT


Introduction to C++ Programming Unit 1

 The organization of data and function in object-oriented programs is shown in fig.

 The data of an object can be accessed only by the function associated with that object.
However, function of one object can access the function of other objects.
 Some of the features of object oriented programming are:

a) Emphasis is on data rather than procedure.


b) Programs are divided into what are known as objects.
c) Data structures are designed such that they characterize the objects.
d) Functions that operate on the data of an object are ties together in the data
structure.
e) Data is hidden and cannot be accessed by external function.
f) Objects may communicate with each other through function.
g) New data and functions can be easily added whenever necessary.
h) Follows bottom up approach in program design.

The following table highlights the major differences between Procedural Programming and Object
Oriented Programming –

Brunda G, Lecturer, Dept. of CSE, MSRIT


Introduction to C++ Programming Unit 1

Parameter Object Oriented Programming Procedural Programming

Definition Object-oriented Programming is a Procedural Programming is a programming


programming language that uses classes language that follows a step-by-step
and objects to create models based on approach to break down a task into a
the real world environment. collection of variables and routines (or
In OOPs, it makes it easy to maintain subroutines) through a sequence of
and modify existing code as new objects instructions.
are created inheriting characteristics Each step is carried out in order in a
from existing ones. systematic manner so that a computer can
understand what to do.

Approach In OOPs concept of objects and classes In procedural programming, the main
is introduced and hence the program is program is divided into small parts based on
divided into small chunks called objects the functions and is treated as separate
which are instances of classes. program for individual smaller program.

Access In OOPs access modifiers are introduced No such modifiers are introduced in
modifiers namely as Private, Public, and Protected. procedural programming.

Security Due to abstraction in OOPs data hiding Procedural programming is less secure as
is possible and hence it is more secure compare to OOPs.
than POP.

Complexity OOPs due to modularity in its programs There is no simple process to add data in
is less complex and hence new data procedural programming, at least not without
objects can be created easily from revising the whole program.
existing objects making object-oriented
programs easy to modify

Program OOP divides a program into small parts Procedural programming divides a program
division and these parts are referred to as objects. into small programs and each small program
is referred to as a function.

Importance OOP gives importance to data rather Procedural programming does not give
than functions or procedures. importance to data. In POP, functions along
with sequence of actions are followed.

Inheritance OOP provides inheritance in three Procedural programming does not provide
modes i.e. protected, private, and public any inheritance.

Examples C++, C#, Java, Python, etc. are the C, BASIC, COBOL, Pascal, etc. are the
examples of OOP languages. examples POP languages.

Brunda G, Lecturer, Dept. of CSE, MSRIT


Introduction to C++ Programming Unit 1

BASIC CONCEPTS OF OBJECTS ORIENTED PROGRAMMING


It is necessary to understand some of the concepts used extensively in object-oriented
programming. These include:
• Objects
• Classes
• Data abstraction and encapsulation
• Inheritance
• Polymorphism
• Dynamic binding
• Message passing

Objects
Definition
 In object-oriented programming (OOP), an object is an instance of a class. An object
represents a specific entity or instance in a program.
 It is a runtime entity that encapsulates both data (attributes) and behavior (methods)
associated with that particular entity.

 Objects are the basic run-time entities in an object-oriented system.


 They may represent a person, a place, a bank account, a table of data or any item that the
program must handle.
 The fundamental idea behind object oriented approach is to combine both data and function
 Into a single unit and these units are called objects.
 An object has a state, which is determined by its attributes or instance variables. These
attributes store the object's data and represent its characteristics or properties. For a car
object, attributes could include its color, make, model, and current speed.
 In addition to its state, an object can perform actions or behaviors. These behaviors are
defined by methods or member functions of the class. Methods are functions associated
with the object that allow it to perform specific operations or respond to messages. For
example, a car object could have methods such as "start," "accelerate," or "brake."
 Objects are created from a class blueprint using a process called instantiation. When you
create an object, you allocate memory for it and initialize its attributes. Each object has its
own unique set of attribute values but follows the structure and behavior defined by the
class.
 In OOP, objects are the building blocks of the system, and they interact with each other
through method calls and message passing.
 Objects can communicate, collaborate, and exchange data to fulfill specific tasks and
achieve the overall functionality of the program.
 The concept of objects in OOP enables the modeling of complex systems by breaking them
down into modular and manageable entities that have their own state and behavior. This

Brunda G, Lecturer, Dept. of CSE, MSRIT


Introduction to C++ Programming Unit 1

approach promotes code reuse, encapsulation, and abstraction, allowing for more efficient
and maintainable software development.

OBJECTS: STUDENT

DATA
Name
Date-of-birth
Marks

FUNCTIONS
Total
Average
Display
………

Classes
Definition
 In C++, a class is a user-defined type that serves as a blueprint for creating objects.
 It provides a way to define the structure and behavior of objects that belong to a
specific class.
 A class encapsulates data (member variables) and functions (member functions) that
operate on that data.

 Once a class has been defined, we can create any number of objects belonging to that class.
 Each object is associated with the data of type class with which they are created.
 A class is thus a collection of objects similar types.
 For examples, Mango, Apple and orange members of class fruit.

Create a Class
A class is defined in C++ using 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.

class className {
// some data
// some functions
};

Syntax to Define Object in C++


className objectVariableName;

Brunda G, Lecturer, Dept. of CSE, MSRIT


Introduction to C++ Programming Unit 1

Example 1: Object and Class in C++ Programming

#include <iostream>
using namespace std;

// create a class
class Room {

public:
double length;
double breadth;
double height;

double calculateArea() {
return length * breadth;
}

double calculateVolume() {
return length * breadth * height;
}
};

int main() {

// create object of Room class


Room room1;
// assign values to data members
room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;

// calculate and display the area and volume of the room


cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;

return 0;
}

 Here, we defined a class named Room.


 The variables length, breadth, and height declared inside the class are known as data
members. And, the functions calculateArea() and calculateVolume() are known as
member functions of a class.
 Room room1; Here Object room1 is created.
 The values of length, breadth, and height are assigned to room1 using dot notation.

Brunda G, Lecturer, Dept. of CSE, MSRIT


Introduction to C++ Programming Unit 1

 The calculateArea() and calculateVolume() member functions are called on room1 to


calculate the area and volume of the room, respectively.
 The calculated area and volume are displayed to the console using cout.

Data Abstraction and Encapsulation

 The wrapping up of data and function into a single unit (called class) is known as
encapsulation.
 The data is not accessible to the outside world, and only those functions which are wrapped
in the class can access it. These functions provide the interface between the object’s data
and the program. This insulation of the data from direct access by the program is called
data hiding or information hiding.
 In C++, data encapsulation is achieved using access specifiers. The access specifiers define
the visibility and accessibility of class members (variables and functions) to the outside
world. The three access specifiers in C++ are:

 Public: Public members are accessible from anywhere in the program. They can be
accessed by objects of the class and external code that uses the objects. Public
members represent the interface of the class, providing a way for external code to
interact with the class.

 Private: Private members are only accessible within the class itself. They cannot
be accessed directly by objects or external code. Private members are typically
accessed and manipulated through public member functions (methods). They
represent the internal implementation details and state of the class.

 Protected: Protected members are similar to private members, but they can be
accessed by derived classes (classes that inherit from the base class). Protected
members provide a way to share data and behaviors between the base class and its
derived classes.

 Abstraction refers to the act of representing essential features without including the
background details or explanation.
 Abstraction is the process of only showing the necessary details to the user and hiding
the other details in the background
 Classes use the concept of abstraction and are defined as a list of abstract attributes such as
size, wait, and cost, and function operate on these attributes. They encapsulate all the
essential properties of the object that are to be created.

Brunda G, Lecturer, Dept. of CSE, MSRIT


Introduction to C++ Programming Unit 1

INHERITANCE
Inheritance is the process by which objects of one class acquired the properties of objects
of another classes.
 This mean that we can add additional features to an existing class without modifying it.
 This is possible by designing a new class will have the combined features of both the
classes.
 It enables code reuse, promotes modularity, and establishes hierarchical relationships
between classes. Inheritance is a key feature of object-oriented programming, providing a
way to model real-world relationships and achieve polymorphism.

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.
For example, the bird, ‘robin’ is a part of class ‘flying bird’ which is again a part of the class ‘bird’.
The principal behind this sort of division is that each derived class shares common
Characteristics with the class from which it is derived as illustrated in fig

Syntax: Property Inheritance

Brunda G, Lecturer, Dept. of CSE, MSRIT


Introduction to C++ Programming Unit 1

class <derived_class_name> : <access-specifier> <base_class_name>


{
//body
}

Where
Class — keyword to create a new class
derived_class_name — name of the new class, which will inherit the base class
Access-specifier — either of private, public or protected. If neither is specified, PRIVATE is taken
as default
Base-class-name — name of the base class
Note: A derived class doesn’t inherit access to private data members. However, it does inherit a
full parent object, which contains any private members which that class declares.
Example Program for Inheritance

In the above example, Base is the class name and the parent class, which contains the property
named salary and the value 900.

Brunda G, Lecturer, Dept. of CSE, MSRIT


Introduction to C++ Programming Unit 1

In the same way, there is another class named Derived, which is the child class, which inherits the
property of the parent class and has its property named as a bonus which contains the value of 100.

In the child class, there is a function named sum(), which is used to add the salary and bonus. In
the main function, an object is created named “x” of the “Derived” class which is a child class, and
using that object, the properties, and the sum function are called from the derived class, whichwill
add the salary and bonus and gives it as output.

POLYMORPHISM

 Polymorphism is another important OOP concept.


 Polymorphism, a Greek term, means the ability to take more than on form. An operation
may exhibit different behavior is different instances. The behavior depends upon the types
of data used in the operation.
 For example, consider the operation of addition. For two numbers, the operation will
generate a sum. If the operands are strings, then the operation would produce a third string
by concatenation. The process of making an operator to exhibit different behaviors in
different instances is known as operator overloading.
 Fig illustrates that a single function name can be used to handle different number and
different types of argument. This is something similar to a particular word having several
different meanings depending upon the context. Using a single function name to perform
different type of task is known as function overloading.

Fig. Polymorphism

 Polymorphism plays an important role in allowing objects having different internal


structures to share the same external interface. This means that a general class of operations
may be accessed in the same manner even though specific action associated with each
operation may differ. Polymorphism is extensively used in implementing inheritance.

Brunda G, Lecturer, Dept. of CSE, MSRIT


Introduction to C++ Programming Unit 1

DYNAMIC BINDING

Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic binding means that the code associated with a given procedure call is not known until
the time of the call at run time. It is associated with polymorphism and inheritance. A function call
associated with a polymorphic reference depends on the dynamic type of that reference.

Dynamic binding in C++ is the mechanism by which the appropriate function implementation is
determined at runtime based on the actual object type. It is achieved through the use of virtual
functions and the concept of late binding.

Message Passing

An object-oriented program consists of a set of objects that communicate with each other. The
process of programming in an object-oriented language, involves the following basic steps:
1. Creating classes that define object and their behavior,
2. Creating objects from class definitions, and
3. Establishing communication among objects.

Objects communicate with one another by sending and receiving information much the same way
as people pass messages to one another. The concept of message passing makes it easier to talk
about building systems that directly model or simulate their real- world counterparts.

A Message for an object is a request for execution of a procedure, and therefore will invoke a
function (procedure) in the receiving object that generates the desired results. Message passing
involves specifying the name of object, the name of the function (message) and the information to
be sent. Example:

Object has a life cycle. They can be created and destroyed. Communication with an object is
feasible as long as it is alive

Brunda G, Lecturer, Dept. of CSE, MSRIT


Introduction to C++ Programming Unit 1

Benefits of OOP
Oop offers several benefits to both the program designer and the user. Object-oriented contributes
tothe solution of many problems associated with the development and quality of software products.
The principal advantages are :
1. Through inheritance we can eliminate redundant code and extend the use of existing
classes.
2. We can build programs from the standard working modules that communicate with one
another, rather than having to start writing the code from scratch. This leads to saving of
development time and higher productivity.
3. This principle of data hiding helps the programmer to build secure programs that can’t be
invaded by code in other parts of the program.
4. It is possible to have multiple instances of an object to co-exist with out any interference.
5. It is easy to partition the work in a project based on objects.
6. Object-oriented systems can be easily upgraded from small to large systems.
7. Message passing techniques for communication between objects makes the interface
description with external systems much simpler.
8. Software complexity can be easily managed.

APPLICATION OF OOP:
The most popular application of oops up to now, has been in the area of user interface
design such as windows. There are hundreds of windowing systems developed using oop
techniques.
Real business systems are often much more complex and contain many more objects
with complicated attributes and methods. Oop is useful in this type of applications because it
can simplify a complex problem. The promising areas for application of oop includes.
1. Real – Time systems.
2. Simulation and modeling
3. Object oriented databases.
4. Hypertext,hypermedia and expertext.
5. Al and expert systems.
6. Neural networks and parallel programming.
7. Dicision support and office automation systems.
8. CIM / CAM / CAD system.

Introduction of C++
C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell
Laboratories in Murray Hill, New Jersey, USA, in the early 1980’s. Stroustrup, an admirer of Simula67 and
a strong supporter of C, wanted to combine the best of both the languages and create a more powerful
language that could support object-oriented programming features and still retain the power and elegance of
C. The result was C++. Therefore, C++ is an extension of C with a major addition of the class construct
feature of Simula67. Since the class was a major addition to the original C language, Stroustrup initially
called the new language ‘C with classes’. However, later in 1983, the name was changed to C++. The idea
of C++ comes from the C increment operator ++, thereby suggesting that C++ is an augmented version of C.

C+ + is a superset of C. Almost all c programs are also C++ programs. However, there are a few minor
differences that will prevent a c program to run under C++ complier. We shall see these differences later as
Brunda G, Lecturer, Dept. of CSE, MSRIT
Introduction to C++ Programming Unit 1

and when they are encountered.

The most important facilities that C++ adds on to C care classes, inheritance, function overloading and
operator overloading. These features enable creating of abstract data types, inherit properties from existing
data types and support polymorphism, thereby making C++ a truly object-oriented language

Application of C++
C++ is a versatile language for handling very large programs; it is suitable for virtually any programming
task including development of editors, compilers, databases, communication systems and any complex real
life applications systems.
• Since C++ allow us to create hierarchy related objects, we can build special object-oriented libraries which
can be used later by many programmers.
• While C++ is able to map the real-world problem properly, the C part of C++ gives the language the ability
to get closed to the machine-level details.
• C++ programs are easily maintainable and expandable. When a new feature needs to be implemented, it is
very easy to add to the existing structure of an object.
• It is expected that C++ will replace C as a general-purpose language in the near future.

Simple C++ Program


Let us begin with a simple example of a C++ program that prints a string on the screen.

Program feature

Like C, the C++ program is a collection of function. The above example contain only one function main().
As usual execution begins at main(). Every C++ program must have a main(). C++ is a free form language.
With a few exception, the compiler ignore carriage return and white spaces. Like C, the C++ statements
terminate with semicolons.

Brunda G, Lecturer, Dept. of CSE, MSRIT


Introduction to C++ Programming Unit 1

Comments

C++ introduces a new comment symbol // (double slash). Comment start with a double slash symbol and
terminate at the end of the line. A comment may start anywhere in the line, and whatever follows till the end
of the line is ignored. Note that there is no closing symbol.

The double slash comment is basically a single line comment. Multiline comments can be written as follows:

// This is an example of
// C++ program to illustrate
// some of its features

The C comment symbols /*,*/ are still valid and are more suitable for multiline comments. The following
comment is allowed:

/*
This is an example of
C++ program to illustrate
some of its features
*/

Output operator
The statement
Cout<<”C++ is better than C.”;
Causes the string in quotation marks to be displayed on the screen. This statement introduces two new C++
features, cout and <<. The identifier cout(pronounced as C out) is a predefined object that represents the
standard output stream in C++. Here, the standard output stream represents the screen. It is also possible to
redirect the output to other output devices. The operator << is called the insertion or put to operator.

Brunda G, Lecturer, Dept. of CSE, MSRIT


Introduction to C++ Programming Unit 1

The iostream File

We have used the following #include directive in the program:


#include <iostream>
The #include directive instructs the compiler to include the contents of the file enclosed within angular
brackets into the source file. The header file iostream.h should be included at the beginning of all programs
that use input/output statements

Tables 2.1 and 2.2 provide lists of c++ standard libraryheader files that may needed in c++ program.

Brunda G, Lecturer, Dept. of CSE, MSRIT


Introduction to C++ Programming Unit 1

Namespace
Namespace is a new concept introduced by the ANSI C++ standards committee. This defines a scope for the
identifiers that are used in a program. For using the identifier defined in the namespace scope we must include
the using directive, like

Using namespace std;

Here, std is the namespace where ANSI C++ standard class libraries are defined. All ANSI C++ programs
must include this directive. This will bring all the identifiers defined in std to the current global scope. Using
and namespace are the new keyword of C++.

Return Type of main()

In C++, main () returns an integer value to the operating system. Therefore, every main () in C++ should end
with a return (0) statement; otherwise a warning an error might occur. Since main () returns an integer type
for main () is explicitly specified as int. Note that the default return type for all function in C++ is int.

Brunda G, Lecturer, Dept. of CSE, MSRIT


Introduction to C++ Programming Unit 1

An Example with Class


• One of the major features of C++ is classes. They provide a method of binding together data and functions
which operate on them. Like structures in C, classes are user-defined data types.

Output

Brunda G, Lecturer, Dept. of CSE, MSRIT


Introduction to C++ Programming Unit 1

The program define person as a new data of type class. The class person includes two basic data type items
and two function to operate on that data. These functions are called member function. The main program uses
person to declare variables of its type. As pointed out earlier, class variables are known as objects. Here, p is
an object of type person. Class object are used to invoke the function defined in that class.

Structure of C++ Program


As it can be seen from program above a typical C++ program would contain four sections as shown in the
below fig.. This section may be placed in separate code files and then compiled independently or jointly.

It is a common practice to organize a program into three separate files. The class declarations are placed in a
header file and the definitions of member functions go into another file. This approach enables the
programmer to separate the abstract specification of the interface from the implementation details (member
function definition).
Finally, the main program that uses the class is places in a third file which “includes: the previous two files
as well as any other file.

Include Files

Class declaration

Member functions definitions

Main function program


Fig. Structure of a C++ program

This approach is based on the concept of client-server model as shown in fig. 1.10. The class definition
including the member functions constitute the server that provides services to the main program known as
client. The client uses the server through the public interface of the class.

Brunda G, Lecturer, Dept. of CSE, MSRIT

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy