Object Oriented Programming using VC++

Download Report

Transcript Object Oriented Programming using VC++

Object Oriented Programming
using VC++
Introduction
• Program – Set of instruction written in a high
level language
• High level language used for writing programs is
also called as Programming Language
• Every Programming language has a compiler or
an interpreter which merely translates the
instructions issued in high level language to low
level language that is understandable by the
computer.
• Machine language comprises of zeros and ones
(0 and 1)
Programming Paradigms
• Paradigm is nothing but a style of programming
• Few paradigms are
–
–
–
–
–
–
Structured Programming (C)
Object Oriented Programming (C++,Java,C#,VB .Net)
Object Based Programming (Java Script, VB Script)
Event driven Programming (Visual Basic)
Service Oriented Programming (Any web application)
Component Based Programming (COM, CORBA)
Object Oriented Programming
• OOP is a programming style that is focused on
objects
• Features of OOP
–
–
–
–
–
–
–
–
Modularity
Reusability
Readability
Maintainability
Inheritance
Polymorphism
Abstraction
Encapsulation
Structured Vs OOP
Structured
Focuses on
Process
Follows Top
Down Approach
OOP
Focuses on
Object
Follows Bottom
Up Approach
Approaches in Software
Development
• Top Down approach
– A Single module will be split into several smaller
modules
– General to Specific
• Bottom Up approach
– Lot of small modules will be grouped to form a single
large module
– Specific to General
• If the requirements are clear at the first instance
we can go for Top down approach
• In circumstances where the requirements may
keep on adding, we go for Bottom up approach
OOP Significance
• In real world scenario, for developing a
software, we need requirements.
• But practically speaking, requirements
keep on changing and request to add new
features will keep on accumulating.
• So its better if we follow a bottom up
approach I.e. Object Oriented
Programming Strategy
OOP Extension
• With the advent of OOP, databases too
started implementing the concept.
• Databases that make use of objects are
called as Object Oriented Databases
• This simple maps a class in OOP to a
table
• More explanation on notes page
Modularity
• Feature that enables us to split a single
large module to several small sub modules
• Enables easy maintainability of code
• Enables easy readability and
understandability of code
• Achieved in OOPS using functions
Maintainability and Readability
• Functions in OOPS enables maintainability
and readability of code
• The presence of comments in code,
enables the readability of the code
• Also in future if we want to get the
functionality of our code, then comments
will definitely of great help.
Reusability
• This feature enables us to re use the
objects (functions, variables)
• Write Once, Use Any where, any number
of times
• Since functions are independent piece of
code, they can be used any number of
times
Abstraction
• Showing only the essential features and hiding
the unnecessary features
• The access modifiers in C++ or any OOP
language, provides abstraction
• Functions also provide abstraction
• If a variable is declared as private, then other
classes cannot access it
• The function name that is used in function call
hides the implementation details from user. It
shows only the outline of functionality that the
function provides.
Encapsulation
• The process of bringing together the data
and method of an object is called as
encapsulation
• The data and method are given in the
class definition
• Classes provides us with this feature Encapsulation
Inheritance
• Feature that enables the characteristics or
properties of a parent to reach its child
• C++ supports inheritance
• A class can inherit one or more classes
• Inherited class is called as parent class or
super class or base class
• Class that inherits a parent class is called
as child class or sub class or derived class
Polymorphism
• Poly – Many
• Morph – Form
• Polymorphism is the characteristic that
enables an entity to co exist in more than
one form
• C++ supports function overloading and
operator overloading to implement
polymorphism
Writing a simple C++ Program
•
•
•
•
•
•
•
•
•
Open Microsoft Visual Studio -> Visual C++
Click File -> New
In the dialog box, select Project Tab
Select Windows Console Application
Give a name for the project
Click Files Tab
Select C++ source files
Give File name
Click OK
Writing a simple C++ Program
• In the editor opened, type the code given
at the notes page
• Save the file
• Compile the file
– This generates an exe for the project
• Build the file
– This generates an obj file for the source file
• Execute the file
Writing an OOP in C++
#include<iostream.h>
class Person
// Class declaration
{
private:
// Access specifier – Private can be accessed
int id;
// with in the class and objects of the class
char name[10];
public:
// Access specifier – Public can be accessed
void getDetails(); // with in class and also outside class
void showDetails();
};
void Person::getDetails()
// :: is called as scope resolution operator. Refer Notes page
{
cout << “Enter Id:”;
cin >> id;
// characters entered through key board is pushed to variable id
cout << “Enter Name:”;
cin >> name;
}
Writing an OOP in C++
void Person::showDetails()
{
cout << “Id: ” << id << endl;
cout << “Name:” << name << endl;
}
int main()
{
Person p;
p.getDetails();
p.showDetails();
return 0;
}
// Creating object for class Person
// invoking the class’s method
Conditions
• if
• if..else
• If..elseif..else
• switch case
Loops
•
While
while(condn)
{
Statements;
}
•
Do – while
do
{
statements;
}while(condn);
•
For
for( initialization; condition cheking; increment/decrement )
{
body of for loop
}
Variables
• Variable names are case sensitive
• Variables can contain _, alphabets and
numbers
• Variables should either start with an
alphabet or an _ (underscore)
• Variable names should not be a reserved
word
Data types
• Integer
int a;
• Float
float b;
• Double
double c;
• Char
char d;
Inline Functions
• By default all functions that are defined
with in a class definition are inline
functions
• If we wish to define a function outside
class definition, and still want it to behave
like an inline function, we need to use the
keyword inline before the function return
type in the function definition
Inline Functions
• If a function is declared as inline, then the
function call will be directly replaced by the
body of the function
• In non inline functions, if a function call is
encountered, then the program execution
saves the current context in stack and
jumps to the memory location where the
function is defined, executes it and returns
back to the entry point.
Inline Functions
• Advantages with inline function
– Execution is made faster
– Stack overhead reduced
• Inline function is similar to preprocessor
directives in C.
– If we give #define MAX 5 in C, then wherever
MAX comes in the program, it will be replaced
by 5
Inheritance
• Feature by which an entity gets the
characteristics or properties of its ancestors
• A class can derive properties and methods
belonging to another class by means of
inheritance
• The former is called as derived class or child
class or sub class
• The latter is called as base class or parent class
or super class
Types of Inheritance
• Simple
– A derived class inherits from one base class
• Multi level
– Inheritance in several levels – One class per level
• Multiple
– A class inherits from more than one base class
• Hierarchical
– Several derived class inherits from a single base
class
• Hybrid
– Combination of multiple and hierarchical inheritance.
Also called as diamond inheritance
Inheritance
• A class can inherit the members and
methods of another class in 3 ways:
– Public
– Private
– Protected
• Private members cannot be inherited
• Only public or protected members can be
inherited
Constructors
• Constructors are used for initializing data
members of a class
• Constructors are always to be defined under
public access
• Constructor is invoked whenever an object is
created
• Name of the constructor is the class name
• Constructor should not contain a return type
• Constructor can contain one or more parameters
Destructors
• Destructors are used to release the memory
used by the objects
• Destructors cannot have parameters or return
type
• There is only one destructor for a class
• Destructors are invoked before the program
execution ends
• Name of the destructor is a tilde symbol (~)
followed by class name and parenthesis –
~cls() { }
Polymorphism
• Ability of an entity to co exist in more than
one form
• Two types of polymorphism:
– Static or compile time polymorphism
– Dynamic or run time polymorphism
• Static polymorphism is called as early
binding
• Dynamic polymorphism is called as late
binding
Static Polymorphism
• Three types of static polymorphism
– Constructor overloading
• A class can contain more than one constructors
– Function overloading
• A class can contain more than one function with
the same name
– Operator overloading
• In a class, the normal behavior of an operator can
be changed. I.e in addition to its normal behavior
we can give additional functionality
Constructor Overloading
• Constructor overloading is said to be done
on constructors if
– The number of parameters for the
constructors are different
– If data type of the parameters for the
constructors are different
– Eg. Class called Sample having constructors
like Sample(), Sample(int a), Sample(int a,
float b) and so on
Function Overloading
• Two or more functions with same name
can co exist in the same class if they are
overloaded. They are said to be
overloaded functions if
– Return types of the functions are different
– Number of parameters in them are different
– Data types of parameters are different
Operator Overloading
• Syntax:
<Return type> operator <operator to be
overloaded> (<parameter list>)
{
body of the function
}
• Usage:
Obj.operator<overloaded operator> (values)
Dynamic Polymorphism
• Implemented via abstract classes and virtual
function
• If we have given a function in base class as
virtual function, then it means that its definition
can be altered in the derived classes.
• Example:
virtual int area() = 0;
We can give the definition for the function in the
derived class
Templates
• Templates enforces reusability property of
object oriented programming
• We can write functions using generic data
types and while creating objects or calling
functions, we can specify the data types
• Accordingly function’s definition or class’s
definition will be changed to the required
data type
Function templates
template <class T>
T max(T a, T b)
{
return a>b?a:b;
}
int main()
{
cout << max<int>(1,2);
}
Class Templates
template <class T>
class Test
{
T val;
Test(T a)
{
val = a;
}
};
int main()
{
Test <int> t1(10);
Test <double> t2(1.3);
return 0;
}
//a is treated as int
// a is treated as double
Exception Handling
• Exception – Error occurring at the run time or
during execution
• Exceptions are not recognized during
compilation
• C++ implements exception handling using try
catch mechanism
• The portion of code that may cause exception is
written with in try block.
• The catch block contains the code that need to
be executed when exception occurs.
Example
int main()
{
int a=10;
int b=0;
try
{
cout << a/b;
//throws an exception
throw(b);
}
catch(int e)
{
cout << “divide by zero exception:” << e;
}
}
•
•
We can also reassign value of b and make the program to continue its execution in the catch
block, instead of stopping the execution
If catch(…) is present, then it is called as default exception
Namespaces
• Allows to group entities like classes,
objects, functions under a name
• Format:
namespace <<namespace_name>>
{
declarations and definitions
}
Using namespaces
• We can change the namespace that is being
used currently by means of using directive
• We can declare alternate names for existing
namespaces according to the following format:
namespace new_name = current_name;
• using <<namespace_name>>;
• We can access members of namespace using a
:: operator (scope resolution operator)
<namespace_name>::<<member_name>>