0% found this document useful (0 votes)
13 views36 pages

Chap6 OOP CCE

Uploaded by

chamounilona
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views36 pages

Chap6 OOP CCE

Uploaded by

chamounilona
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Object Oriented

Programming
USJ - ESIB
Department of Electrical and Mechanical Engineering
Program: Computer and Communications Engineering

1
Object-Oriented Programming Chapter 6: OOP Basics

Course Outline
1. Basics of the C++ language
2. Changing the program flow with Control Statements
3. All about Functions
4. Arrays
5. Pointers, References, Structures and Memory Management
6. Object Oriented Programming (OOP) Basics
7. Operators Overloading in OOP
8. Inheritance and Polymorphism in OOP
9. More on OOP (Static members, Namespaces, Exceptions, Templates, File
Management)

USJ-ESIB Electrical and mechanical department – CCE Program 2


Object-Oriented Programming Chapter 6: OOP Basics

Chapter 6: OOP basics – Classes, objects, attributes, methods, abstraction


encapsulation, constructors, destructors, memory management

• Object-Oriented Programming vs Procedural Programming


• Abstraction and encapsulation: main concepts of OOP
• Classes and objects
• Data member (Attributes) and member functions (methods)
• Constructors
• Destructors
• Copy Constructor
• Memory management with smart pointers

USJ-ESIB Electrical and mechanical department – CCE Program 3


Object-Oriented Programming Chapter 6: OOP Basics

What is Object-Oriented Programming?

• OOP is a programming paradigm based around the concept of


objects.
• An object contains data in the form of attributes or fields related to
that object, and code in the form of functions or methods that
operate on that object data.

USJ-ESIB Electrical and mechanical department – CCE Program 4


Object-Oriented Programming Chapter 6: OOP Basics

Difference between Object-Oriented Programming and


Procedural programming

USJ-ESIB Electrical and mechanical department – CCE Program 5


Object-Oriented Programming Chapter 6: OOP Basics

Difference between Object-Oriented and Procedural programming


Procedural or structured programming Object-oriented programming

The program is divided into small parts The program is divided into small parts called objects.
called functions.

Less secure. Doesn’t provide a proper way for data More secure. Data protection is possible by hiding
hiding. sensitive data and functions.

Less robust. Data integrity is not guaranted. More robust by ensuring data integrity and
consistency.

Code is less comprehensible. Code is more readable and comprehensible.

Modification and code expansion is more difficult and Modification and code expansion is easy and fast.
complex.

Not suitable for complex applications. Can be used for Suitable for complex applications and software
simple programs. development.

USJ-ESIB Electrical and mechanical department – CCE Program 6


Object-Oriented Programming Chapter 6: OOP Basics

OOP Encapsulation and abstraction


Room
• Encapsulation: It’s about wrapping data and data
the functions that manipulate them under a name
single unit called object. width
length
height
• Abstraction: It’s about creating generic functions
computeArea()
functions for class objects and hiding computeVolume()
implemetation details of the class. display()

USJ-ESIB Electrical and mechanical department – CCE Program 7


Object-Oriented Programming Chapter 6: OOP Basics

Encapsulation and abstraction


Object
Attributes Methods

Interface Accessible
What is visible methods

Attributes to Methods to
Implementation be hidden be hidden
What is hidden

USJ-ESIB Electrical and mechanical department – CCE Program 8


Object-Oriented Programming Chapter 6: OOP Basics

Encapsulation and abstraction


Room
Attributes Methods

Interface computeArea()
What is visible computeVolume()
display()

name
height
Implementation width
What is hidden length

USJ-ESIB Electrical and mechanical department – CCE Program 9


Object-Oriented Programming Chapter 6: OOP Basics

The four pillars of OOP


implementation m drure a3rf shu fya bs maawzeta la esta3mela yaane bt koun l info cachee aali bdo yuuz l class tbaana

• Abstraction: means hiding implementation code that is not necessary for use by
other objects. This helps make it easier for developers to change the object
implementation over time without changing the behavior of the object when it’s
used. kel objet aw class bi alba operations that works on these object yaane kel shi khaso bel objet la ymshe wel objet mawjud bi mahal wahad, je peux securisee mes
donne w ana baarir la min baate acces

• Encapsulation: means that objects contain everything they need to function,


including the object methods and any related data. The object can then make its
interface available to other objects to enable them to use the object.
• Polymorphism: means that an object can mean or be used differently in different
contexts. une class je peu creer des class en font, fya testa3mil kel l fonctions l mawjudin bel parent w fye zid aaleyun
• Inheritance means that object classes can reuse code from other classes.

USJ-ESIB Electrical and mechanical department – CCE Program 10


Object-Oriented Programming Chapter 6: OOP Basics

Advantages of OPP

Modularity

Robustness Readability

Advantages
of OOP

Data
Reusabilty
protection

Maintainability

USJ-ESIB Electrical and mechanical department – CCE Program 11


Object-Oriented Programming Chapter 6: OOP Basics

Class definition and instantiation


• A class is the result of encapsulation and abstraction
• A class is a category of objects
• A class defines a type
• Data is stored in attributes or data members
• Function for data manipulation are declared inside the class. They are called methods or member
functions.
• Class definition and instantiation:
// Instantiation of MyClass
// definition of the class MyClass
MyClass class1, class2;
class MyClass
{
// declaration of attributes and functions class1 and class2 are variables that refer to instances or
}; objects of MyClass.
Memory will be allocated only during class instantiation.
Naming convention for classes.
The name of class must begin a capital letter

USJ-ESIB Electrical and mechanical department – CCE Program 12


Object-Oriented Programming Chapter 6: OOP Basics

Attributes or data members


• Attributes store data for an object.
• Attributes are declared inside the class just as variables.
type attribute_name;
int credits;
• Attributes declared inside a class can be accessed by the methods of
the class. No need to pass them as parameters.
• To access an attribute we use the member access operator (.):
Room room1; //room1 is an object of the Room class
room1.width = 4; //width is an attribute defined inside the Room class

USJ-ESIB Electrical and mechanical department – CCE Program 13


Object-Oriented Programming Chapter 6: OOP Basics

Member functions or methods

• A method is a function defined inside the class.


• When a method doesn’t have the right to change the object data, its
declaration must be followed by the const keyword.
• A method can be defined outside the class by using the scope
resolution operator :: In this case, a prototype for the function must
be defined inside the class.

USJ-ESIB Electrical and mechanical department – CCE Program 14


Object-Oriented Programming Chapter 6: OOP Basics

Access modifiers

• Access modifiers are used to implement an important aspect of


Object-Oriented Programming known as Data Hiding. Many modifiers
exist in C++. However, we will be covering for now the private and
public access modifiers.
• By default, all members defined in a class are hidden. They can be
used inside the class only.
• public access modifier: in order to be able to access members from
outside the class, we must declare them under the public keyword.
• private access modifier. If a class contains a public section, we must
include a private section in which we declared all private members.

USJ-ESIB Electrical and mechanical department – CCE Program 15


Object-Oriented Programming Chapter 6: OOP Basics

Setters and getters

• Setters are member functions used to change the value of an


attribute. We pass to the setter the new value of the attribute and its
return type is void. We can include in the setter’s code tests to
validate data before changing the attribute value.
• Getters are member functions used to retrieve the value of an
attribute. Usually, getters are parameter less and have as return type
the attribute type.
• It’s not recommended to define getters and setters for every attribute
which is not inline with the encapsulation rules.

USJ-ESIB Electrical and mechanical department – CCE Program 16


Object-Oriented Programming Chapter 6: OOP Basics

Class constructors kl m ekhla2 objet bhtobel construction fye aati argument lal constructeur w fye par
defaut ya explcite mtl qd je cree un objet avec valeur w class
ya implicite huwe waet ekhla2 objet bala class huwe b c++ b zabto w b hoto bi
memory m lezim ne3temedaa

• A constructor in C++ is a special method that is invoked automatically


equivalent aa l __init__

at the time of object creation. It is used to initialize the data members


of created objects. methode execute automatique a la creation des objets

• The constructor has same name as the class itself. class bekhla2la constructeur w attributes

• Constructors don’t have return type


• A constructor is automatically called when an object is created.
• It must be placed in public section of a class.
• A constructor can be defined outside the class if we precede its name
with the class name followed by the scope resolution operator ::.

USJ-ESIB Electrical and mechanical department – CCE Program 17


Object-Oriented Programming Chapter 6: OOP Basics

Intializer list in constructors


• Initializer List is used in initializing the data members of a class. The
list of members to be initialized is indicated with constructor as a
comma-separated list preceded by a colon.

Room(double len, double width, double height) {


length = len ;
this->width = width ;
this->height = height ;
}

Room(double length, double width, double


height)
: length(length), width(width), height (height)
{
}

USJ-ESIB Electrical and mechanical department – CCE Program 18


Object-Oriented Programming Chapter 6: OOP Basics

Default constructor

• An explicit default constructor is defined by the programmer. It either


has all input arguments with default values, or no input arguments at
all.
• If we do not specify a constructor, C++ compiler generates an implicit
default constructor. If the attribute is of base type, like double, int,
etc., it’s left uninitialized. If the attribute is an object, its default
constructor is invoked.
• A default constructor is not called eventually if the class contains a
constructor with at least one mandatory argument.

USJ-ESIB Electrical and mechanical department – CCE Program 19


Object-Oriented Programming Chapter 6: OOP Basics

Example of a class definition


#include <iostream>
using namespace std;
const int Max_Name = 6;

class Room {
public:
//method prototypes
Room(double len=2, double width=2, double height=2);
It’s possible to initialize attributes when
string getName() const;
they are declared (double height = 15).
void setName(string);
However, this is not recommended. It’s
double computeArea() const;
better to initialize them through the
double computeVolume() const;
constructor.
void display() const;
private:
//private attributes
string name;
double height;
double width;
double length;
}

USJ-ESIB Electrical and mechanical department – CCE Program 20


Object-Oriented Programming Chapter 6: OOP Basics

Methods definition outside the class


Room::Room(double length, double width, double height)
:length(length), width(width), height (height) {} string Room::getName() const {
return name;
double Room::computeArea() const { }
return length*width; void Room::display() const {
} cout << "Room: " << getName()
double Room::computeVolume() const { << " Height: " << height
return computeArea()*height; << " Width: " << width
} << " Length:" << length << endl;
void Room::setName(string name){ }
if (name.size() > Max_Name){
cout << "Room name must not exceed " << Max_Name
<< endl;
exit(1);
}
else{
this->name = name;
}
}

USJ-ESIB Electrical and mechanical department – CCE Program 21


Object-Oriented Programming Chapter 6: OOP Basics

Class instantiation example


int main(){
Room room1 (7, 8.8, 4);
Room room2 {12.5,14,6};
Room room3;
room1.setName("CIC06");
room2.setName("CIC07");
cout << "Room1 volume " << room1.computeVolume() << endl;
room1.display();
room3.display();
return 0;
}

Room1 volume 246.4


Room: CIC06 Height: 4 Width: 8.8 Length:7
Room: Height: 2 Width: 2 Length:2

USJ-ESIB Electrical and mechanical department – CCE Program 22


Object-Oriented Programming Chapter 6: OOP Basics

Parametrized constructor
• It’s a constructor having at least one mandatory argument. The
presence of a parametrized constructor cancels the role of the default
constructor.
class Room { Room room1 (7, 8.8, 4);
public: Room room2 {12.5};
//parametrized constructor prototype Room room3;
Room(double length, double width=2, double height=2);
.
.
.

//Constructor definition
Room::Room(double length, double width, double height)
: length(length), width(width), height(height) {}

USJ-ESIB Electrical and mechanical department – CCE Program 23


Object-Oriented Programming Chapter 6: OOP Basics

Parametrized constructor
• It’s a constructor having at least one mandatory argument. The
presence of a parametrized constructor cancels the role of the default
constructor unless we add Room()=default; inside the class.
class Room { Room room1 (7, 8.8, 4);
public: Room room2 {12.5};
//parametrized constructor prototype Room room3;
Room(double length, double width=2, double height=2);
Room() = default;
.
.
.
//Constructor definition
Room::Room(double length, double width, double height)
: length(length), width(width), height(height) {}

USJ-ESIB Electrical and mechanical department – CCE Program 24


Object-Oriented Programming Chapter 6: OOP Basics

Destructor

• A destructor is a method invoked automatically when an object goes out of


scope or deleted.
• An explicit destructor may be included if we wish to liberate resources (free
memory, close files, etc.) before freeing the memory allocated for the
object.
• A destructor has the same name as the class preceded by the ~ symbol. It
doesn’t have parameters, nor return type and it can’t be overloaded.
• In case the class doesn’t include an explicit destructor, an implicit
destructor is invoked by the system. Its role is the deallocate the memory
occupied by the object.

USJ-ESIB Electrical and mechanical department – CCE Program 25


Object-Oriented Programming Chapter 6: OOP Basics

Destructor
#include <iostream>
#include <memory>
using namespace std;
class MyClass{
public:
MyClass(){cout << "Object created" << endl;;}
~MyClass(){cout << "Object destroyed" << endl;}
int getA(){return a;}
void setA(int b){a=b;} Start of block
private: Object created
int a;
Object destroyed
};
int main() End of block
{
cout << "Start of block" << endl;
{
MyClass myclass;
myclass.setA(9);
}
cout << "End of block" << endl;
}

USJ-ESIB Electrical and mechanical department – CCE Program 26


Object-Oriented Programming Chapter 6: OOP Basics

Copy Constructor

• A copy constructor is a member function that initializes an object using another object of
the same class. It creates an object by initializing it with an object of the same class
which has been created previously.
• The copy constructor can be defined explicitly by the programmer. If the programmer
does not define the copy constructor, the compiler does it for us.
• The copy constructor is called when:
• When an object of the class is returned by value.
• When an object of the class is passed (to a function) by value as an argument.
• When an object is constructed based on another object of the same class.
• MyClass obj1(arg1, arg2, …);
• MyClass obj2(obj1);
• MyClass obj3 = obj1;

USJ-ESIB Electrical and mechanical department – CCE Program 27


Object-Oriented Programming Chapter 6: OOP Basics

Copy constructor – shallow copy


• An implicit copy constructor does a member-wise Obj1
copy between objects know as shallow copy.
• Assume that the object contains a pointer attribute x: 0x100B 0x100B
that addresses a memory allocated dynamically on
the heap. 10
• If we have a previously defined object obj1 and we Obj2
create a new object obj2 as a copy of obj1, the
implicit constructor performs a shallow copy and x: 0x100B
the pointer attribute in both obj1 and obj2 points
to the same location.
• This might cause the problem if :
▪ We try to change the value of the memory location,
it will be changed for both obj1 and obj2.
▪ One of the objects goes out of scope, the allocated
memory will be deleted which will cause a
segmentation fault if the other object tries to
access that memory location.
USJ-ESIB Electrical and mechanical department – CCE Program 28
Object-Oriented Programming Chapter 6: OOP Basics

Copy constructor – deep copy


Obj1
• To avoid the problems of a shallow copy, an 0x100B
explicit copy constructor must be defined x: 0x100B 10
by the programmer in which a deep copy of
the attributes is performed.
• For each copied object, a new memory Obj2
0x110A
location is allocated that contains the value
x: 0x110A 10
of the source object.
• An implicit constructor is defined using the
following syntax:
ClassName(const ClassName& source_obj){
//perform deep copy
}
USJ-ESIB Electrical and mechanical department – CCE Program 29
Object-Oriented Programming Chapter 6: OOP Basics

Smart Pointers
• Consider this example:
void my_func()
{
int* valuePtr = new int(15);

int x = 45;

if (x == 45){

return; // here we have a memory leak, valuePtr is not deleted


}

delete valuePtr;
}

If x == 45, the function returns without freeing the allocated memory. One possible solution is to use Smart Pointers.
USJ-ESIB Electrical and mechanical department – CCE Program 30
Object-Oriented Programming Chapter 6: OOP Basics

Smart Pointers

• Smart pointers are used to make sure that an object is deleted if it is


no longer used (referenced).
• In this course, we’ll define two kinds of smart pointers:
▪ Unique ptr
▪ Shared ptr
• Smart pointers are objects defined in the memory header file

USJ-ESIB Electrical and mechanical department – CCE Program 31


Object-Oriented Programming Chapter 6: OOP Basics

Smart Pointers – unique_ptr


• unique_ptr is one of the Smart pointer implementation of the STL provided by C++11 to prevent
memory leaks. A unique_ptr object wraps around a raw pointer and it’s responsible for its
lifetime. When this object is destructed then in its destructor it frees the memory addressed by
the associated raw pointer. A unique_ptr cannot be copied, nor passed to a function.
• To define a unique_ptr : unique_ptr<type> ptr_name(new type(value));

#include <memory>
using namespace std;
void my_func()
{
unique_ptr<int> valuePtr(new int(15));
int x = 45;
// ...
if (x == 45)
return; // no memory leak anymore!
// ...
}

USJ-ESIB Electrical and mechanical department – CCE Program 32


Object-Oriented Programming Chapter 6: OOP Basics

Smart Pointers – unique_ptr


• Another way to define unique_ptr:
• To define a unique_ptr : unique_ptr<type> p = make_unique<type>(value);
• The deference operator (*) and the member access operators (->) can be used with smart
pointers.

{
unique_ptr<int> p = make_unique<int>();
// make use of p

} // p is destructed, so the int object is destructed.

USJ-ESIB Electrical and mechanical department – CCE Program 33


Object-Oriented Programming Chapter 6: OOP Basics

Smart Pointers – unique_ptr


#include <iostream>
#include <memory>
using namespace std;
class MyClass{
public:
MyClass(){cout << "Object created" << endl;;}
~MyClass(){cout << "Object destroyed" << endl;} Start of block
int getA(){return a;} Object created
void setA(int b){a=b;} 5
private: Object destroyed
int a; End of block
};
int main(){
cout << "Start of block" << endl;
{
unique_ptr<MyClass> ptr = make_unique<MyClass>();
ptr->setA(5);
cout << ptr->getA() << endl;
}
cout << "End of block" << endl;}
USJ-ESIB Electrical and mechanical department – CCE Program 34
Object-Oriented Programming Chapter 6: OOP Basics

Smart Pointers – shared_ptr


• The shared_ptr type is a smart pointer in the C++
standard library that is designed for scenarios in
which more than one owner might have to manage
the lifetime of the object in memory.
• After you initialize a shared_ptr you can copy it,
pass it by value in function arguments, and assign it
to other shared_ptr instances. All the instances
point to the same object, and share access to one
"control block" that increments and decrements
the reference count whenever a new shared_ptr is
added, goes out of scope, or is reset. When the
reference count reaches zero, the control block
deletes the memory resource and itself.
USJ-ESIB Electrical and mechanical department – CCE Program 35
Object-Oriented Programming Chapter 6: OOP Basics

Smart Pointers – shared_ptr


int main()
{
{
shared_ptr <MyClass> p0;
{
Object created
shared_ptr<MyClass> p1 = make_shared<MyClass>();
8
p0 = p1;
8
p1->setA(8);
Object destroyed
cout << p1->getA() << endl;
End of block
}
cout << p0->getA() << endl;
}
cout << "End of block" << endl;
}

USJ-ESIB Electrical and mechanical department – CCE Program 36

You might also like