SlideShare una empresa de Scribd logo
1 de 25
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.

Más contenido relacionado

La actualidad más candente

Actors and Threads
Actors and ThreadsActors and Threads
Actors and Threadsmperham
 
CPP02 - The Structure of a Program
CPP02 - The Structure of a ProgramCPP02 - The Structure of a Program
CPP02 - The Structure of a ProgramMichael Heron
 
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 2017Thinkful
 
Thinkful - Intro to JavaScript
Thinkful - Intro to JavaScriptThinkful - Intro to JavaScript
Thinkful - Intro to JavaScriptTJ Stalcup
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptRangana Sampath
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaJohan Andrén
 
Actor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder MeetupActor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder MeetupApcera
 
Attributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programmingAttributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programmingLearnNowOnline
 
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-NativeKobkrit 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 toolskinan keshkeh
 
The Actor Model - Towards Better Concurrency
The Actor Model - Towards Better ConcurrencyThe Actor Model - Towards Better Concurrency
The Actor Model - Towards Better ConcurrencyDror 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 typeChang John
 

La actualidad más candente (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 a Introduction to Object Oriented Programming in C

2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation Fundamentals2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation FundamentalsMichael Heron
 
C++ Introduction brown bag
C++ Introduction brown bagC++ Introduction brown bag
C++ Introduction brown bagJacob Green
 
Intro to Objective C
Intro to Objective CIntro to Objective C
Intro to Objective CAshiq Uz Zoha
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and ClassesMichael Heron
 
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 BlocksCate Huston
 
COMP111-Week-1_138439.pptx
COMP111-Week-1_138439.pptxCOMP111-Week-1_138439.pptx
COMP111-Week-1_138439.pptxFarooqTariq8
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4thConnex
 
Cappuccino - A Javascript Application Framework
Cappuccino - A Javascript Application FrameworkCappuccino - A Javascript Application Framework
Cappuccino - A Javascript Application FrameworkAndreas 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 InheritanceBlue Elephant Consulting
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1stConnex
 
SE-IT JAVA LAB OOP CONCEPT
SE-IT JAVA LAB OOP CONCEPTSE-IT JAVA LAB OOP CONCEPT
SE-IT JAVA LAB OOP CONCEPTnikshaikh786
 
introduction of Object oriented programming
introduction of Object oriented programmingintroduction of Object oriented programming
introduction of Object oriented programmingRiturajJain8
 
2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator OverloadingMichael Heron
 
JavaScript Interview Questions Part - 1.pdf
JavaScript Interview Questions Part - 1.pdfJavaScript Interview Questions Part - 1.pdf
JavaScript Interview Questions Part - 1.pdfkatarichallenge
 

Similar a Introduction to Object Oriented Programming in C (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
 
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
 
JavaScript Interview Questions Part - 1.pdf
JavaScript Interview Questions Part - 1.pdfJavaScript Interview Questions Part - 1.pdf
JavaScript Interview Questions Part - 1.pdf
 

Más de Michael Heron

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMichael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconductMichael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkMichael 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 SupportMichael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and AutershipMichael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interactionMichael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityMichael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - TexturesMichael 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 RepresentationMichael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsMichael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsMichael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationMichael Heron
 

Más de 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
 

Último

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 

Último (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

Introduction to Object Oriented Programming in C

  • 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.