Unit 1 C++
Unit 1 C++
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)
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.
Another serious drawback with the procedural approach is that we do not model real world
problems very well
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:
The following table highlights the major differences between Procedural Programming and Object
Oriented Programming –
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.
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.
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
};
#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() {
return 0;
}
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.
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
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.
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
Fig. Polymorphism
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
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
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.
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.
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.
Tables 2.1 and 2.2 provide lists of c++ standard libraryheader files that may needed in c++ program.
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
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++.
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.
Output
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.
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
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.