Sei sulla pagina 1di 72

C++ OOP Concepts

Outline
Basics of Object Oriented Programming
Introduction to C++
C++ Language OOP Constructs & Features

Basics of Object Oriented


Programming

What is OOP?
Object Oriented Programming (OOP) is the programming
paradigm uses objects to design applications and computer
programs.
Object oriented programming provides some nice features, some
of them include :

Classes

Data Abstraction

Objects

Data Encapsulation

Constructors & Destructors

Polymorphism

Inheritance

Overloading

Objects
The basic unit of Object Oriented Programming.
Objects are data structures consisting of data fields and methods.
Each object is a particular instance of a class, which has its
unique name.
Each object carries the properties of its relevant class, i.e.variables & associated functions.
When created, each object allocates memory for variables and
data associated with it.

Classes
Classes are the data types from which objects are created.
It can be seen as a template which define the abstract
characteristics and behaviour of a thing (object).
Properties Characteristics of each object that may be created
from the class.
Methods Actions to be performed by the objects that are
declared in class.
No memory is allocated when a class is created.

Classes (Contd..)
Memory allocation happens only when the actual instances of a
class (the objects) are created.
Basically, a class is an expanded concept of a data structure;
which can hold data as well as functions.
In terms of variables, a class would be the data_type and the
object would be the variable.

Properties & Methods


Properties mean the data to be used or manipulated within a
computer program.
Properties are generally referred to as variables.
Methods are the subroutines exclusively associated with a class
or with an object.
The methods may have a sequence of programming statements to
perform some action, a set of input parameters to customize
these actions, and possibly an output value of some kind.
Methods in C++ are usually called functions.

Introduction to C++

Introduction to C++
C++ - An enhancement of C with added OOP concepts.
Originally named C with Classes. Later changed to C++ by
adding increment operator of C language.
Standardized
14882:2003.

as

ISO/IEC

14882:1998 and later ISO/IEC

C++ has a slightly enhanced standard library over C.


C++ class based approach helps generic and template based
programming.

C++ OOP Features

Classes & Objects


Declared with a keyword class.
The syntax for class declaration is as follows:

class class_name{
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;

Classes & Objects (Contd..)


class_name is a valid C++ identifier.
The body of the declaration may contain members, which can be
both data or function declarations, and optionally access
specifiers.
object_list is an optional list of names of objects of this class.
Access specifiers: private, protected & public.

Classes & Objects (Contd..)


private : members of a class accessible only from within other
members of the same class or from their friends.
protected : accessible from members of their same class and from
their friends, and also from members of their derived classes.
public : accessible from anywhere where the object is visible.

Classes & Objects (Contd..)


Example
class Employer{
int regno, sal;
public:
void set_values (int, int);
int area (void);
} emp;

Employer is a class
emp is an object of
class Employer
Class has data and
member functions that
may be accessed through
a . (dot) operator.

class Example
class
#include <iostream>
using namespace std;
class cube
{
public:
double side;
double volume()
{
return (side * side* side);
}
};

main() Program
int main()
{
double volume1 = 0;
cube c1,c2;
cout << "Enter the length of the cube:" << endl;
cin >> c1.side;
cout << "The volume of the cube is:"
<< c1.volume() << endl;
c2.side = c1.side + 2;
cout << "The volume of the 2 nd cube is:
<< c2.volume() << endl;
return(0);
}

Constructor
Constructors are used to initialize the objects.
Constructor A special kind of function which is the member of
the class.
The name of the constructor is same as the name of the class.
Constructor is automatically called whenever an object is
created.
Constructors DO NOT have a return value.

Constructor (Contd..)
A default constructor is the one with no parameters.
If no constructor is defined by the user, the compiler supplies the
default constructor.

Destructor
A destructor is the complement of the constructor that is, it is
used to destroy the objects.
The objects are destroyed in order to deallocate the memory
occupied.
The name of the destructor is the same as the constructor and is
preceded by a ~ (tilt) operator.
A destructor for objects is executed in the reverse order of the
constructor functions.

Constructor-Destructor Example
Constructor & Destructor

#include<iostream>
using namespace std;
//
continues here...
class cube
cube()
{
{
public:
cout << "A default constructor
double side;
is called " << endl;
double volume()
}
{
~cube()
return( side * side * side );
{
}
cout << "Destructing " <<
cube(double side1)
side << endl;
{
}
cout << "A constructor is called" << endl; };
side=side1;
}
// continue...

Constructor-Destructor Example (Contd..)


int main()
{
cube c1(2.34);
cube c2;

main Program

cout << "The side of the cube is: " << c1.side << endl;
cout << "The volume of the first cube is : " << c1.volume() << endl;
cout << "Enter the length of the second cube : " ;
cin >> c2.side;
cout << "The volume of second cube is : " << c2.volume() << endl;
return(0);
}
// end...

Constructor-Destructor Example (Contd..)


Constructor & Destructor

#include<iostream>
using namespace std;
cube()
class cube
{
{
cout << "A default constructor
public:
is called " << endl;
double side;
}
double volume()
~cube()
{
{
return( side * side * side );
cout << "Destructing " <<
}
side << endl;
cube(double side1)
}
{
};
cout << "A constructor is called" << endl;
side=side1;
}
// continue..

Constructor-Destructor Example (Contd..)


int main()
{
cube c1(2.34);
cube c2;

main Program

cout << "The side of the cube is: " << c1.side << endl;
cout << "The volume of the first cube is : " << c1.volume() << endl;
cout << "Enter the length of the second cube : " ;
cin >> c2.side;
cout << "The volume of second cube is : " << c2.volume() << endl;
return(0);
}
// end...

Inheritance
A process of forming a new class from an existing class (often
called base class).
The base class also called parent class/super class.
The derived class also called as child class/sub class/extended
class.
Inheritance helps reduce the overall size of the program code,
which helps the overall performance.
The derived/extended classes have all the properties of the base
class. Upon them, a programmer can choose to add new features
specific to the newly created derived class.

Inheritance (Contd..)
Advantages of inheritance:
Reusability
Inheritance helps the reuse of the same code .
Once the base class is defined and worked out, it need not be reworked.
Any no. of derived classes can be created from the base class as needed
while adding specific features to each derived class as needed.

Saves Time & Efforts

Increases the program structure which results in a greater reliability.

Inheritance (Contd..)
Inheritance declaration:
class <derived_class_name> : <access_specifier><base_class_name>
e.g.

class bread: public food


class e_n_c: private engg
class science_students: protected students

Inheritance (Contd..)
//base class
class food
{
public:
food(void) { x=0; }
void f(int n1)
{
x= n1*5;
}
void output(void)
{ cout << x; }
private:
int x;
};
//end of base class

Inheritance Example
// derived class
class bread: public food
{
public:
bread(void) { s1=0; }
void f1(int n1)
{
s1=n1*10;
}
void output(void)
{
food :: output();
cout << s1;
}

private:
int s1;
}
// end of derived class
// main program
int main (void)
{
bread s;
s.f(10);
s.output();
s.f1(50);
s.output();
}
//end of main program

Inheritance (Contd..)
Some important points regarding inheritance:
Derived class CANNOT have access to the constructor or destructors of the
base class.
However, it can add new member functions or variables, new constructors or
destructors.
For each object of the derived class, the memory is allocated for the data
members of the base class as well as that of the derived class.
The derived class will have access to all the member data and functions of
the base class which are not defined as private.

Some Remark on Access Specifiers


public: All public type members of the class are accessible from
outside the class.
private: None of the members of type private within the class
may be accessed from outside the class.
protected: protected access specifier lies in between public and
private. If the member function/variable is defined in a class as
protected, it cannot be accessed from outside the class but they
can be accessed by the derived class of that class.

Data Abstraction
It allows creation of user-defined data types. It represents the
needed information without presenting the details.
The main idea behind data abstraction is to give a clear
separation between properties of data type and the associated
implementation details.
Abstract data type:
Properties clearly visible to the user interface.
Implementation details hidden.

Abstract data type defined in terms of the operations that it


performs, and not in terms of its structure (implementations).

Data Abstraction (Contd..)


Two types of data abstraction: Functional Abstraction, & Data
Abstraction

Functional Abstraction

Data Abstraction

Refers to functions without taking


into account its implementation.

Refers to the data that is used


without taking into account the way
it is stored.

Access to the function is provided


through a specific interface defined
to invoke the function.

Access to the data is provided


through a specific set of operations
defined to examine and manipulate
the data.

Data Abstraction (Contd..)


Reasons for need of abstraction:
Flexibility in approach: By hiding data or abstracting details, the
programmer achieves greater flexibility.
Enhanced security: Hiding the implementation details provides security.
Easier replacement: Allows the code to be replaced without recompilation. So,
replacing code becomes easier and less time consuming.
Modular approach: Project application may be divided into modules and each
of them may be tested separately. Later, all the modules are taken together
and tested. So, application development approach becomes easier.

Data Abstraction (Contd..)


Ways to achieve abstraction:
1. Modular/Function based approach:
Code is broken int small segments functions
Code or parts of it may be reused many times.
It customized all the data of a similar type, under the control of a type
module.
By defining module type, we can get the module to be an abstract data type.
2. Friend Functions:
One class or some of its members are associated with the other class as its
friend.

Encapsulation
The process of combining or packaging data with functions and
thereby allowing users to create a new abstract data type. (which
is nothing but a class!)
As data and functions reside inside a single autonomous unit.
The user cannot directly access the encapsulated data.
Encapsulation introduces the concept if information hiding.

Encapsulation (Contd..)
Encapsulation Example

class Exforsys
{
public:
int sample();
int example(char *se)
int endfunc();
//Other member functions
private:
int x;
float sq;
//Other data members
};

All data members and


functions are bundled inside
a single autonomous entity
called class Exforsys.

Encapsulation (Contd..)
As the data and the functions are bundled inside the class, the
class takes total control of maintenance and hence human errors
are reduced.
Encapsulated objects act as black boxes to the other parts of the
program. This enhances the security. And still, the objects maybe
used to achieve some functionality.
The usage of access specifiers can further add restrictions on the
way data may or may not be allowed to be accessed.
In case a user wants some non-member function to access an
objects private or protected data, he/she can use friend functions.

Abstraction vs. Encapsulation


Encapsulation

Abstraction

Information hiding

Working on higher level without


worrying about internal details.

It hides data.

It hides implementation

It binds the data and functions and


is independent for each object.
Data hiding is applicable for the
Once this object gets destroyed,
whole implementation.
all related binding information
also gets destroyed.

Polymorphism
Polymorphism allows routines to use variables of different types
at different times.
It is an ability to use an operator or a function in different ways.
A function given different meanings or an operator functioning in
many ways is called Polymorphism.

Overloading
Overloading is a type of polymorphism.
When an exiting operator or function begins to operate on new
data type, or class, it is understood to be overloaded.
There are two types of overloading:
Function overloading, &
Operator overloading

Function Overloading
Polymorphism in which the functions assume different forms at
different times is called function overloading.
The selection of an appropriate function is done at the compile
time.
Two or more functions may have the same name but their
parameter lists should be different in terms of either:
parameters, or
their data types

The functions which differ only in their return values CANNOT


be overloaded.

Function Overloading (Contd..)


The compiler selects right function depending on the type of
parameters passed.
In case of classes, the constructors could be overloaded as they
can be both initialized and uninitialized objects.

Function Overloading (Contd..)


Function Overloading Example
#include<iostream>
using namespace std;
// start of class
class employee
{
public:
int week;
int year;
double calculate(double salary)
{
return(salary*week);
}
// fnc-1

int calculate(int salary)


{
return(salary*week*year);
}
// fnc-2
employee(int week1)
{
week = week1;
}
// constructor-1
employee(int week1,int year1)
{
week = week1;
year = year1;
}
// constructor-2
};
// end of class

Function Overloading (Contd..)


main Program

int main()
{
int sal; double sal2;
employee emp1(10);
employee emp2(10,3);
cout << "Enter the no years for first employee" << endl;
cin >> emp1.year;
cout << endl << "Enter the salary per week for first employee" << endl;
cin >> sal;
cout << "The total salary of first employee is : " << emp1.calculate(sal) << endl;
cout << endl << "Enter the salary per week for second employee is : " << endl;
cin >> sal2;
cout << "The total salary of second employee is for one year:
<< emp2.calculate(sal2) << endl;
return(0);
}
// end of main program..

Operator Overloading
Polymorphism in which the operators assume different meanings
at different times is called operator overloading.
Operator functions are created to perform operator overloading.
However, operator overloading DOES NOT allow creating new
operators.
General syntax for operator function is as follows:
<return_type> operator #(<arg_list>)
{
...
}

Operator Overloading (Contd..)


<return_type> operator #(<arg_list>)
{
...
}

<return_value> : return type of the function


<arg_list> : list of function arguments
operator is a keyword.
# will be replaced with an operator for which overloading is to be
done.

Operator Overloading (Contd..)


Operator Overloading Example
#include<iostream>
using namespace std;
// start of class
class rectangle
{
public:
int length;
int breadth;
rectangle(int length1,
int breadth1)
{
length = length1;
breadth = breadth1;
}
// constructor

int operator+(rectangle r1)


{
return(r1.length+length);
}
};
// end of class

Operator Overloading (Contd..)


main Program
int main ()
{
rectangle r1(10,20);
rectangle r2(40,60);
int len;
len = r1+r2;
cout << "The total length of the two rectangles is : " << len << endl;
return(0);
}
// end of main program..

ThanQ

Potrebbero piacerti anche