You are on page 1of 45

OOP in C++

Methodology for software design / Programming Paradigm

Dr. K. Veningston
Department of Computer Science and Engineering
National Institute of Technology Srinagar
veningstonk@nitsri.ac.in
Other methodologies
• Procedure Oriented Programming (POP)
– Developing software in terms of modules and functions (job to do).
– It gives less importance to data on which job (function) is applied.
– When the complexity of the problem is high, at some stage, the POP fails, as it cannot cope with the
complexity.
• It cannot sustain high complexity, where OOP comes in with the solution.
– Example:
• C, C++, Python
• Functional Programming (FP)
– A technique where most of the activities will be done directly with the help of functions
– Example:
• Python, LISP, Prolog
• Object Oriented Programming (OOP)
– It gives equal importance to both the activities/jobs/functions we do and the data on which these jobs are
performed.
– Examples:
• C++ is OOP & POP
• Java – Pure OOP
• Python is OOP, POP, and FP.
Object Oriented Programming (OOP)
• It is a powerful technique that reflects real-world entities.
• OOP’s Guru:
– Grady Booch (who developed Unified Modeling Language (UML))
defines it as a methodology in which programs are organized/built as
a cooperative collection of objects (interaction/communication
between the objects).
• The object is an instance of a class.
Key terms in OOP
• The class is taken from the hierarchy of classes. Cred
it
Card
User ATM
SB
Acco
unt
What is OOP?
• Object oriented programming (OOP) is the principle of design & development of programs
using modular approach.
– Define real-life problems in a more systematic way (using certain principles).
• The procedural programming focuses on processing of instructions in order to perform a
desired computation.
– It emphasises more on doing things like algorithms.
– Used in programming languages like C & Pascal.
• OOP combines both the data and the functions that operate on that data into a single unit
called the object.
– It follows bottom-up design technique, it is piecing together the smaller systems to give rise to
more complex systems.
• Another major component that plays a major role in OOP is the class.
– It is a template that represents a group of objects which share common properties and
relationships.
Why OOP?
• It is a programming paradigm
– A set of rules, ideas, and concepts.
– A standard in programming that we use to solve a specific type of
problem.
• Other programming paradigms - why?
– We have a lot of different types of problems.
• The main reason is that the traditional procedural
programming is unable to model real-world problems.
C++ as Object Oriented Language?
• It is an object-oriented, general purpose programming language, derived
from C.
• Existing code on C can be used with C++, hence mode compatible.
– Even existing pre-compiled libraries can be used with new C++ code.
– Also there is no additional cost for using C++, hence efficient.
• Major improvements over C
– Stream I/O
– Strong typing
– Default argument values
– Parameter passing by reference
– OOP principles
Idea behind OOP paradigm
• To represent real-time objects/entities.
– To get with their characteristics, attributes, and behaviors.
• To explain those objects to our computer.
– To represent those objects in our programs.
How does it work on a real-life example?
• Example: Consider “Car” as an entity.
– In real life, it has many attributes or characteristics.
• Manufacturer, color, price, max speed, etc.
– Behaviors of Car
• Drive, accelerate, stop, open door, fuel level, etc.
• Other examples:
– Student, Book, Animal, etc.
Objects
• The object represents a real-world entity.
– Entities are tangible that they can be seen, noticed, or at least felt.
– Examples: room, table, chair, book, paper, student, employee, vehicle, pen,
fan, animal, box, air, etc.
– What are not objects?
• Alien
– Entities are represented in programming as objects.
– Entity possesses some properties and behaviors.
• Properties describe the entity.
• Behaviors describe actions/functionality/operations performed on the object or by
the object.
Object – Example 1

ROOM

Properties: length,
width, height,
colour

Behaviours: area(),
getRent(), paint()
Objects – Example 2
• A neat approach of developing a software.
LIBRARY
BOOK
Properties: length,
width, height,
Properties: title,
colour, capacity,
author, publisher
#books
Behaviours: read(),
Behaviours: stock(),
copier(), getPrice(),
procureBooks(),
getQtyInStock()
issueBook(),
returnBook()
Objects – Example 3
• A neat approach of developing a software.
EMPLOYEE
COMPANY
Properties: empID,
Properties: name, name, department,
location contact, salary

Behaviours: DEPARTMENT Behaviours:


revenue(), getSalary(),
Properties: name, #projects()
deptID,
#employees,
manager

Behaviours:
revenue(),
promoteEmp()
class
• Template where properties and behaviors of an entity/object are
kept.
– Class is an area/place holder/template/prototype which is holding all the
properties and behaviors of a particular entity.
– Object represents the entity itself.
• Example (class vs. object)
– Class: “Plan of a House”  class says how entity/house should be in the
form of a template/description.
– Object: “House”  entity itself/the real entity is object.
• From a class, we can create any # of objects. Class Object
• From a plan, we can construct any # of houses. Type of Variable Variable itself
Data type describes Every variable has
size, operations, etc. associated attributes
and operations
class
• The building block of OOP.
– Class is a user-defined datatype as opposed to a pre-defined datatype
(int, float, bool, double, etc.).
– It is a bit more complex datatype.
• To define a user, we need to store user characteristics including ‘name’,
‘gender’, ‘email’, etc.,
• All of the variables together are going to make a group called class.
• Applications that need to store users:
– FB: ‘name’, ‘gender’, ‘email’, ‘age’
– Fitness App: ‘name’, ‘gender’, ‘email’, ‘age’, ‘height’, ‘weight’
OOAD – Approaching a real-world problems
• (i) Identification of Entities (Noun phrase approach)
• (ii) Abstraction of each entity
– Identifying/finding the essential characteristics/behaviours of an
entity in the perspective of the user in the problem
space/application domain.
PERSON
– It is a way of looking/viewing towards an object/entity.
Properties: name,
ID, DoB, height, – Class is a good example. EMPLOYEE
weight, PATIENT
bloodGroup,BP, STUDENT CUSTOMER Properties: name,
bodyTemp, Properties: name, ID, DoB,
qualification, Properties: name, ID, DoB, height, Properties: name, qualification,
parentage, 10th ID, DoB, parentage, weight, BP, ID, DoB, parentage, 10th
mark, 12th mark, 10th mark, 12th bodyTemp, qualification, mark, 12th mark,
address, etc. mark, address parentage, address parentage, address address
GENERAL PERSON ENTITY COLLEGE HOSPITAL BANK COMPANY
OOAD – Approaching a real-world problems
• (iii) Encapsulation of entities
– Combining the properties and behaviours of an entity into a
capsule/template called class.
– A kind of hiding the details
– Class is a good example.
PERSON

Properties: name,
ID, DoB, height, EMPLOYEE
weight, PATIENT
bloodGroup,BP, STUDENT CUSTOMER Properties: name,
bodyTemp, Properties: name, ID, DoB,
qualification, Properties: name, ID, DoB, height, Properties: name, qualification,
parentage, 10th ID, DoB, parentage, weight, BP, ID, DoB, parentage, 10th
mark, 12th mark, 10th mark, 12th bodyTemp, qualification, mark, 12th mark,
address, etc. mark, address parentage, address parentage, address address
GENERAL PERSON ENTITY COLLEGE HOSPITAL BANK COMPANY
How to create class in C++?
• Members of a class = attributes + behavior

• This class represents a


blueprint, not the data.
• This will serve as a model
for the Employee.
How to create an instance/object of this class
Employee in C++?
• Members of a class = attributes + behavior
• Object is an instance of a Class.

Why we call object as


instance? Object resides in
memory.
How to access these members/attributes of this
class Employee in C++?
• Members of a class = attributes + behavior
#include <iostream>
• Every member inside the
class in C++ is private by
using namespace std; default.
class Employee { • Access modifiers
string Name; • In C++, we have
string Company; private, public,
int Age; protected.
};

Access modifiers Scope


private private members in class are not accessible (hidden)
outside the class.
public public members in class are accessible outside the class
as well.
protected In-between private & public [let’s discuss in detail when
we learn about Inheritance later]
How to access these members/attributes of this
class Employee in C++?
• Members of a class = attributes + behavior

We have set values for the


properties.
How to describe the behaviors of this class
Employee in C++?
• Members of a class = attributes + behavior (functions)

Class Method
Scope resolution operator ::
• The functions can be defined outside the class
– however they should be declared inside the class.
What if we have to create many Employee objects?
• We may need to repeat lines 19 to 21 for every Employee
object.
– This is not really optimal.
– There is a better approach to constructing objects.
• Constructors
– A constructor is a special type of method that is invoked each time an
object of a class is created.
Default constructor
• The output is the work of the
default constructor.
– Constructor that is
automatically generated by the
compiler, in case we do not
create constructors of our
own.
How we can create our own constructor?
• 3 Rules to create constructors
– (i) Despite it being a special method, the constructor does not have a
return type, unlike methods.
– (ii) The constructor has the same name as the class that it belongs to.
– (iii) The constructor must be public.
• Everything that is private is locked/hidden inside the class. We do not want to
make our constructor hidden.
• Note:
– When we decide to create our own constructors, the default
constructor will not be created.
Constructor - Example
• Code is reduced.

Constructs/Initializes the value of


the object
this pointer
mutable Storage class
• The mutable storage class specifier is used only on a class data
member to make it modifiable even though the member is part
of an object declared as const.
• We cannot use the mutable specifier with names declared as
static, const, or reference members.
mutable Storage class - Example
OOP Principles
• OOP is a methodology characterized by the following concepts.
– Encapsulation: The process of binding data members (variables,
properties) and member functions (methods/actions) into a single
unit. A class is the best example.
4 important principles/pillars/concepts of OOP
• (i) Encapsulation
• (ii) Abstraction
• (iii) Inheritance
• (iv) Polymorphism
(i) Encapsulation
• What is Encapsulation?
– Tying/binding together data and methods that operate on that data. So
that, they are grouped together within a class.
– Why?
• We do it with the purpose of preventing anything outside our class from being able
to directly access our data to interact with it and modify it.
• We want to provide our own way for that to happen, not directly.
– How do we provide a way for other classes to interact with the properties
of our class?
• We provide specific public methods that other class can invoke and interact with our
data.
(i) Encapsulation
• What is Encapsulation?
– How do we provide a way for other classes to interact with the
properties of our class?
• We provide specific public methods that other class can invoke and interact
with our data.
– How do we access an encapsulated properties of a class?
• Through its methods.
• These methods are very often implemented as getters and setters.
How getters & setters look like to obey the rule of
#include<iostream>
using namespace std;
class Employee {
private:
encapsulation?
string Name; Encapsulate these 3 properties void Introduce(){
string Company; and hide them within the cout <<"Name: "<<Name<<endl;
int Age; Employee class cout <<"Company: "<<Company<<endl;
public:
cout <<"Age: "<<Age<<endl;
void setName(string name){
}
Name = name;
Employee(string name, string company, int age){
}
Name = name;
string getName(){
Company = company;
return Name;
Age = age;
}
}
void setCompany(string company){
};
Company = company;
int main(){
}
Employee e1 = Employee("Veningston", "NIT Srinagar", 37);
string getCompany(){
Employee e2 = Employee("Oswald", "NIT Trichy", 35);
return Company;
e1.Introduce();
}
e2.Introduce();
void setAge(int age){
e1.setAge(40);
Age = age;
cout<<e1.getName() << " is "<<e1.getAge()<<" years old"<<endl;
}
return 0;
int getAge(){
}
return Age;
}
What we can do with these getters & setters ?
• We can provide special validation rules to interact with the
class properties/variables.
– Let’s say, Employee cannot be anyone who is not older than 18 years.

void setAge(int age){


if (age >= 18){
Age = age;
}
}
Example
Example – with Validation Rules
(ii) Abstraction
• What is abstraction?
– Hiding complex things behind a procedure that makes those things look
simple.
– Real-life example: Smart Phone
• Smart Phones can take pictures.
– How does the procedure of taking a picture looks like?
» User just press a button to click pictures
• We just press a button to make a call or send a message.
– These characteristics/functionalities are not that simple.
• For user, it is just a button click.
• For the company that makes Smart Phones, there is much more complex logic that
they need to implement in order for you to be able to press a button and then take a
picture.
(ii) Abstraction
• There is some sort of interface between the user and the
company that produce Smart Phones.
– On user side, everything is pretty simple and easy.
– All of the complexities behind those functionalities is hidden from
users.
• The complexities are on the side of the company that produces Smart Phones.
– User do not need to know anything about the complexity in order to
be able to use the Smart Phone.
(ii) Abstraction
• If another company comes and they want to produce Smart
Phones as well.
– What they have to do? They have to sign this contract.
• They have to provide users with a clean, simple easy to use interface.
• They have to take care on their side to implement all of the complex logic
which are hidden from users.
– Hiding this complex things from the user is called abstraction.
(ii) Abstraction
• How we can implement this concept of Contract where one side looks
simple, and the other side very complex?
– Using abstract class.
• What complex functionality we can implement on the Employee class?
– Every Employee can ask for promotion.
• Employee approaches Boss, and Boss needs to go through a very complex thought process in
order to decide if this Employee deserves the promotion or not.
• Boss needs to consider many things.
– How long this Employee has been working for the Company?
– How much knowledge this Employee possess?
– What kind of relationship that this Employee has with their colleagues?
– How much this Employee is contributing to the Company?
– Is this Employee always late for work?
– Is this Employee breaking deadlines?
– etc.
• How can we abstract this complex functionality?
(ii) Abstraction
• How can we abstract this complex functionality?
– In this situation, we are doing that for another developer who is going to
use our class.
– Assuming we are the ones producing the Smart Phones, we are the ones
who must provide the functionalities that are complex.
• We should provide that simple, basic interface for anyone who wants to use this
abstract class.
– How can we create that Contract?
• By using abstract classes.
• In Java & C# world, there is a concept called interface.
• In C++, we can simulate the behaviour of interface by using abstract class.
How to create an abstract class?
How to create an abstract class?

You might also like