Sei sulla pagina 1di 22

1

Object Oriented Programming Using CPP

Object Oriented Programming Using CPP


Notes By

Kunal S Kasar
BBA(CA)
2
Object Oriented Programming Using CPP

28 November 2017

1. Introduction to CPP
Introduction to CPP :-
CPP is object oriented programming language, which is super set of C language. That
is all features of c language are available in CPP. As we know that C language is procedure oriented
programming language, Which supports the modular programming concepts.
CPP is object oriented language because it supports following 7 concepts of object
oriented programming :-
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Data abstraction and Encapsulation
6. Dynamic Binding
7. Message passing

History :-
CPP is developed by Bjarne Strotop. The thought of strotop to combine a powerful
language that is C language and a powerful programming technique OOP is to be combine
and produce new language. The initial name of that language was ‘C with classes’ but latter
on that name was change as ‘CPP’ or ‘C plus plus’ or ‘C++’.
29 November 2017

Basic Concepts of Object Oriented Programming :-


1. Object :-
Object is a real world entity, Which is represent a person, a thing, a document, a place,
organization, bank account, table of data, etc. In object oriented programming we can creates a various
objects. Data related to Object is called properties of object and various operations performed on data are
called methods or member functions.

Following diagrams shows student is object with various properties and functions :-

Student
Roll no
Name
Age

Student
Roll no
Name
Age
Insert();
Display();
3
Object Oriented Programming Using CPP

UML : Unified modified language

2. Class :-
Class represent the group of same type of objects or we can say object having same properties.
In our daily life we can say animal is a class having various objects such as Tiger, Cat, Dog etc. In object
oriented programming we can create a class with suitable name. Class contains different types of variables
and set of functions to process those variables. This variables belonging to class are called properties or
fields or data members and function belonging to class are called member function or methods.
We can use class name as new data type and variables created using class type are called object.
Following Figure shows Student Class :
Here ‘-’ indicates private variables or functions.
‘+’ indicates public variables or functions.

Student
- Roll no
- Name
- Age
+ Insert();
+ Display();

Student
- Roll no
- Name
- Age

3. Inheritance :-
Inheritance is a mechanism of acquiring properties of one class by the object of another
class. We can reuse existing classes for constructing new classes without disturbing them. It saves time and
cost of development.
There are various forms of inheritance :-
1) Single Inheritance
2) Multilevel Inheritance
3) Hierarchical Inheritance
4) Multiple Inheritance
By using this forms we can implement inheritance in our programs.

10 April 2018
4. Data abstraction and Encapsulation :-
4
Object Oriented Programming Using CPP

Classes are used to construct user defined data types. Those data types created using class
are called abstract data type. In which data abstraction concepts is implemented. Abstract data types hides
implementation details from their users.
Wrapping up data and functions together into a single unit is known as Encapsulation. With help of class
we can implement encapsulation in object oriented programs.

5. Polymorphism :-
Polymorphism is useful concept of object oriented programming. Polymorphism is a greek
work, In simple term it means one name many forms. It provides a common interface to carry out similar
task. In object oriented programming we can used polymorphism using function overloading and operator
overloading that is we can define more than one functions having same name but different task will be
performed. We can also used operator overloading for implementing polymorphism.

6. Dynamic Binding :-
Binding is nothing but linking of functions. Such binding will be performed at compile time is called Static
Binding, It also called as Early Binding. A binding which performed at run time is called Dynamic Binding,
It also called as Late binding.
7. Message Passing :-
Object oriented programming consist of set of objects, This object Communicates with each
other. The process of programming in object oriented programming language there for involve following 3
basic steps :-
i. Create class which defines object and their behavior.
ii. Create Object from class definition.
iii. Establish communication between object by calling their member function.
Message for object is request for execution of function which receives message as parameter,
processes it and return a value as a response.
5
Object Oriented Programming Using CPP

1 December 2017

2. Tokens, Expression and Control


Tokens in CPP :-
Token is a smallest unit of program. Set of tokens are called statement. Set of Statement is called program.
In cpp there are 5 types of takes such as
i. Identifier
ii. Keyword
iii. Literals
iv. Operator
v. Other Symbols

i. Identifier :-
Identifier is user defined name given to variable, array, function, structure, class etc.
There are certain rules of identifier such as
a. Uppercase and Lowercase alphabets are distinct.
b. Identifier can be of any length
c. It contain only alphabets, digits and underscore even other character not allow including space.
d. It should not begging with digit.
e. It should not contains keyword.

ii. Keyword :-
Keyword are reserve words. They are used for specific purpose in CPP and Compile can interpreter
this words all keywords of C are available in CPP and some new keywords are called in it as given below.
a. Keywords common in C and CPP :-
auto do goto sign unsign
break double if sizeof void
case else int struct volatile
char enume long static wide
cons extern register switch
continue float return typedef
default for short union

b. Keyword specific to CPP :-


asm inline public typeid
bitand new template typename
bitor namespace this using
catch operator throw virtual
class private true wchar_t
delete protected try

iii. Literals :-
Literals are the constants whose values are not change during execution of the program. There are
5 types of literals in CPP as follows :-
a. Integer literals
b. Floating point literals
c. Character literals
d. String literals
e. Enumeration literals

2 December 2017
6
Object Oriented Programming Using CPP

iv. Operators :-
Operator is a symbol which performs specific task on operands.
A. According to the number of operators use operator, operator are classified into 3 types :
I. Unary Operators :- It performs operations on only One operant.
II. Binary Operator :- It performs operations on Two operant.
III. Ternary Operator :- It performs operations on Tree operant.

B. Types of operators according to functionality :-


1. Arithmetic Operator
2. Relational Operator
3. Logical Operator
4. Assignment Operator
5. Conditional Operator
6. Increment / Decrement Operator
7. Bitwise Operator
8. Special Operator
● Precedence of Operator :-
Precedence of operator is nothing but order of execution operator in an expression,
If expression contains one or more than operators.

● Associativity of operators :-
If expression contains more than one operant having same precedence then order of execution
will be depends on associativity of operators. That is either left to right or right to left.

● Operators specific to CPP :-


Following Operators are not available in C, That is these operators are newly added in CPP.

i. Scope Resolution Operators :-


This operators is added in CPP. It is useful to perform various tasks in CPP, It denoted by
:: (double colon).
Example it is useful to access global variable inside the program, if same variable name is given to local
and global variable.
int a = 20;
main()
{
int a = 10;
cout<<a;
cout<<::a;
}
Output :-
10 20

ii. endl newline operator :-


endl operator is used to move cursor to next line. It is similar to “\n” in C.
cout<< “Hello”<<endl;
cout<< “Friends”<<endl;
output :-
Hello
Friends
7
Object Oriented Programming Using CPP

iii) setw() :-
It is used to set field width of variable to be display.
int a = 10;
cout<<setw(5)<<a;

iv. new :- memory allocation operator similar to malloc function in C.


v. delete :- memory release function similar to free function in C.
vi. pointer to member declaration ( *:: ) :- It is used to declare pointer for specific class member.
vii. pointer to member operator ( .:: and ->:: ) :- It is used to access class member through
pointer.

Input / Output Operations :-


In CPP we can used the concept of stream for input and output. There are various stream
classes given in CPP for input/output purpose.
Following are the predefine object of stream :
i. cout :- It is output stream used to display given value on the screen.
Eg. cout<<value;
ii. cin :- It is output stream object used to read given value by user and stored it into variable.
Eg. cin>>a; or cin>>a>>b;

9:30 4 December 2017


#include<iostream>
#include<conio.h>
using namespace std;
Main()
{
int a,b;
cout<<”Enter two values”;
cin>>a>>b;
int c=a+b;
cout<<”Addition is “<<c;
getch();
return 0;
}

Program for meter to centimeter conversion.


#include<iostream>
#include<conio.h>
using namespace std;
main()
{
int m;
cout<<”Enter value in meter “;
cin>>m;
int cm=a*100;
cout<<”Value in Centimeter is = “<<cm;
getch();
}
Assignment 3 progrmas …………

5 December 2017
8
Object Oriented Programming Using CPP

Control Structure in CPP :-


There are various control structures we can use in CPP such as if, switch,
conditional operator.
i. if :-
It is conditional control structures which executes given statement block as per the condition. There
are 4 different formats of if statement we can use such as :-
a. simple if:-
In this format one statement blog is given and that statement block will be executes only when given
condition is true.
if ( condition )
{
Statements;
}

b. if else format :-
In this format two statement blog are given and only one from them will be execution depends on
condition, That is if condition is true then statement block before else will be executes otherwise
statement block after else will be executes.
if ( condition )
{
Statement;
}
Else
{
Statement;
}
c. nested if format :-
In this format one if statement contains into another if statement.From them will be executes
depends on condition, that is if condition is true then statement block before also in another if will
be executes otherwise statement block after else will be executes.
if ( condition )
{
if ( condition )
{
statements;
}
}
else
{
statements;
}

d. if else ladder :-
In this format various statement blocks are given only one from them will be executes.

if ( condition )
{
statements;
}
else if ( condition )
{
statements;
9
Object Oriented Programming Using CPP

}
else if ( condition )
{
statements;
}

28 November
2017
Switch Statement :-
Program for number digit to word conversion.
#include<iostream>
#include<conio.h>
using namespace std;
main()
{
int a;
cout<<”Enter single digit number”<<endl;
cin>>a;
switch(a)
{
case 0 : cout<<”Zero”<<endl;
case 1 : cout<<”One”<<endl;
case 2 : cout<<”Two”<<endl;
case 3 : cout<<”Three”<<endl;
case 1 : cout<<”Four”<<endl;
case 5 : cout<<”Five”<<endl;
case 6 : cout<<”Six”<<endl;
case 7 : cout<<”Seven”<<endl;
case 8 : cout<<”Eight”<<endl;
case 9 : cout<<”Nine”<<endl;
default : cout<<”Wrong number”;
}
}

Program for given number is even or odd using switch


#include<iostream>
#include<conio.h>
using namespace std;
main()
{
int n;
cout<<”Enter number ”<<endl;
cin>>n;
switch(n%2)
{
case 0 : cout<<n<<”Odd number ”<<endl;
case 1 : cout<<n<<”Even number ”<<endl;
}
getch();
}

7 December 2017
10
Object Oriented Programming Using CPP

Conditional Operators :-
It is ternary operator which checks a given condition and evaluates one of the given expression.
Syntax :- condition?expr1:expr2;
If the condition is true then expr1 will be evaluate otherwise expr2 will be executes.
Eg. Program for find out largest from 2 numbers :-
#include<iostream>
#include<conio.h>
using namespace std;
main()
{
int a,b,c;
cout<<”Enter two values ”;
cin>>a>>b;
c=a<b?a:b;
cout <<”Larger number is ”<<c;
getch();
}

Program for quantity and rate of product calculate amount and discount. If amount is less
than 1000 then the discount is 10% otherwise 20%.
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int q,r,d;
cout<<"Enter rate of product : ";
cin>>r;
cout<<"Enter amount of quentity : ";
cin>>q;
int t=q*r;
cout<<"\n---------------"<<endl;
cout<<"Rate : "<<r<<endl;
cout<<"Quentity : "<<q<<endl;
cout<<"Total ammount : "<<t<<endl;
d=t<=1000?t*0.10:t*0.20;
cout<<"Discount : "<<d<<endl;
int p=t-d;
cout<<"----------------"<<endl;
cout<<"Payable ammount : "<<p;
getch();
}
Loop structures :-
Loop is nothing but repetition of execution of given statement. In CPP programs we can use 2
types of loops such as while and do while.
1. While :-
It is entry control loop which executes given statement repeatedly till condition is true.
Syntax :-
while( condition )
{
Statements;
11
Object Oriented Programming Using CPP

}
2. Do while :-
It is exit controlled loop, once either condition is true or falls and repeat the execution till
condition is true.
Syntax :-
do
{
Statements;
} while( condition );
Difference between while and do while :-
While Do while
1. It is entry controlled looped structure. 1. It is exit controlled looped structure.
2. Condition is given before statement 2. Condition is given after statement block
block
3. Statement block will be executes only 3. Statement block will be executes at least
when condition is true. one time either condition is true or falls.
4. Do keyword is not used. 4. Loop begging with Do keyword.
5. Condition is not terminated by 5. Condition should be terminated by
semicolon. semicolon.

8 December 2017
Struture in cpp:- As we know that structure can create new data type in 'c' as well as in cpp
with measure differencers as follows.
In C structure contains only variables as their member but in CPP structure contains variables as
well as function.
In C program while creating variables of structure type we should used struct keyword but in CPP
We does not used structure name as data type.
In C programs we can access all the members of structure outside the structure body but in CPP we
can hide structure members to access the outside the structure using public and private keywords.
Program for addition of two numbers using structure as follows :-
#include <iostream>
#include <conio.h>
using namespace std;
struct add
{
private :
int a,b,c;
public :
void input()
{
cout<<"Enter two values : ";
cin>>a>>b;
}

void display()
{
c=a+b;
cout<<"Addition is : "<<c;
}

int main()
{
Add s;
12
Object Oriented Programming Using CPP

s.input();
s.display();
getch();
return 0;
}

* CPP program for area of circle using structure as follows :-


#include<iostream.h>
#include<conio.h>
structure area
{
int r,a;
public:
void input()
{
cout<<”Enter radius : “;
cin>>r;
}
void display()
{
a=22/7*r*r;
cout<<”Area of circle having radius “<<r<<” is “<<a;
}
};
int main()
{
area o;
o.input();
o.display();
getch();
return 0;
}

CPP program for find a lagest number from 2 numbers using structure :-
#include<iostream.h>
#include<conio.h>
structure large
{
int a,b;
public:
void input()
{
cout<<”Enter any two numbers : “;
cin>>a>>b;
}

void display()
{
if(a>b)
cout<<”Large = “<<a;
else
13
Object Oriented Programming Using CPP

cout<<”Large = “<<b;
}
};

int main()
{
large o;
o.input();
o.display();
getch();
return 0;
}

Write a program for reverse given number using structure where structure contains some
function as pulbic and some function as private.
#include<iostream.h>
#include<conio.h>
structure rev
{
int a,b,c;
void input()
{
cout<<”Enter any number : “;
cin>>a;
}
public:
void display();
};
void rev::display()
{
input();
b=0;
while(a>0)
{
c=a%10+c;
b=b*10+c;
a=a/10;
}
cout<<”Reverse is “<<b;
}

int main()
{
rev r;
r.display();
getch();
return 0;
}
14
Object Oriented Programming Using CPP

CPP program for accept rate of plot and find the amount of it.
#include<iostream.h>
#include<conio.h>
structure plot
{
private:
int r,w,r,a;
void input()
{
cout<<”Enter Length and Width : “;
cin>>l>>w;
cout<<”Enter Rate : “;
cin>>r;
}
void display()
{
a=l*w*r;
cout<<”Area is “<<a;
}
};
int main()
{
plot p;
p.call();
geych()
return 0;
}

enumerator in CPP :-
enum are symbolic constants we can create using enum keyword as follow.

1. enum colour (Red, Blue, Green, Orange)


Here Red, Green etc are symbolic constant having default values such as Red = 0, Green = 1 as on.
2. We can change default of enumerator.
enum color{ Red=4, Green, Blue=8, Orange}
3. We can create enumerator without tag name which is know as Anonymous enumerator.
enum { red, green, blue, orange }
4. Tag name of enum can be use as data type and we can define variable of that type and contains value
defined as enumerator.

colour c;
c=Red;
c=Green;

5. Casting should be done while assign enum to integer variable


int a;
a=(int)Red;

Class :-
Class creates new user defined type in CPP like structure class also contain variables and function.
Variables belonging to class are called fields, properties or data members and function belonging to class
are known as member functions or methods.
15
Object Oriented Programming Using CPP

All members of structure are by default public where as all members of class are by default private hence at
least one member of function of class should be public otherwise we can not access any member of the class
to outside the class hence class becomes useless.

Declaration :-

Class declaration is similar to structure declaration only instead of struct keyword we should use class
member variables and function may private or public or protected. Private member can not access outside
the class where as public members can be access outside the class using class object.

class name
{
Private :
Variables;
Functions;
Public:
Variables;
Functions;
};

Defining member function :- Member function of class may be defined inside or outside the class like
structure. Member function define inside the class are by default inline Hence only those functions should
be defined inside the class which is satisfies the condition of inline function.
Creating object from class :- Once we declare a class and defined all member function, classname can
be used as new data type and we can create variables of class_type such as variables are called object.

Eg class_name obj;

Accessing data members :- After creating object of class, we can access pubic members of the class
through that object using member access operator(.)dot
Syntax – object.member

4 program
Accessing private members of class :-
We know that only public members of class can be access outside the class. Hence to access private
member of class we can should have a public function and called private members in it.
1 program

Array of object :-
We know that array is special type of variable in which we can store more than one value of same type in
CPP we can create array of object.
For eg. Suppose we consider classname we can create array of product type for store 5 product as follows
Class product
{
---;
----;
}
Product p[5];
16
Object Oriented Programming Using CPP

3. Function in CPP
Function :-
Functions are used to implement lager program. In structured programming functions are to break large
program into smaller one, which makes debugging of program easy.
Following Advantages of Functions :-
1. To reduce size of program by calling them at different places in the program.
2. Function can be complied separately.
3. Using function programs are easy to design, debug maintain.
4. Reuse of function may be possible.
5. Function provide interfaces to communicate with object.

Following are the elements of function we should know :-


1. Function declaration :-
This is also refer as function prototype, the prototype of function contains return type, function name and
argument list such as
Typename (argumanet list);
Int add(int x, int y);

2. Function definition :-
Function definition consist of two section function head and function body. Function head is similar to
function prototype and function body contain body of statements.
Eg
type name (arg list)
{
-----;
------;
};

Eg
int add(int x, int y)
{
int z;
z=x+y;
return z;
}

3. Function Call :- Once we define a function function can be call directly or indirectly in program.
Direct Call :- Function can be direct called using function name by passing arguments to it.
Indirect call :- If function returns an value then it can be indirectly called into another statements or
expression as follows : eg. printf(“Addition is %d”,add(a,b));

Value return from function :- Control can be written from function with value and without value. If
function return a value then return type should be specify which is similar to the type of value return by
function.
Some time function does not return any value at that time specify return type as void and return statement
does not return any value.
17
Object Oriented Programming Using CPP

Types function in CPP :-


We can implement various types of functions in CPP such as
1. Default Argument Function
2. Static Member Function
3. Inline Function
4. Call by Reference
5. Return by Reference
6. Friend Function
7. Function Overloading
8. Virtual Function

1. Inline Function :- When we use function in program then we have some advantages but we also
disadvantages that is speed of execution program becomes slow because of certain overheads such as
Passing arguments to the function
Push Argument into stack
Save the register
Return back to calling function
To avoid this overheads we can use preprocessor macros in C. macro looking like function but expand
inline before compilation of program by preprocessor Hence compiler can not detect any error if macros
contain error that means can not goes through error checking.
CPP provides another solution to this problem that is inline function. Inline function will work as macro
that expanded inline and also goes through error checking. We can define inline function by adding “inline”
keyword in function definition as follows
inline type name (argument)
{
statements;
}
Inline is request to the compiler not an order Hence compiler decides whether function should be work as
inline or as normal function. Some of the situation in which inline function does not work such as
Function contains structures and loops that is if, switch, while etc.
Function is recursive
Function contains return statements but does not return any values.
Note : Inside definition of function is by default inline function.

2. Reference Variable :- Reference variable in an alias ( topen name ) to existint variable we can declare
reference variable as follows :
type &reference_name = variable
eg int a=10;
int &b=a;
Here reference of variable is stored into variable b, Hence b is a reference of variable through which can
access value of a.
Reference variable does not allocate separate memory location, it uses memory location of existing
variable.

Call by reference :- In CPP we can create call by reference function using reference variable instead of
pointer which saves the memory space required for pointer.

void add (int &b)


{
b=b+5;
}
18
Object Oriented Programming Using CPP

main()
{
int a=10;
add(a);
cout<<”a = “<<a;
getch();
return 0;
}

Return by Reference :- Function can also return reference of variable. This reference variable is actually
alias for referred variable.
int &max(int &a, int &b)
{
if(a>b)
return(a);
else
return(b);
}

main()
{
int x=10, y=20;
max(x,y)=100;
cout<<”x = “<<x<<endl;
cout<<”y = “<<y<<endl;
getch();
return 0;
}

Default argument function :-


In CPP the concept of default argument is use we know that when function call is given number of
arguments insufficient compiler generate error message.
In CPP we can assign default values to argument and we call function with insufficient values then is uses
default value of argument.

when we call the function then parameter will be assign from left to right, Hence if we do not want to use
default values to all arguments then use default values from right to left.

Function overloading :-
CPP support the concept of polymorphism we can define more than function having same function name
which is known as function overloading. Consider following points while over loading function.
1. Number of arguments to the function should be different.
2. If number of arguments should be same then types of arguments must be different.
3. Return type of function is not consider in function overloading.

Constant Parameter Function :-


We know that when we called any function by passing same parameter values then values of parameter
will be assign to formal parameter we can change that value inside the function.
In CPP we can define constant parameter to the function using constant keyword. Then we can not change
value of that parameter inside the function.

Passing Pointer to the function :-


19
Object Oriented Programming Using CPP

We know that pointer is special type of variable in which we can store memory address of another variable.
We can use as pointer parameter to function by passing memory address to the function we can modify
value of actual parameter without return the value.

Passing object by reference :-


Reference variable can store reference of another variable changes in reference variable will change value
of that variable whose reference is stored in it.
In CPP we can use reference variable as formal parameter for passing object reference to function, that will
update information of actual parameter object.

Passing Object by pointer :-


In CPP we can pass memory address of object to the function and use pointer as parameter.

Static Members of class :-


In c program we can declare any variables as static, it will automatically initialize will value zero it global
space from start to end of program.
CPP also allows to use static members. Members declare inside the class but persisting from their
declaration to the end of program are called static member. Static members are two types :
a. Static Data members :- A variable declare inside the class using static keyword are called static data
members.
It has following properties :
i. One copy is shared between all objects of same class.
ii. It is automatically initialize when first object is created.
iii. Visibility of static data member only within the class but lifetime is till the end of program.
iv. It is used to maintain value common to the entire class.
v. Static data member need to be defined outside the class.

b. Static Member function :-


Member function may also be declare as static but there are some restriction on them.
i. They may only access other static member of the same class directly.
ii. They do not have this pointer.
iii. Static member function should be called using class name instead of object.
iv. There can not be static or non static version of same function.
class number
{
static int a;
public:
static void display()
{
cout<<a;
}
};
int number ::a;
Here variable a is a static data member which is re-declared outside the class.
Display is static member function which can not access by class object Hence we should called by
class name as follows : Number::display();
Friend Function :-
Friend function is outsided function that is not member of function. It should be declared inside the class
using friend keyword then class will allows to access its private members to that function.

Virtual Function :-
20
Object Oriented Programming Using CPP

When one class is inherited into another class and same function definition appears in both the classes
then base class function will be overwrite.
CPP provides concept of virtual function by which preserve base class function for this purpose base class
function should be defined as virtual function using virtual keyword.
21
Object Oriented Programming Using CPP

4. Constructor and Destructor


Constructor :-

Constructor is a special member function of class. When object is created constructor will be automatically
called when we create object of that class. Name of constructor function should be same as that of the class.

Syntax rule of constructor / characteristics :-

i. Name of constructor function should be same as that of class name.


ii. It does not have any return value. Hence return type is not specified even void.
iii. It is generally declared as public member function.
iv. Constructor will be called automatically when we create class object.
v. Constructor may have parameter or without parameters.
vi. Constructor may have default arguments.
vii. Constructor can not be inherited.
viii. Constructor can not declared as constant, static or virtual.
ix. Constructor can be called as implicit or explicit.
class class_name
{
class_name()
{
statements;
}
};

eg . class number
{
int a =10;
number()
{
cout<<”a = “<<a;
}
};
number m;
22
Object Oriented Programming Using CPP

Contact Us :
Facebook : Kunal S Kasar
Instagram : kunalskasar44
Email Id : kunalkasar44.kk@gmail.com
Blog : www.onlyksk.blogspot.com

Potrebbero piacerti anche