You are on page 1of 109

Raj Kumar Goel Institute of Technology, Ghaziabad

C++ Basics

Unit: IV
Object Oriented Programming
Ritu Agarwal
1
B Tech 6th Semester
Associate Professor
IT Department
Faculty Information
Faculty Information
2

• Name: Ms. Ritu Agarwal

• Qualification : M. Tech (CSE)

• Teaching Experience: 20 years

• Designation: Associate Professor

• Area of Interest: Deep Learning, Machine learning

• E-Mail: ritu7fit@rkgit.edu.in

Ms. Indira Adak Unit -2 03/05/2023


Subject Syllabus
3
Course Objective

4
At the end of the semester, the student will be able to:
 Understand the functionality and basic concepts of object oriented design
techniques.
 Understand and apply various object oriented features like inheritance, data
abstraction, encapsulation and polymorphism to solve various computing
problems.
 Appreciate the dynamic memory allocation functions, access specifiers and the
friend functions.
 Understanding the basics of C and C++.
 Implementing the subprogram call and return.
Course Outcome
5
 Understand the application development and analyze the insights of object
oriented programming to implement application
 Understand, analyze and apply the role of overall modeling concepts (i.e.
System, structural).
 Understand, analyze and apply oops concepts (i.e. abstraction, inheritance).
 Understand the basic concepts of C++ to implement the object oriented
concepts.
 To understand the object oriented approach to implement real world problem.
Program Outcome
6
1. Engineering knowledge: Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization for the solution of
complex engineering problems.
2. Problem analysis: Identify, formulate, research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified
needs with appropriate consideration for public health and safety, and cultural,
societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research based knowledge
and research methods including design of experiments, analysis and interpretation
of data, and synthesis of information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources,
and modern engineering and IT tools, including prediction and modeling to
complex engineering activities, with an understanding of the limitations.  
6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
7 to the professional engineering practice.
relevant
7. Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with the society at large, such as, being able to comprehend
and write effective reports and design documentation, make effective presentations, and
give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.
CO-PO Mapping

CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2

2 2 2 1 2 2 - - - - - 2 2 2
CO1
2 2 3 1 2 2 - - - - - 2 2 2
CO2
2 2 2 1 2 1 1 - - - - 2 2 2
CO3
2 2 2 1 2 - 1 - - - - 2 2 2
CO4
2 2 3 1 2 - - - - - - 2 2 2
CO5
2 2 2.4 1 2 1.6 1 - - - - 2 2 2
CO
End Semester Question Paper Template
9
Brief Introduction about the Subject with Videos

Videos: https://www.youtube.com/watch?v=LpU2h-4iEys
https://www.youtube.com/watch?v=hozM7JhFFXg

10
Prerequisites and Revision
11

In the Unit-1 students learnt the basic functionality and basic concepts of object
oriented design techniques and UML modelling.

In Unit-2, the students will understand the Structural model: a view of an system,
that emphasizes the structure of the objects, including their classifiers, relationships,
attributes and operations and the structural relationships.

In Unit-3, the students will understand dynamic memory allocation functions, access
specifiers and the friend functions, Understanding the basics of C and C++,
Implementing the subprogram call and return.
Overview of C language:

1.C language is known as structure oriented language or procedure oriented language


2.Employs top-down programming approach where a problem is viewed as a sequence of tasks to
be performed.
3.All program code of c can be executed in C++ but converse many not be possible
4. Function overloading and operator overloading are not possible.
5. Local variables can be declared only at the beginning of the block.
6. Program controls are through jumps and calls to subroutines.
7.Polymorphism, encapsulation and inheritance are not possible.
For solving the problems, the problem is divided into a number of modules. Each module is a subprogram.
8. Data abstraction property is not supported by procedure oriented language.
9. Data in procedure oriented language is open and can be accessed by any function.
Overview of C++ language:

1. C++ can be considered as an incremental version of c language which consists all programming language constructs with newly added features of
object oriented programming.
2. C++ is object oriented programming language.
3. The file extension of C++ program is “.CPP”
4. Function overloading and operator overloading are possible.
5. Variables can be declared in inline i.e. when required
6. In c++ more emphasis is give on data rather than procedures.
7. Polymorphism, encapsulation and inheritance are possible.
8. Data abstraction property is supported by c++.
9. Data access is limited. It can be accessed by providing various visibility modes both for data and member functions.
10.Dynamic binding is supported by C++
11.It supports all features of c language
12.It can be called as an incremental version of c language
Difference Between Procedure Oriented Programming
(POP) & Object Oriented Programming (OOP)
Difference Between Procedure Oriented Programming
(POP) & Object Oriented Programming (OOP)
BASIC STRUCTURE OF C++ LANGUAGE:

A C++ program should have one or more sections but the sequence of sections is to be
followed.
1. Documentation section
2. Linking section
3. Definition section
4. Global declaration section & class declarations
5. Member function definition
6. Main function
1. DOCUMENTATION
SECTION :

1. Document section comes first and is used to document the use of logic or reasons in
your program.
2. It can be used to write the program's objective, developer and logic details.
3. The documentation is done in C++ language with /* and */ . Whatever is written
between these two are called comments.
2. LINKING SECTION :

1. This section tells the compiler to link the certain occurrences of keywords or functions in your
program to the header files specified in this section.
2. e.g. #include<iostream>
using namespace std;
3. Directive causes the preprocessor to add the contents of the iostream file to the program. It
contains declarations for cout and cin.
4. cout is a predefined object that represents the standard output stream. The operator << is an
insertion operator, causes the string in double quotes to be displayed on the screen.
5. The identifier cin is a predefined object in C++ that corresponds to the standard input stream. The
operator >> is known as extraction operator. It extracts the value from the keyboard and assigns it
to the value variable on its right.
3. DEFINITION SECTION :

1. It is used to declare some constants and assign them some value. e.g. #define MAX 25

2. Here #define is a compiler directive which tells the compiler whenever MAX is found
in the program replace it with 25.
4. GLOBAL DECLARATION
SECTION :

1. Here the variables and class definitions which are used through out the program (including
main and other functions) are declared so as to make them global(i.e
accessible to all parts of program). 
2. A CLASS is a collection of data and functions that act or manipulate
the data. The data components of a class are called data members and function
components of a class are called member functions.
3.  A class can also termed as a blue print or prototype that defines the variable or functions
common to all objects of certain kind. 
4. It is a user defined data type.
5. e.g.   int i; //this declaration is done outside and before main()  
5. SUB PROGRAM OR
FUNCTION SECTION :

This has all the sub programs or the functions which


our program needs.
void display()
{
cout<<”C++ is better that C”;
}
6. MAIN FUNCTION SECTION :

 It tells the compiler where to start the execution.


 main() {
point from execution starts
}

 main function has two sections


1. declaration section : In this the variables and their data types are declared.
2. Executable section or instruction section : This has the part of program which
actually performs the task we need.
namespace:

1. Namespace is used to define a scope that could hold global identifiers.


2. ex:-namespace scope for c++ standard library.
3. A classes, functions and templates are declared within the namespace named
std, using namespace std;
4. user defined name space:
syntax for defining name space is:
namespace namespace_name
{
//declarations of variables. functions, classes etc...
}
namespace:

1. ex:
#include<iostream>
using namespace std;
namespace sample
{
int m;
void display(int n)
{
cout<<"in namespace N="<<n<<endl;
}
}
IDENTIFIERS:

1. Identifiers are the names given to various program elements such as variables, functions and arrays.
2. These are user defined names consisting of sequence of letters and digits.
3. Rules for declaring identifiers:
 The first character must be an alphabet or underscore.
 It must consist of only letters, digits and underscore.
 Identifiers may have any length but only first 31 characters are significant.
 It must not contain white space or blank space.
 We should not use keywords as identifiers.
 Upper and lower case letters are different.
IDENTIFIERS:

1. Examples of valid identifiers:


a, x, n, num, SUM, fact, grand_total, sum_of_digits, sum1
2. Examples of Invalid identifiers: $amount, ³num, grand-total, sum of digits, 4num.
$amount : Special character is not permitted
grand-total : hyphen is not permitted.
sum of digits : blank spaces between the words are not allowed.
4num : should not start with a number (first character must be a letter or underscore
Variables:

1. A named memory location is called variable.


2. It is an identifier used to store the value of particular data type in the memory.
3. Since variable name is identifier we use following rules which are same as of identifier
4. Rules for declaring Variables names:
 The first character must be an alphabet or underscore.
 It must consist of only letters, digits and underscore.
 Identifiers may have any length but only first 31 characters are significant.
 It must not contain white space or blank space.
 We should not use keywords as identifiers.
 Upper and lower case letters are different.
 Variable names must be unique in the given scope
Variable declaration:

1. The declaration of variable gives the name for memory location and its size.
2. It specifies the range of value that can be stored in that location.
3. Syntax:
Data_type variable_name;
4. Ex:
int a=10;
float x=2.3;
Constants:

1. Constants refer to fixed values that the program may not alter and they are called literals.
2. Constants can be of any of the basic data types and can be divided into Integer Numerals, Floating-
Point Numerals, Characters, Strings and Boolean Values.
3. Again, constants are treated just like regular variables except that their values cannot be modified
after their definition.
4. Integer Literals: An integer literal can be a decimal, octal, or hexadecimal constant. A prefix
specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
 85 // decimal
 0213 // octal
 0x4b // hexadecimal
Enum:

1. Enumerated type (enumeration) is a user-defined data type which can be assigned


some limited values.
2. These values are defined by the programmer at the time of declaring the enumerated
type.
3. For example: If a gender variable is created with value male or female. If any other
value is assigned other than male or female then it is not appropriate. In this situation,
one can declare the enumerated type in which only male and female values are assigned.
4. Syntax:
enum enumerated-type-name{value1, value2, value3…..valueN};
Enum:

1. // Defining enum Year


2. enum year { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec };
3. int main()
4. {
5. int i;
6. // Traversing the year enum
7. for (i = Jan; i <= Dec; i++)
8. cout << i << " ";
9. return 0;
10.}
11.Output:
12.0 1 2 3 4 5 6 7 8 9 10 11
operators:

1. An operator is a symbol that tells the compiler to perform specific mathematical or


logical manipulations.
2. C++ is rich in built-in operators and provide the following types of operators:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators
Arithmetic Operators:
The Relational Operators:
The Logical Operators:
The Bitwise Operators:
The Assignment Operators:
Misc Operators:

Sr. No Operator & Description

sizeof

1 sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is integer, and will return 4.

Condition ? X : Y

2 Conditional operator (?). If Condition is true then it returns value of X otherwise returns value of Y.

3 Comma operator causes a sequence of operations to be performed. The value of the entire comma expression is the value of the last expression of the comma-separated list.

. (dot) and -> (arrow)

4 Member operators are used to reference individual members of classes, structures, and unions.

Cast

5 Casting operators convert one data type to another. For example, int(2.2000) would return 2.

&

6 Pointer operator & returns the address of a variable. For example &a; will give actual address of the variable.

7 Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var.
Precedence of Operators :
typecasting:

1. A type cast is basically a conversion from one type to another.


2. There are two types of type conversion:
 Implicit Type Conversion
 Explicit Type Conversion
Implicit Type Conversion:

1. Also known as ‘automatic type conversion’.


2. Done by the compiler on its own, without any external trigger from the user.
3. Generally takes place when in an expression more than one data type is present. In
such condition type conversion (type promotion) takes place to avoid lose of data.
4. All the data types of the variables are upgraded to the data type of the variable with
largest data type.
5. bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long ->
float -> double -> long double
Implicit Type Conversion:

1. // An example of implicit conversion


2. int main()
3. {
4. int x = 10; // integer x
5. char y = 'a'; // character c Output:
6. // y implicitly converted to int. ASCII x = 107
7. // value of 'a' is 97 y=a

8. x = x + y; z = 108

9. // x is implicitly converted to float


10. float z = x + 1.0;
11. cout << "x = " << x << endl << "y = " << y << endl << "z = " << z << endl;
12. return 0;
13. }
Explicit Type Conversion:

1. This process is also called type casting and it is user-defined.


2. Here the user can typecast the result to make it of a particular data type.
3. In C++, it can be done by two ways:
 Converting by assignment: This is done by explicitly defining the required type in
front of the expression in parenthesis. This can be also considered as forceful casting.
 Syntax: (type) expression
 where type indicates the data type to which the final result is converted.
Explicit Type Conversion:

1. // explicit type casting


2. int main()
3. {
4. double x = 1.2;
5. // Explicit conversion from double to int
6. int sum = (int)x + 1;
7. cout << "Sum = " << sum;
8. return 0;
9. }
10. Output:
11. Sum = 2
Explicit Type Conversion:

1. Conversion using Cast operator: A Cast operator is an unary operator which forces one data type to be converted into another data
type.

2. int main()
3. { Click to add text

4. float f = 3.5;
5. // using cast operator
6. int b = static_cast<int>(f);
7. cout << b;
8. }
9. Output:
10. 3
Control Structures:

1. Control Structures are just a way to specify flow of control in programs.


2. Any algorithm or program can be more clear and understood if they use self-
contained modules called as logic or control structures.
3. It basically analyzes and chooses in which direction a program flows based on certain
parameters or conditions.
Control Structures:

Control
Statement

Selection Statement Iteration Statement Jump Statement

I If-else switch break continue return


f

while do for
Control Structures:

Nesting of If—else Statement


If(test expression)
If(test condition1)
{ {
Statement-block; if(test condition2)
} {
---------------------------------------------------------------- Statement-1;
If-else statement }

if(test expression) else

{ {
Statement-2;
True-Block Statement(s);
}
}
}
Else
else
{ {
False-Block statement(s); Statement-3;
} }
Control Structures:
Control Structures:

Switch(expression)
{
Case value-1:
block-1;
break;
Case value-2:
block-2;
break;
……
……
default:
default-block;
break;
}
Control Structures:

for (initialization; testExpression;


incremement)
   
int count;
for (count=0; count<100; count++)
{
    cout<<count;
}
Control Structures:

int count = 0; The do…while Statement


while (count < 5)
do
{
{
    cout<<count;
    statement;
    count++;
} while (booleanExpression);
}
Jumping from loops
Jumping from loops
Function in C++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
Function in c++
MACRO

It is also called preprocessors directive. The macros are defined by the #define keyword. Before the
program compilation, the preprocessor examines the program whenever the preprocessor detects the macros
then preprocessor replaces the macro by the macro definition.
Syntax of Macro:
#define MACRO_NAME Macro_definition
Example of Macro:

#include <iostream>
using namespace std;
  // macro with parameter
#define MAXIMUM(a, b) (a > b) ? a : b
  // Main function for the program Output:
int main()
{
Max (100, 1000):1000 Max (20, 0):20
    cout << "Max (100, 1000):";
    int k = MAXIMUM(100, 1000);
    cout << k << endl;
      cout << "Max (20, 0):";
    int k1 = MAXIMUM(20, 0);
    cout << k1;
      return 0;
}
Difference between inline FUNCTION AND MACRO

S.NO Inline Macro

1. An inline function is defined by the inline keyword. Whereas the macros are defined by the #define keyword.

2. Through inline function, the class’s data members can be accessed. Whereas macro can’t access the class’s data members.

Whereas in the case of macros, the program can’t be easily


3. In the case of inline function, the program can be easily debugged.
debugged.

Whereas in the case of macro, the arguments are evaluated every


4. In the case of inline, the arguments are evaluated only once.
time whenever macro is used in the program.

In C++, inline may be defined either inside the class or outside the Whereas the macro is all the time defined at the beginning of the
5.
class. program.
In C++, inside the class, the short length functions are automatically
6. While the macro is specifically defined.
made the inline functions.
7. Inline is not as widely used as macros. While the macro is widely used.

8. Inline is not used in competitive programming. While the macro is very much used in competitive programming.

While the macro is not terminated by any symbol, it is terminated


9. Inline function is terminated by the curly brace at the end.
by a new line.
Friend function

 A friend function of a class is defined outside that class' scope but it has the right to access
all private and protected members of the class. Even though the prototypes for friend
functions appear in the class definition, friends are not member functions.
 A friend can be a function, function template, or member function, or a class or class
template, in which case the entire class and all of its members are friends.
 To declare a function as a friend of a class, precede the function prototype in the class
definition with keyword friend.
 Characteristics of a Friend function:
• The function is not in the scope of the class to which it has been declared as a friend.
• It cannot be called using the object as it is not in the scope of that class.
• It can be invoked like a normal function without using the object.
• It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
Friend function

// Note: printWidth() is not a member function of any class.


#include <iostream>
using namespace std; void printWidth( Box box ) {
/* Because printWidth() is a friend of Box, it can
class Box { directly access any member of this class */
double width; cout << "Width of box : " << box.width <<endl;
}
// Main function for the program
public: int main() {
friend void printWidth( Box box ); Box box;
void setWidth( double wid ); // set box width without member function
box.setWidth(10.0);
}; // Use friend function to print the wdith.
// Member function definition printWidth( box );
void Box::setWidth( double wid ) { return 0;
}
width = wid;
}
virtual function

 A virtual function is a member function which is declared within a base class and is re-
defined(Overridden) by a derived class. When you refer to a derived class object using a
pointer or a reference to the base class, you can call a virtual function for that object and
execute the derived class’s version of the function. 
• Virtual functions ensure that the correct function is called for an object, regardless of the
type of reference (or pointer) used for function call.
• They are mainly used to achieve Runtime polymorphism
• Functions are declared with a virtual keyword in base class.
• The resolving of function call is done at Run-time
virtual
#include <iostream>
function
using namespace std;
 
class base {
public:
    void fun_1() { cout << "base-1\n"; } int main()
    virtual void fun_2() { cout << "base-2\ {
    base* p;
n"; }     derived obj1;
    virtual void fun_3() { cout << "base-3\     p = &obj1;
n"; }      // Early binding because fun1() is non-virtual in base
    p->fun_1();
    virtual void fun_4() { cout << "base-4\      // Late binding (RTP)
n"; }     p->fun_2();
};      // Late binding (RTP)
    p->fun_3();
       // Late binding (RTP)
class derived : public base {     p->fun_4();
public:   p->fun_4(5);
}
    void fun_1() { cout << "derived-1\n"; }
    void fun_2() { cout << "derived-2\n"; }
    void fun_4(int x) { cout << "derived-4\
n"; }
};
virtual function

Rules for Virtual Functions


1. Virtual functions cannot be static.
2. A virtual function can be a friend function of another class.
3. Virtual functions should be accessed using pointer or reference of base class type to achieve
run time polymorphism.
4. The prototype of virtual functions should be the same in the base as well as derived class.
5. They are always defined in the base class and overridden in a derived class. It is not
mandatory for the derived class to override (or re-define the virtual function), in that case,
the base class version of the function is used.
Weekly Assignments
105
Q1. Draw a object diagram for the following object classes with association name and
additional object classes if required
Object classes: file system, file, directory, file name, ASCII file, executable file,
directory file, disk, drive, track, sector.
Weekly Assignments
106
Q1. Draw a object diagram for the following object classes with association name and
additional object classes if required
Object classes: file system, file, directory, file name, ASCII file, executable file,
directory file, disk, drive, track, sector.
Expected Questions for Exam
107 Expected Questions for Exam
1. Define and differentiate between link and association
2. Describe the concept of Use cases, Use case Diagrams and Activity Diagrams in
Basic Structural Modeling.
3. Define UML. Draw a UML diagram for the automation of training and placement
office of any college. Make suitable assumptions if required
Video Links and Reference
108
• https://www.youtube.com/watch?v=-DP1i2ZU9gk
• https://nptel.ac.in/courses/106105224/
• https://nptel.ac.in/noc/courses/noc21/SEM2/noc21-cs57/
• James Rumbaugh et. al, “Object Oriented Modeling and Design”, PHI
• Grady Booch, James Rumbaugh, Ivar Jacobson, “The Unified Modeling
Language User Guide”, Pearson Education
• Object Oriented Programming With C++, E Balagurusamy, TMH
• C++ Programming, Black Book, Steven Holzner, dreamtech
• Object Oriented Programming in Turbo C++, Robert Lafore, Galgotia
• Object Oriented Programming with ANSI and Turbo C++, Ashok Kamthane,
Pearson
• The Compete Reference C++, Herbert Schlitz, TMH
109

Thank You.

You might also like