SlideShare a Scribd company logo
Objects
Michael Heron
Introduction
• Over the past few weeks we have been working towards an
understanding of the syntax of C-type languages.
• Loops and selections
• In this lecture and the next three, we are going to look at a
special way in which we can put together programs in C++.
• It is called Object Oriented Programming.
Object Orientation
• Object orientation is a programming technique by which
functionality gets broken out into little, self contained objects.
• C++ is an object oriented language, as is Java
• Syntactically, objects are a little different from the code we’ve
seen so far.
• Conceptually, they are substantially different.
• Need to think about programs in a different way.
What is Object Orientation?
• Object orientation works on the principle of classes and
objects.
• We write classes in our code, and then create objects from them.
• They are something like writing your own data type.
• Like an int or string
• But much more powerful.
• Good object design is hard to do.
• That’s not our concern for now.
What is a Class?
• Think of a class as a blueprint.
• In C++, a class defines the following things:
• What variables a class possesses.
• What functions exist in that class.
• Classes are structural explanations for the compiler.
• They tell the compiler what kind of things we are dealing with.
• They do not exist in your code.
• Until you create an object.
What is an object?
• An object is a specific instance of a class.
• In technical terms, we say we instantiate an object when we
create it.
• The class tells the object what variables it has.
• The object contains the state of those variables.
• Think back to the idea of a class as a blueprint.
• We send that blueprint into a factory, and out comes objects
based on that blueprint.
• It’s not the easiest idea to get in your head…
• It may take some time.
In The Abstract
• Think of a chair.
• A chair has a certain structure to it, that’s how we recognise
chairs.
• It has legs
• It may have a back
• It may have arms
• It will be made of some kind of material
• It will be a colour of some kind
• We don’t know in advance what the value of any of these
traits will be.
• We only know when we create a specific chair – an object.
Why Object Orientation?
• Writing programs is hard.
• Useful to be able to break it down into its components.
• Object orientation allows us to take a ‘divide and conquer’
approach to programming.
• It’s important to maximize benefit from code.
• Useful to be able to reuse it.
• They allow us to group together variables and the functions
that act on them.
• More on that later….
Object State
• The state of an object is the value of all its variables.
• The functions permitted in an object are usually those needed
to allow the object to function.
• Consider a CD player class.
• What functions are we likely to need to make it work?
• We don’t need to know, when designing an object, how it
does it.
• Black box mentality.
Writing a Class in C++
• The process of writing a class in C++ is slightly awkward.
• First we create a header file for the class definition.
• This allows us to prototype the class in the same way we do with
functions.
• Then we need to create an implementation file for the code.
• We keep the two separate to aid in portability of code.
The Class Definition
• The class definition goes into a header file.
• A .h file
• We have seen these before
• But they have always been written for us.
• This is a file we include into our programs using the #include
directive.
• All this file contains is the structure of our class.
• No code.
The Class Definition
class Car {
private:
float price;
public:
void set_price (float p);
float query_price();
};
We use the special keyword class here – the name of our class is Car.
Ignore the public and private stuff just now – we’ll talk about that properly tomorrow.
Note that we end the structure with a semi-colon – that’s new.
The Class Implementation
• We always put variables in our classes under the private part of the
code.
• We’ll talk about why tomorrow.
• We put functions under the public part of the code.
• What we are saying to C++ is:
• We have a class called Car
• It contains a float called price.
• It contains two functions – set_price and query_price.
The Object Implementation
• However, we also need to provide the code to drive these
functions.
• C++ doesn’t do it for us.
• For this we create a second file – a cpp file.
• This is not the same thing as the program we usually create.
• We write these functions in exactly the same way we have in
the past.
• Except…
Scope Resolution
• The functions we have written so far have all been
unstructured.
• They didn’t belong to an class.
• The functions we are writing now belong to a class.
• As such, we need to tell C++ to which class they belong.
• This requires us to use a new operator.
• The scope resolution operator.
The Class Implementation
#include "car.h”
void Car::set_price (float p) {
price = p;
}
float Car::query_price() {
return price;
}
Note that we don’t have a main method here.
Our class sits there idly until we actually create an object from it.
We do that in our actual program (which looks much like it did before)
Our Main Program
#include <iostream>
#include "car.h”
using namespace std;
int main() {
Car myCar;
myCar.set_price (100.0);
cout << "You car is worth: " << myCar.query_price() << endl;
return 0;
}
We use the dot notation to access the functions that have been defined as part of our
class.
Here we create an object called myCar from the class Car we wrote earlier.
Right… why?
• This class is not very powerful.
• It really just contains a single variable and some methods for
acting on that variable.
• The more functions and variables we provide, the more
powerful our objects become.
• By breaking out this from our main program, our code
becomes easier to understand.
• We communicate between our objects via the messages passed
through function calls.
Okay, but why?
• Objects give us a mechanism by which we can begin to model
connections between separate parts of a system.
• This is not easy otherwise.
• Imagine you needed to store an array of X,Y and Z co-ordinates.
• How would you do that?
• Imagine you needed to express a relationship between universities,
students and modules?
• How would you do that?
A Bigger Example - Header
class Account {
private:
int balance;
int overdraft;
public:
int query_balance();
void set_balance (int);
int query_overdraft();
void set_overdraft (int);
void adjust_balance (int);
};
A Bigger Example - CPP
#include "Account.h”
void Account::set_balance (int v) {
balance = v;
}
int Account::query_balance() {
return balance;
}
void Account::set_overdraft (int v) {
overdraft = v;
}
int Account::query_overdraft() {
return overdraft;
}
bol Account::adjust_balance (int v) {
if (balance - v < 0 - overdraft) {
return false;
}
set_balance (balance - v);
return true;
}
A Bigger Example - Program
#include <iostream>
#include "Account.h"
using namespace std;
int main() {
Account ob;
int amount;
bool success;
cout << "How much would you like to withdraw?" << endl;
cin >> amount;
ob.set_balance (200);
ob.set_overdraft (100);
success = ob.adjust_balance (amount);
if (success) {
cout << "Transaction successful" << endl;
}
else {
cout << "Transaction failed" << endl;
}
return 0;
}
Object Orientation
• Object orientation is a tremendously powerful way of writing
programs.
• But regardless of what anyone says, it’s not an easy way of writing
programs.
• It will take some time before the use becomes apparent.
• Especially if you have some non OO programming experience.
• Almost all modern languages incorporate object orientation.
• It’s the dominant way of programming these days.
Object Orientation
• Think of objects as an especially powerful kind of variable.
• One that contains functions as well as data.
• The object is your variable.
• The class is your variable type.
• Most of the theoretical aspects of object orientation you can
ignore for now.
• That’s handy, because there are so very many of them.
Summary
• New way of programming!
• Object orientation.
• It’s tremendously powerful.
• That power comes at the cost of simplicity.
• You won’t see why just yet.
• It will take some time before it becomes obvious why object
orientation is a great way to program.
• We’ll be talking more about this over the coming lectures.

More Related Content

What's hot

Actors and Threads
Actors and ThreadsActors and Threads
Actors and Threads
mperham
 
Variables in Pharo5
Variables in Pharo5Variables in Pharo5
Variables in Pharo5
Marcus Denker
 
CPP02 - The Structure of a Program
CPP02 - The Structure of a ProgramCPP02 - The Structure of a Program
CPP02 - The Structure of a Program
Michael Heron
 
Sep 15
Sep 15Sep 15
Sep 15
Zia Akbar
 
Sep 15
Sep 15Sep 15
Sep 15
dilipseervi
 
Intro to JavaScript - Thinkful LA, June 2017
Intro to JavaScript - Thinkful LA, June 2017Intro to JavaScript - Thinkful LA, June 2017
Intro to JavaScript - Thinkful LA, June 2017
Thinkful
 
Thinkful - Intro to JavaScript
Thinkful - Intro to JavaScriptThinkful - Intro to JavaScript
Thinkful - Intro to JavaScript
TJ Stalcup
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Rangana Sampath
 
Akka introtalk HyScala DEC 2016
Akka introtalk HyScala DEC 2016Akka introtalk HyScala DEC 2016
Akka introtalk HyScala DEC 2016
PrasannaKumar Sathyanarayanan
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Johan Andrén
 
Java script ppt
Java script pptJava script ppt
Actor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder MeetupActor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder Meetup
Apcera
 
Scala-Ls1
Scala-Ls1Scala-Ls1
Scala-Ls1
Aniket Joshi
 
Java script
Java scriptJava script
Java script
Prarthan P
 
Attributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programmingAttributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programming
LearnNowOnline
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
Alaref Abushaala
 
Lecture 3 - ES6 Script Advanced for React-Native
Lecture 3 - ES6 Script Advanced for React-NativeLecture 3 - ES6 Script Advanced for React-Native
Lecture 3 - ES6 Script Advanced for React-Native
Kobkrit Viriyayudhakorn
 
2 BytesC++ course_2014_c6_ constructors and other tools
2 BytesC++ course_2014_c6_ constructors and other tools2 BytesC++ course_2014_c6_ constructors and other tools
2 BytesC++ course_2014_c6_ constructors and other tools
kinan keshkeh
 
The Actor Model - Towards Better Concurrency
The Actor Model - Towards Better ConcurrencyThe Actor Model - Towards Better Concurrency
The Actor Model - Towards Better Concurrency
Dror Bereznitsky
 
Functions, anonymous functions and the function type
Functions, anonymous functions and the function typeFunctions, anonymous functions and the function type
Functions, anonymous functions and the function type
Chang John
 

What's hot (20)

Actors and Threads
Actors and ThreadsActors and Threads
Actors and Threads
 
Variables in Pharo5
Variables in Pharo5Variables in Pharo5
Variables in Pharo5
 
CPP02 - The Structure of a Program
CPP02 - The Structure of a ProgramCPP02 - The Structure of a Program
CPP02 - The Structure of a Program
 
Sep 15
Sep 15Sep 15
Sep 15
 
Sep 15
Sep 15Sep 15
Sep 15
 
Intro to JavaScript - Thinkful LA, June 2017
Intro to JavaScript - Thinkful LA, June 2017Intro to JavaScript - Thinkful LA, June 2017
Intro to JavaScript - Thinkful LA, June 2017
 
Thinkful - Intro to JavaScript
Thinkful - Intro to JavaScriptThinkful - Intro to JavaScript
Thinkful - Intro to JavaScript
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Akka introtalk HyScala DEC 2016
Akka introtalk HyScala DEC 2016Akka introtalk HyScala DEC 2016
Akka introtalk HyScala DEC 2016
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Java script ppt
Java script pptJava script ppt
Java script ppt
 
Actor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder MeetupActor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder Meetup
 
Scala-Ls1
Scala-Ls1Scala-Ls1
Scala-Ls1
 
Java script
Java scriptJava script
Java script
 
Attributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programmingAttributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programming
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
Lecture 3 - ES6 Script Advanced for React-Native
Lecture 3 - ES6 Script Advanced for React-NativeLecture 3 - ES6 Script Advanced for React-Native
Lecture 3 - ES6 Script Advanced for React-Native
 
2 BytesC++ course_2014_c6_ constructors and other tools
2 BytesC++ course_2014_c6_ constructors and other tools2 BytesC++ course_2014_c6_ constructors and other tools
2 BytesC++ course_2014_c6_ constructors and other tools
 
The Actor Model - Towards Better Concurrency
The Actor Model - Towards Better ConcurrencyThe Actor Model - Towards Better Concurrency
The Actor Model - Towards Better Concurrency
 
Functions, anonymous functions and the function type
Functions, anonymous functions and the function typeFunctions, anonymous functions and the function type
Functions, anonymous functions and the function type
 

Similar to CPP13 - Object Orientation

2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation Fundamentals2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation Fundamentals
Michael Heron
 
Introduction to c ++ part -1
Introduction to c ++   part -1Introduction to c ++   part -1
CPP15 - Inheritance
CPP15 - InheritanceCPP15 - Inheritance
CPP15 - Inheritance
Michael Heron
 
C++ Introduction brown bag
C++ Introduction brown bagC++ Introduction brown bag
C++ Introduction brown bag
Jacob Green
 
Intro to Objective C
Intro to Objective CIntro to Objective C
Intro to Objective C
Ashiq Uz Zoha
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
Michael Heron
 
lecture_for programming and computing basics
lecture_for programming and computing basicslecture_for programming and computing basics
lecture_for programming and computing basics
JavedKhan524377
 
2classes in c#
2classes in c#2classes in c#
2classes in c#
Sireesh K
 
Introducing object oriented programming (oop)
Introducing object oriented programming (oop)Introducing object oriented programming (oop)
Introducing object oriented programming (oop)
Hemlathadhevi Annadhurai
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building Blocks
Cate Huston
 
COMP111-Week-1_138439.pptx
COMP111-Week-1_138439.pptxCOMP111-Week-1_138439.pptx
COMP111-Week-1_138439.pptx
FarooqTariq8
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
 
Cappuccino - A Javascript Application Framework
Cappuccino - A Javascript Application FrameworkCappuccino - A Javascript Application Framework
Cappuccino - A Javascript Application Framework
Andreas Korth
 
Introduction To Design Patterns Class 4 Composition vs Inheritance
 Introduction To Design Patterns Class 4 Composition vs Inheritance Introduction To Design Patterns Class 4 Composition vs Inheritance
Introduction To Design Patterns Class 4 Composition vs Inheritance
Blue Elephant Consulting
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
Connex
 
Design Without Types
Design Without TypesDesign Without Types
Design Without Types
Alexandru Bolboaca
 
Lecture 1.pptx
Lecture 1.pptxLecture 1.pptx
Lecture 1.pptx
IndraKhatri
 
SE-IT JAVA LAB OOP CONCEPT
SE-IT JAVA LAB OOP CONCEPTSE-IT JAVA LAB OOP CONCEPT
SE-IT JAVA LAB OOP CONCEPT
nikshaikh786
 
introduction of Object oriented programming
introduction of Object oriented programmingintroduction of Object oriented programming
introduction of Object oriented programming
RiturajJain8
 
2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator Overloading
Michael Heron
 

Similar to CPP13 - Object Orientation (20)

2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation Fundamentals2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation Fundamentals
 
Introduction to c ++ part -1
Introduction to c ++   part -1Introduction to c ++   part -1
Introduction to c ++ part -1
 
CPP15 - Inheritance
CPP15 - InheritanceCPP15 - Inheritance
CPP15 - Inheritance
 
C++ Introduction brown bag
C++ Introduction brown bagC++ Introduction brown bag
C++ Introduction brown bag
 
Intro to Objective C
Intro to Objective CIntro to Objective C
Intro to Objective C
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
 
lecture_for programming and computing basics
lecture_for programming and computing basicslecture_for programming and computing basics
lecture_for programming and computing basics
 
2classes in c#
2classes in c#2classes in c#
2classes in c#
 
Introducing object oriented programming (oop)
Introducing object oriented programming (oop)Introducing object oriented programming (oop)
Introducing object oriented programming (oop)
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building Blocks
 
COMP111-Week-1_138439.pptx
COMP111-Week-1_138439.pptxCOMP111-Week-1_138439.pptx
COMP111-Week-1_138439.pptx
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
Cappuccino - A Javascript Application Framework
Cappuccino - A Javascript Application FrameworkCappuccino - A Javascript Application Framework
Cappuccino - A Javascript Application Framework
 
Introduction To Design Patterns Class 4 Composition vs Inheritance
 Introduction To Design Patterns Class 4 Composition vs Inheritance Introduction To Design Patterns Class 4 Composition vs Inheritance
Introduction To Design Patterns Class 4 Composition vs Inheritance
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
 
Design Without Types
Design Without TypesDesign Without Types
Design Without Types
 
Lecture 1.pptx
Lecture 1.pptxLecture 1.pptx
Lecture 1.pptx
 
SE-IT JAVA LAB OOP CONCEPT
SE-IT JAVA LAB OOP CONCEPTSE-IT JAVA LAB OOP CONCEPT
SE-IT JAVA LAB OOP CONCEPT
 
introduction of Object oriented programming
introduction of Object oriented programmingintroduction of Object oriented programming
introduction of Object oriented programming
 
2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator Overloading
 

More from Michael Heron

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
Michael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
Michael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
Michael Heron
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
Michael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
Michael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
Michael Heron
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
Michael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
Michael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
Michael Heron
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
Michael Heron
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
Michael Heron
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
Michael Heron
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
Michael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
Michael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
Michael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
Michael Heron
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
Michael Heron
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
Michael Heron
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
Michael Heron
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
Michael Heron
 

More from Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 

Recently uploaded

openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
pavan998932
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 

Recently uploaded (20)

openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 

CPP13 - Object Orientation

  • 2. Introduction • Over the past few weeks we have been working towards an understanding of the syntax of C-type languages. • Loops and selections • In this lecture and the next three, we are going to look at a special way in which we can put together programs in C++. • It is called Object Oriented Programming.
  • 3. Object Orientation • Object orientation is a programming technique by which functionality gets broken out into little, self contained objects. • C++ is an object oriented language, as is Java • Syntactically, objects are a little different from the code we’ve seen so far. • Conceptually, they are substantially different. • Need to think about programs in a different way.
  • 4. What is Object Orientation? • Object orientation works on the principle of classes and objects. • We write classes in our code, and then create objects from them. • They are something like writing your own data type. • Like an int or string • But much more powerful. • Good object design is hard to do. • That’s not our concern for now.
  • 5. What is a Class? • Think of a class as a blueprint. • In C++, a class defines the following things: • What variables a class possesses. • What functions exist in that class. • Classes are structural explanations for the compiler. • They tell the compiler what kind of things we are dealing with. • They do not exist in your code. • Until you create an object.
  • 6. What is an object? • An object is a specific instance of a class. • In technical terms, we say we instantiate an object when we create it. • The class tells the object what variables it has. • The object contains the state of those variables. • Think back to the idea of a class as a blueprint. • We send that blueprint into a factory, and out comes objects based on that blueprint. • It’s not the easiest idea to get in your head… • It may take some time.
  • 7. In The Abstract • Think of a chair. • A chair has a certain structure to it, that’s how we recognise chairs. • It has legs • It may have a back • It may have arms • It will be made of some kind of material • It will be a colour of some kind • We don’t know in advance what the value of any of these traits will be. • We only know when we create a specific chair – an object.
  • 8. Why Object Orientation? • Writing programs is hard. • Useful to be able to break it down into its components. • Object orientation allows us to take a ‘divide and conquer’ approach to programming. • It’s important to maximize benefit from code. • Useful to be able to reuse it. • They allow us to group together variables and the functions that act on them. • More on that later….
  • 9. Object State • The state of an object is the value of all its variables. • The functions permitted in an object are usually those needed to allow the object to function. • Consider a CD player class. • What functions are we likely to need to make it work? • We don’t need to know, when designing an object, how it does it. • Black box mentality.
  • 10. Writing a Class in C++ • The process of writing a class in C++ is slightly awkward. • First we create a header file for the class definition. • This allows us to prototype the class in the same way we do with functions. • Then we need to create an implementation file for the code. • We keep the two separate to aid in portability of code.
  • 11. The Class Definition • The class definition goes into a header file. • A .h file • We have seen these before • But they have always been written for us. • This is a file we include into our programs using the #include directive. • All this file contains is the structure of our class. • No code.
  • 12. The Class Definition class Car { private: float price; public: void set_price (float p); float query_price(); }; We use the special keyword class here – the name of our class is Car. Ignore the public and private stuff just now – we’ll talk about that properly tomorrow. Note that we end the structure with a semi-colon – that’s new.
  • 13. The Class Implementation • We always put variables in our classes under the private part of the code. • We’ll talk about why tomorrow. • We put functions under the public part of the code. • What we are saying to C++ is: • We have a class called Car • It contains a float called price. • It contains two functions – set_price and query_price.
  • 14. The Object Implementation • However, we also need to provide the code to drive these functions. • C++ doesn’t do it for us. • For this we create a second file – a cpp file. • This is not the same thing as the program we usually create. • We write these functions in exactly the same way we have in the past. • Except…
  • 15. Scope Resolution • The functions we have written so far have all been unstructured. • They didn’t belong to an class. • The functions we are writing now belong to a class. • As such, we need to tell C++ to which class they belong. • This requires us to use a new operator. • The scope resolution operator.
  • 16. The Class Implementation #include "car.h” void Car::set_price (float p) { price = p; } float Car::query_price() { return price; } Note that we don’t have a main method here. Our class sits there idly until we actually create an object from it. We do that in our actual program (which looks much like it did before)
  • 17. Our Main Program #include <iostream> #include "car.h” using namespace std; int main() { Car myCar; myCar.set_price (100.0); cout << "You car is worth: " << myCar.query_price() << endl; return 0; } We use the dot notation to access the functions that have been defined as part of our class. Here we create an object called myCar from the class Car we wrote earlier.
  • 18. Right… why? • This class is not very powerful. • It really just contains a single variable and some methods for acting on that variable. • The more functions and variables we provide, the more powerful our objects become. • By breaking out this from our main program, our code becomes easier to understand. • We communicate between our objects via the messages passed through function calls.
  • 19. Okay, but why? • Objects give us a mechanism by which we can begin to model connections between separate parts of a system. • This is not easy otherwise. • Imagine you needed to store an array of X,Y and Z co-ordinates. • How would you do that? • Imagine you needed to express a relationship between universities, students and modules? • How would you do that?
  • 20. A Bigger Example - Header class Account { private: int balance; int overdraft; public: int query_balance(); void set_balance (int); int query_overdraft(); void set_overdraft (int); void adjust_balance (int); };
  • 21. A Bigger Example - CPP #include "Account.h” void Account::set_balance (int v) { balance = v; } int Account::query_balance() { return balance; } void Account::set_overdraft (int v) { overdraft = v; } int Account::query_overdraft() { return overdraft; } bol Account::adjust_balance (int v) { if (balance - v < 0 - overdraft) { return false; } set_balance (balance - v); return true; }
  • 22. A Bigger Example - Program #include <iostream> #include "Account.h" using namespace std; int main() { Account ob; int amount; bool success; cout << "How much would you like to withdraw?" << endl; cin >> amount; ob.set_balance (200); ob.set_overdraft (100); success = ob.adjust_balance (amount); if (success) { cout << "Transaction successful" << endl; } else { cout << "Transaction failed" << endl; } return 0; }
  • 23. Object Orientation • Object orientation is a tremendously powerful way of writing programs. • But regardless of what anyone says, it’s not an easy way of writing programs. • It will take some time before the use becomes apparent. • Especially if you have some non OO programming experience. • Almost all modern languages incorporate object orientation. • It’s the dominant way of programming these days.
  • 24. Object Orientation • Think of objects as an especially powerful kind of variable. • One that contains functions as well as data. • The object is your variable. • The class is your variable type. • Most of the theoretical aspects of object orientation you can ignore for now. • That’s handy, because there are so very many of them.
  • 25. Summary • New way of programming! • Object orientation. • It’s tremendously powerful. • That power comes at the cost of simplicity. • You won’t see why just yet. • It will take some time before it becomes obvious why object orientation is a great way to program. • We’ll be talking more about this over the coming lectures.