Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

Object oriented Programming

Lecture 4: Classes and objects


Natalia Chaudhry

Object oriented programming in C++ by Robert Lafore 1


Recap..
Primary steps in software development
• Requirements gathering
• Modeling
• What are objects?
• Classes and objects
• UML
• Development/ Implementation
• Basic concepts / pillars in OOP

Object oriented programming in C++ by Robert Lafore 2


Recommended reads
Object oriented programming in C++ by Robert Lafore: Chapter 6

Object oriented programming in C++ by Robert Lafore 3


Abstraction
• used to hide the complexity
• One more type of abstraction in C++ can be header files. For example, consider
the pow() method present in math.h header file.
• Simplifies the model by hiding irrelevant details
• Abstraction provides the freedom to defer implementation decisions
• “Capture only those details about an object that are relevant to current
perspective”

Object oriented programming in C++ by Robert Lafore 4


• Ali is a PhD student and teaches BS students
Attributes:
Name Employee ID
Student Roll No Designation
Year of Study Salary
CGPA Age

Engineer’s View

Driver’s View

Object oriented programming in C++ by Robert Lafore 5


Information hiding
Protecting the members of a class from an illegal or unauthorized access
• Suppose you declared a CheckAccount class and you have a data
member balance inside that class
• Ali’s name is stored within his brain
• We can’t access his name directly
• Rather we can ask him to tell his name
================================================
A phone stores several phone numbers
• We can’t read the numbers directly from the SIM card
• Rather phone-set reads this information for us

Object oriented programming in C++ by Robert Lafore 6


Access modifiers
• Used to implement data hiding
• Public (available to everyone, to other classes)
• Private (can be accessed only by the functions inside the class)
• Protected ( inaccessible outside the class but they can be accessed by any
subclass(derived class) of that class)

Object oriented programming in C++ by Robert Lafore 7


Encapsulation
• An idea of bundling data and methods that work on that data within one unit
• Difference from data Hiding:
• data hiding focus more on data security and encapsulation focuses more on
hiding the complexity of the system.
• Difference from data abstraction:
• Abstraction hides details at the design level, while Encapsulation hides details
at the implementation level.

Object oriented programming in C++ by Robert Lafore 8


Classes vs objects’ representation

Object oriented programming in C++ by Robert Lafore 9


Class representation
• A class can be visualized as a three-compartment box, as illustrated:
• Class name (or identifier): identifies the class.
• Data Members or Variables (or attributes, states, fields): contains the static
attributes of the class.
• Member Functions (or methods, behaviors, operations): contains the dynamic
operations of the class.

Object oriented programming in C++ by Robert Lafore 10


two instances of the class Student, identified as
"paul" and "peter".

Object oriented programming in C++ by Robert Lafore 11


Brief summary
• A class is a programmer-defined, abstract, self-contained, reusable software
entity that mimics a real-world thing.
• A class is a 3-compartment box containing the name, data members (variables)
and the member functions.
• A class encapsulates the data structures (in data members) and algorithms
(member functions). The values of the data members constitute its state. The
member functions constitute its behaviors.
• Object is an instantiation (or realization) of a class.

Object oriented programming in C++ by Robert Lafore 12


Class Definition
• In C++, we use the keyword class to define a class. There are two sections in the class
declaration: private and public

#include <iostream>
using namespace std; void MultiplyByTwo()
class Shape //define a class {
{ int mul;
private: mul = length * length;
int length; //class data }
public: int main()
void setlength(int l) //member function to set data {
{ Shape line;
length = l; // set line length
} line.setlength(6.0);
int showlength() //member function to display data cout << "Length of line : "<< line.showlength();
{ return 0;
return length; }
}
}
Object oriented programming in C++ by Robert Lafore 13
Object oriented programming in C++ by Robert Lafore 14
class Distance
{
private:
int feet;
float inches;
int main()
public: {
void setdist(int ft, float in) Distance dist1;
{ dist1.setdist(11, 6.25); //set dist1
feet = ft; inches = in; dist2.getdist(); //get dist2 from user
} return 0;
void getdist() }
{
cout << “\nEnter feet: “; cin >> feet;
cout << “Enter inches: “; cin >> inches;
}
void showdist() //display distance
{ cout << feet << “\’-” << inches << ‘\”’; }
};

Object oriented programming in C++ by Robert Lafore 15


Counter example..
Scenario: count of number of customers entertained during each hour from 8am to 12pm
class Counter
{
private:
int count;
public:
void zero_count()
{ int main()
count=0; {
}
Counter slot1;
void inc_count()
{ slot1.inc_count(); //increment
count++; cout <<slot1.get_count();
} }
int get_count()
{
return count;
}
Garbage value problem in count data member
Counter slot1; //every time we do this,
};
slot1.zero_count(); //we must do this too

Object oriented programming in C++ by Robert Lafore 16


Constructor
• A constructor will have exact same name as the class and it does not have any
return type at all, not even void.
• A constructor is a member function that is executed automatically whenever an
object is created.
• Constructors can be very useful for setting initial values for certain member
variables.
• A constructor is a special method of a class or structure in object-oriented
programming that initializes an object of that type.
• Same name as the class + no return type!
• Recommendation: Logic involving specific operations that need to be executed at
a particular event in an application - such as opening a database connection -
should not be written in a constructor

Object oriented programming in C++ by Robert Lafore 17


Counter example..
Scenario: count of number of customers entertained during each hour from 8am to 12pm
class Counter
{
private:
int count;
public:
Counter() Counter(): count(0)
{ {
count = 0;
} }
void inc_count() int main()
{
count++; {
} Counter slot1;
int get_count() slot1.inc_count(); //increment
{
return count; cout <<slot1.get_count();
} }
};

Object oriented programming in C++ by Robert Lafore 18


Overloaded constructors: Default vs parametrized constructors
• If you don’t specify parametrized constructor then default constructor is
automatically called by default.
class Counter int main()
{ void inc_count() {
private: {
int count; count++; Counter slot1;
public: }
int get_count()
slot1.inc_count(); //increment
Counter() cout << slot1.get_count();
{ {
cout << "default" << endl; return count;
} } Counter slot2(0);
Counter(int c) }; slot2.inc_count(); //increment
{ cout << slot2.get_count();
cout << “parametrized" << endl;
count = c; return 0;
} }
void zero_count()
{
count = 0;
}

Object oriented programming in C++ by Robert Lafore 19


Member Functions Defined Outside the Class
• It is only declared inside the class, with the statement
• void add_dist_feet( int );
• This tells the compiler that this function is a member of the class but that it will be defined
outside the class declaration

class Distance void getdist() void Distance::add_dist_feet(int val)


{ { {
private: cin >> feet; inches = inches+val;
}
int feet; cin >> inches;
float inches; }
public: void showdist() //display distance
Distance() { cout << feet << “ ”<< inches << ‘\”’;
{ feet=0; inches=0.0; } }
void add_dist_feet( int ); //declaration
Distance(int ft, float in) };
{ feet=ft; inches=in; }

Object oriented programming in C++ by Robert Lafore 20


int main()
{
Distance dist1(2,2.2), dist3;
Distance dist2(1, 6.25);
dist1.add_dist_feet(4);

dist1.showdist();
dist2.showdist();
cout << endl;
return 0;
}

Object oriented programming in C++ by Robert Lafore 21


Objects passed to a function
• It is only declared inside the class, with the statement
• void add_dist( Distance, Distance );
• This tells the compiler that this function is a member of the class but that it will be defined
outside the class declaration

class Distance void getdist() void Distance::add_dist(Distance d2, Distance d3)


{ { {
private: cin >> feet; inches = d2.inches + d3.inches;
feet += d2.feet + d3.feet;
int feet; cin >> inches; }
float inches; }
public: void showdist() //display distance
Distance() { cout << feet << “ ”<< inches << ‘\”’;
{ feet=0; inches=0.0; } }
void add_dist( Distance, Distance ); //declaration
Distance(int ft, float in) };
{ feet=ft; inches=in; }

Object oriented programming in C++ by Robert Lafore 22


void Distance::add_dist(Distance d2, Distance d3)
{
inches = d2.inches + d3.inches;
feet += d2.feet + d3.feet;
}

Object oriented programming in C++ by Robert Lafore 23


int main() void Distance::add_dist(Distance d2, Distance d3)
{ {
Distance dist1(2,2.2), dist3; inches = d2.inches + d3.inches;
Distance dist2(1, 6.25); feet = d2.feet + d3.feet;
dist3.add_dist(dist1, dist2);
}
//dist3 = dist1 + dist2

dist1.showdist();
dist2.showdist();
dist3.showdist();
cout << endl;
return 0;
}

Object oriented programming in C++ by Robert Lafore 24


Destructors
• A destructor has the same name as the class
• to deallocate memory that was allocated for the object by the constructor
• At the end of the program it is called as many times as the number of objects created of that class
class Foo
{
private:
int data;
public:
Foo() : data(0) //constructor
{}
~Foo() //destructor
{}
};

Object oriented programming in C++ by Robert Lafore 25


class Human{
private:
int *age;
public:
Human(int iage)
{
age=&iage;

}
void display()
{
cout<<“Age"<<*Age<<endl;
}
~Human()
{
delete age;
cout<<"Released all memories"<<endl;
}
};
Object oriented programming in C++ by Robert Lafore 26
class sampleclass
{
sampleclass* ptr; // this is fine
};
However, while a class can contain a pointer to an object of its own type, it cannot
contain an object of its own type:
class sampleclass
{
sampleclass obj; // can’t do this
};

Object oriented programming in C++ by Robert Lafore 27


Object oriented programming in C++ by Robert Lafore 28
Array of objects (Dynamic vs static array declaration)
int main() int main()
{ {
int size; Distance parr[2];
size = 4; for(int i = 0; i < 2; i++)
Distance* p; {
p = new Distance[size]; cin >> parr[i].feet;
For (int i=0;i<size;i++) }
{ return 0;
cin>>p[i].feet; }
cin >> p[i].inches;
}
return 0;
}

Object oriented programming in C++ by Robert Lafore 29


Object oriented programming in C++ by Robert Lafore 30
Pointer to objects
int main() int main()
{ {
Distance* distptr; //pointer to Distance Distance d;
distptr = new Distance; //points to new Distance object Distance* distptr; //pointer to Distance
distptr->getdist(); //access object members distptr = &d;
distptr->showdist(); // with -> operator distptr->getdist(); //access object members
cout << endl; distptr->showdist(); // with -> operator
return 0; cout << endl;
} return 0;
}

distptr.getdist(); // won’t work; distptr is not a variable..it is a pointer to a variable


The dot operator requires the identifier on its left to be a variable. Since distptr is a pointer to a
variable, we need another syntax. (->)

Object oriented programming in C++ by Robert Lafore 31


Array of pointers (PF)
Collection of addresses

int main()
{
Int *arr_ptr [3];
Int x=0,y=1,z=3;
arr_ptr[0]=&x;
arr_ptr[1]=&y;
arr_ptr[2]=&z;

return 0;
}

Object oriented programming in C++ by Robert Lafore 32


Object oriented programming in C++ by Robert Lafore 33
Array of pointers to objects
Distance* DisPtr[100]; //array of pointers to distance
int n = 0; //number of distance objects in array
char choice;
do //put distance in array
{
DisPtr[n] = new Distance; //make new object
DisPtr[n]-> getdist();
n++;
cout << “Enter another (y/n)? “;
cin >> choice;
}
while( choice==’y’ );

Object oriented programming in C++ by Robert Lafore 34


Relationships in OOP and UML

Object oriented programming in C++ by Robert Lafore 35


Relationships between objects
• Objects do not exist in isolation from one another
• In UML, there are different types of relationships:
• Association
• Aggregation and Composition
• Generalization
• Usually depicted with a line connecting rectangles
• Class diagrams good for:
• Visualizing relationships between domain objects
• Exploring business rules and assumptions via multiplicities
• Specifying the structure of information to be (eventually) stored

Object oriented programming in C++ by Robert Lafore 36


Multiplicity
• Some examples of specifying multiplicity:
• Optional (0 or 1) 0..1
• Exactly one 1 = 1..1
• Zero or more 0..* = *
• One or more 1..*
• A range of values 2..6

Object oriented programming in C++ by Robert Lafore 37


Association
• Models obvious relationship
• Drivers are related to cars, books are related to libraries, race horses are related to race
tracks
• Association is a “using” relationship between two or more objects
• Two classes are associated if an object of one class calls a member function (an
operation) of an object of the other class
• there is no “owner” or parent
• imagine the relationship between a doctor and a patient. A doctor can be associated
with multiple patients. At the same time, one patient can visit multiple doctors for
treatment or consultation. Each of these objects has its own life cycle and there is no
“owner” or parent. The objects that are part of the association relationship can be
created and destroyed independently.
• In UML an association relationship is represented by a single arrow.

Object oriented programming in C++ by Robert Lafore 38


• An association relationship can be represented as one-to-one, one-to-many, or
many-to-many (also known as cardinality).

Object oriented programming in C++ by Robert Lafore 39


That’s it

Object oriented programming in C++ by Robert Lafore 40

You might also like