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

Sem-2 BCA-CPP notes

Uploaded by

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

Sem-2 BCA-CPP notes

Uploaded by

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

BCA

Teaching hours: 60 / 4hrs per week Course Code: BCA201


Course Title: Object-oriented Programming using CPP

UNIT I

Introduction to OOP: Procedure-oriented programming, object-oriented programming,


basic concepts of OOP, benefits and applications of OOP, simple C++ program,
namespace scope, and structure of C++ Program, creating, compiling and linking a file.

Tokens: Keywords, identifiers, constants, basic data types, user-defined data types,
storage classes, derived datatypes, dynamic initialization of variables, reference
variables, operators in C++, scope resolution operator, member dereferencing
operators, memory management operators.
Control Structures: if, if. Else, elseif ladder, nested if, switch, for, while, do-while,
break, continue, exit, go to.

UNIT II

Classes and Objects: Specifying a class, defining member functions, C++ program
with class, private member functions, arrays within class, memory allocation for
objects, static data members, static member functions, arrays of objects, returning
objects.

Functions in C++: Main function, function prototyping, call by reference, return by


reference, inline functions, default arguments. More about Functions: Function
overloading, friend function, function friendly to two classes, objects as function
arguments.

Constructors & Destructors: Constructors, parameterized constructors, multiple


constructors in a class, constructors with default arguments, copy constructors, dynamic
constructors, destructors.

UNIT III

Inheritance: Introduction to inheritance, single inheritance, multi-level inheritance,


multiple inheritance, hierarchical inheritance, hybrid inheritance.

Operator Overloading: Rules for overloading operators, overloading


unary operators, overloading binary operators.

Pointers: Introduction to pointers, declaring and initializing pointers,


arithmetic operations on pointers, pointers with arrays, arrays of pointers,
pointers to objects, 'this' pointer.

UNIT IV

Polymorphism and Virtual Functions: Compile-time polymorphism,


runtime polymorphism, virtual functions.

Templates: Introduction, function templates, class templates.

Exception Handling: Introduction, exception handling mechanism, throwing


mechanism, catching mechanism.

Suggested Reading:
1. E. Balagurusamy, Object Oriented Programming with C++, 6/e,
McGraw-Hill, 2013.
2. BehrouzA. Forouzan and Richard F.Gilberg, Computer Science: A
Structured Approach Using C++, 2/e, Cengage Learning, 2003.
3. Ashok N.Kamthane, Object Oriented Programming with ANSI and
Turbo C++, 1/e, Pearson Education, 2006.

Overview of C language:

1.C language is known as structure-oriented language/procedure-oriented language

2.It employs top-down programming approach where a problem is viewed as a sequence of tasks to

be performed.

3. Local variables can be declared only at the beginning of the block.

4. Program controls are through jumps and calls to subroutines.

5.All program code of c can be executed in C++ but converse many not be possible

6. Function overloading and operator overloading are not possible.

7.Polymorphism, encapsulation and inheritance are not possible in C.

8. For solving the problems, the problem is divided into a number of modules. Each module is a
subprogram.

9. Data abstraction property is not supported by procedure-oriented language.

10. 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 structure(procedure) oriented and 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. there by providing data security by data hiding

10.Dymanic 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)
Basic concepts of OOP

Object-oriented programming aims to implement real-world entities like inheritance, hiding,


polymorphism, etc in programming. The main aim of OOP is to bind together the data and the
functions that operate on them so that no other part of the code can access this data except that
function.

OOPs Concepts:

 Class

 Objects

 Data Abstraction

 Encapsulation

 Inheritance

 Polymorphism

 Dynamic Binding

 Message Passing

1. Class:

A class is a user-defined data type. It consists of data members and member functions, which can be
accessed and used by creating an instance of that class. It represents the set of properties or
methods that are common to all objects of one type. A class is like a blueprint for an object.

For Example: Consider the Class of Cars. There may be many cars with different names and brands
but all of them will share some common properties like all of them will have 4 wheels, Speed Limit,
Mileage range, etc. So here, Car is the class, and wheels, speed limits, mileage are their properties.

2. Object:

It is a basic unit of Object-Oriented Programming and represents the real-life entities. 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. An object has an identity, state, and behavior. 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 type of
response returned by the objects.

For example “Dog” is a real-life Object, which has some characteristics like color, Breed, Bark, Sleep,
and Eats.
3. Data Abstraction:

Data abstraction is one of the most essential and important features of object-oriented
programming. 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 accelerators will increase the speed of the
car or applying brakes will stop the car, but he does not know about how on pressing the accelerator
the speed is increasing, he does not know about the inner mechanism of the car or the
implementation of the accelerator, brakes, etc in the car. This is what abstraction is.

4. Encapsulation:

Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that
binds together code and the data it manipulates. In Encapsulation, the variables or data of a class are
hidden from any other class and can be accessed only through any member function of their class in
which they are declared. As in encapsulation, the data in a class is hidden from other classes, so it is
also known as data-hiding.

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

5. Inheritance:

Inheritance is an important pillar of OOP(Object-Oriented Programming). The capability of a class to


derive properties and characteristics from another class is called Inheritance. When we write a class,
we inherit properties from other classes. So when we create a class, we do not need to write all the
properties and functions again and again, as these can be inherited from another class that
possesses it. Inheritance allows the user to reuse the code whenever possible and reduce its
redundancy.

6. Polymorphism:

The word polymorphism means having many forms. In simple words, we can define polymorphism as
the ability of a message to be displayed in more than one form. For example, A person at the same
time can have different characteristics. Like a man at the same time is a father, a husband, an
employee. So the same person possess different behavior in different situations. This is called
polymorphism.
7. Dynamic Binding:

In dynamic binding, the code to be executed in response to the function call is decided at runtime.
Dynamic binding means that the code associated with a given procedure call is not known until the
time of the call at run time. Dynamic Method Binding One of the main advantages of inheritance is
that some derived class D has all the members of its base class B. Once D is not hiding any of the
public members of B, then an object of D can represent B in any context where a B could be used.
This feature is known as subtype polymorphism.

8. Message Passing:

It is a form of communication used in object-oriented programming as well as parallel programming.


Objects communicate with one another by sending and receiving information to each other. A
message for an object is a request for 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.

Benefits and applications of OOP

Reusability: In OOP‟ s programs functions and modules that are written by a user can be reused by

other users without any modification.

Inheritance: Through this we can eliminate redundant code and extend the use of existing classes.

Data Hiding: The programmer can hide the data and functions in a class from other classes. It helps
the programmer to build the secure programs.
Reduced complexity of a problem: The given problem can be viewed as a collection of different
objects. Each object is responsible for a specific task. The problem is solved by interfacing the
objects. This technique reduces the complexity of the program design.

Easy to Maintain and Upgrade: OOP makes it easy to maintain and modify existing code as new
objects can be created with small differences to existing ones. Software complexity can be easily
managed.

Message Passing: The technique of message communication between objects makes the interface

with external systems easier.

Modifiability: it is easy to make minor changes in the data representation or the procedures in an

OO program. Changes inside a class do not affect any other part of a program, since the only

public interface that the external world has to a class is through the use of methods.

Applications of C++

1. Software Development:

OOPs, are widely used in software development because it allows developers to design modular and
reusable code. It improves code organization by encapsulating data and methods within objects,
making complex software systems easier to manage and maintain. Furthermore, OOPs promotes
code reuse through concepts such as inheritance and composition, allowing developers to build on
existing codebases and eliminate repetition.

2. Development of Graphical User Interfaces (GUIs):

OOPs lends itself well to GUI development, giving a natural approach to model and representing
graphical elements. Developers may construct engaging and intuitive user interfaces using classes
and objects. OOPs, and frameworks such as Java's Swing and C#'s Windows Presentation Foundation
(WPF) provide rich libraries and tools to help developers create visually beautiful and user-friendly
programs.

3. Game Development:

OOPs are commonly used in game development due to their ability to express game things as
objects. Complex interactions between people, objects, and settings are common in games.
Developers can use OOPs to describe these entities as objects and define their behaviors and
characteristics. OOPs ideas are used by game engines such as Unity and Unreal Engine, allowing
developers to build immersive and engaging gaming experiences.

4. Database Management Systems:

Encapsulation and abstraction are OOPs ideas used in database management systems (DBMS). OOPs
languages like Python and Java have libraries like JDBC and SQLAlchemy that ease database
interaction. Database activities can be encapsulated within objects, enhancing code organization and
maintainability. OOPs also enables the building of data models, which makes mapping database
tables easier.
5. Mobile App Development:

OOPs are widely utilized in mobile app development, powering popular platforms such as Android
and iOS. Languages that adhere to OOPs concepts, like Java and Swift, enable developers to create
robust and scalable mobile applications. OOPs allows for code reuse, making designing programs for
multiple platforms easier while sharing similar code logic.

BASIC STRUCTURE OF C++ LANGUAGE:

The program written in C++ language follows this basic structure. The sequence of sections should be
as they are in the basic structure. 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

section main()

Declaration section

Executable section

1. DOCUMENTATION SECTION : comes first and is used to document the use of logic or

reasons in your program. It can be used to write the program's objective, developer and logic details.
The documentation is done in C language with /* and */ . Whatever is written between these two
are called comments.

2. LINKING SECTION : 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.

e.g. #include<iostream>

using namespace std;

directive causes the preprocessor to add the contents of the iostream file to the program. It contains
declarations

for cout and cin.

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.
The statement cin>>n; is an input statement and causes the program to wait for the user to type in a

number. The number keyed is placed on the variable “n”. 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 : It is used to declare some constants and assign them some

value. e.g. #define MAX 25

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 : 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). 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

A class ca also termed as a blue print or prototype that defines the variable or functions common to

all objects of certain kind. It is a user defined data type

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

SIMPLE „C++‟ PROGRAM:

#include<iostream>

using namespace std;

void display()

cout<<”C++ is better that C”;

int main()

display()

return 0;

6. MAIN FUNCTION SECTION : It tells the compiler where to start the execution

from 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:

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

ex:-namespace scope for c++ standard library.


A classes ,functions and templates are declared within the namespace named

std using namespace std;-->directive can be used.

user defined name space:

syntax for defining name space is

namespace namespace_name

//declarations of variables.functions,classes etc...

ex:

#include<iostream>

using namespace std;

namespace sample

{`

int m;

void display(int n)

cout<<"in namespace N="<<n<<endl;

using namespace sample;

int main()

int a=5;

m=100;

display(200);

cout<<"M in sample name space:"<<sample::m;

return 0;}

#include<iostream>

This directive causes the preprocessor to add content of iostream file to the program.

some old versions of C++ used iostream.h .if complier does not support ANSI

(american nation standard institute) C++ then use header file iostream.h
simple C++ program

// C++ program to display "Hello World"

// Header file for input output functions

#include <iostream>

using namespace std;

// Main() function: where the execution of program begins

int main()

// Prints hello world

cout << "Hello World";

return 0;

Tokens

C++ Keywords

C++ is a powerful language. In C++, we can write structured programs and object-oriented
programs also. C++ is a superset of C and therefore most constructs of C are legal in C++ with their
meaning unchanged. However, there are some exceptions and additions.

Token

When the compiler is processing the source code of a C++ program, each group of characters
separated by white space is called a token. Tokens are the smallest individual units in a program. A
C++ program is written using tokens. It has the following tokens:

 Keywords

 Identifiers

 Constants

 Strings

 Operators
Keywords

Keywords(also known as reserved words) have special meanings to the C++ compiler and are
always written or typed in short(lower) cases. Keywords are words that the language uses for a
special purpose, such as void, int, public, etc. It can’t be used for a variable name or function name
or any other identifiers. The total count of reserved keywords is 95. Below is the table for some
commonly used C++ keywords.

C++ Keyword

asm double new switch

auto else operator template

break enum private this

protecte
case extern throw
d

catch float public try

char for register typedef

class friend return union

const goto short unsigned


C++ Keyword

continu
if signed virtual
e

default inline sizeof void

delete int static volatile

do long struct while

What is the identifier?

Identifiers refer to the name of variables, functions, arrays, classes, etc. created by the programmer.
They are the fundamental requirement of any language.

Rules for naming identifiers:

 Identifier names can not start with a digit or any special character.

 A keyword cannot be used as an identifier name.

 Only alphabetic characters, digits, and underscores are permitted.

 The upper case and lower case letters are distinct. i.e., A and a are different in C++.

 The valid identifiers are GFG, gfg, and geeks_for_geeks.

Examples of good and bad identifiers

Invalid Identifier Bad Identifier Good Identifier

Cash prize C_prize cashprize

catch catch_1 catch1


Invalid Identifier Bad Identifier Good Identifier

1list list_1 list1

// C++ program to illustrate the use of identifiers

#include <iostream>

using namespace std;

int main()

// Use of Underscore (_) symbol

// in variable declaration

int geeks_for_geeks = 1;

cout << "Identifier result is: "

<< geeks_for_geeks;

return 0;

Output:

Identifier result is: 1

C++ Variables

Variables in C++ is a name given to a memory location. It is the basic unit of storage in a program.

 The value stored in a variable can be changed during program execution.

 A variable is only a name given to a memory location, all the operations done on the variable
effects that memory location.

 In C++, all the variables must be declared before use.

How to Declare Variables?


A typical variable declaration is of the form:
// Declaring a single variable
type variable_name;

// Declaring multiple variables:


type variable1_name, variable2_name, variable3_name;
A variable name can consist of alphabets (both upper and lower
case), numbers, and the underscore ‘_’ character. However, the
name must not start with a number.

In the above diagram,


datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.

// Declaring float variable


float simpleInterest;

// Declaring integer variable


int time, speed;

// Declaring character variable


char var;

We can also provide values while declaring the variables


as given below:

int a=50,b=100; //declaring 2 variable of integer type


float f=50.8; //declaring 1 variable of float type
char c='Z'; //declaring 1 variable of char type

Rules For Declaring Variable

 The name of the variable contains letters, digits, and


underscores.
 The name of the variable is case sensitive (ex Arr and arr
both are different variables).

 The name of the variable does not contain any whitespace


and special characters (ex #,$,%,*, etc).

 All the variable names must begin with a letter of the


alphabet or an underscore(_).

 We cannot used C++ keyword(ex float,double,class)as a


variable name.
 Valid variable names:
 int x; //can be letters
int _yz; //can be underscores
int z40;//can be letters
 Invalid variable names:
 int 89; Should not be a number
int a b; //Should not contain any whitespace
int double;// C++ keyword CAN NOT BE USED

Difference Between Variable Declaration and Definition

The variable declaration refers to the part where a variable is


first declared or introduced before its first use. A variable
definition is a part where the variable is assigned a memory
location and a value.

// C++ program to show difference between

// definition and declaration of a

// variable

#include <iostream>

using namespace std;

int main()

// this is declaration of variable a

int a;
// this is initialisation of a

a = 10;

// this is definition = declaration + initialisation


int b = 20;

// Let us print a variable


cout <<a<<b<< endl;

return 0;
}

C++ Data Types

A data type specifies the type of data that a variable can store such as integer, floating, character etc.
C++ supports a wide variety of data types and the programmer can select the data type appropriate
to the needs of the application. Data types specify the size and types of values to be stored.
However, storage representation and machine instructions to manipulate each data type differ from
machine to machine, although C++ instructions are identical on all machines.

There are 4 types of data types in C++ language.

Types Data Types

Basic Data Type int, char, float, double, etc


Derived Data Type array, pointer, etc

Enumeration Data Type enum

User Defined Data Type structure

You might also like