You are on page 1of 16

CS-212

OBJECT ORIENTED
PROGRAMMING
MEHREEN TAHIR
Class
• Collection of things share common properties
– Attributes
– Behaviors
• User defined template for creating objects
• Object: Variable of class
• Class is like a cookie cutter and object is the
cookie
Class Example-Student
Abstraction
• Dealing with ideas
• Provide essential information and hide the
implementation
Abstraction
• Make coffee with coffee machine
• Essentials??
– Water, coffee beans, switch on machine, select
type of coffee
• Implementation??
– Water temperature, Amount of ground coffee,
how is water warmed, how is coffee grounded etc
• All hidden inside coffee machine
Encapsulation
• Bundling of data and its operations in a single
unit

• Restricting direct access to data and methods


– Data hiding
– More flexibility
– Reuse
Objects
• What kinds of things become objects in Object
Oriented programs?
– Air traffic control
– Electric Circuit
– Online Store
– Computer related environment
• LMS
Objects
• Object as an interface
– Car
– Phone
• Separation of implementation and interface
– Data hiding/Encapsulation/Abstraction
– A car driver can drive any car
– A computer user can use any computer
– Changing implementation does not change the
interface
Access Specifiers
• Public
• Private
• Protected

• https://www.geeksforgeeks.org/access-modifiers-in-c/
Inheritance
• Relationship between classes
• superclass /base class/parent class
• subclass/derived class/child class
• Child class inherit visible properties of parent
class and has its own attributes and properties
as well
Exercise
• Box class
Setters and Getters
• A getter need not expose the data in raw
format It can process the data and limit the
view of the data others will see Getters shall
not modify the data member
• A setter could provide data validation (such as
range checking), and transform the raw data
into the internal representation
Setters and Getters
• There is no point of using cout in a getter. It
will only display the value. It cannot be further
used. Always use return statement in a getter,
for further manipulation of the value.

int get_marks(){
return marks;
}
Setters and Getters
• Likewise, do not use cin in a setter. The
purpose of setter is to set the values only.
Putting input statement in a setter violates the
purpose. Take input in main() and set the
value using setter function.
void set_marks(int m){
marks=m;
}
class gradebook{
public:
int marks;
void set_marks(int m){
marks=m;
}
int get_marks(){
return marks;
}
};
void main(){
int m;
gradebook g;
std::cin>>m;
g.set_marks(m);
std::cout<<“Percentage=”<<(g.get_marks()/50)*100;
}

You might also like