SlideShare uma empresa Scribd logo
1 de 23
C++ MODIFIERS
Michael Heron
Introduction
• Modifiers are used in C++ to change default behaviour of
functions and variables.
• Powerful tools, but to be used with caution.
• In this lecture we are going to talk about the way in which
some of these work.
• You’ve already seen some of them.
• Public
• Private
• Both of these are modifiers for visibility
Static
• Static methods and attributes are a common part of C#
and Java
• They indicate that the function or attribute belongs to a class rather
than an object.
• Each object that is instantiated makes use of the same
static variables.
• Change it on object, and you change it in all of them.
• Only one copy of a static field is ever created,
• All objects get their own bit of memory for everything else.
• instance variables
Static
• Static methods similarly are methods that belong to a
class.
• They do not require the context of an object in order to be used.
• Often used to provide ‘utility methods’ that do not require object
instantiation.
• Integer.parseInt for example
• Must indicate the method to be called by the class name.
• Not an object name.
Static
• Static methods are limited.
• They can only make use of other static methods and static
variables.
• In Java the main method is a static method.
• It should serve to bootstrap the program by instantiating the
appropriate objects.
• Programming around this can be awkward.
• You may have seen this yourself in previous years.
Static in C++
• Static in C++ works conceptually identically.
• Minor variations
• Use the scope resolution operator to access static methods in a
class.
• Static variables cannot be set an initial value in a class declaration.
• Must be done in the accompanying CPP file.
Static Example
class Account {
private:
int balance;
int overdraft;
static float interest_rate;
public:
int query_balance();
void set_balance (int);
int query_overdraft();
void set_overdraft (int);
float query_interest_rate();
};
Static Example
#include "Account.h"
#include <iostream>
#include <fstream>
using namespace std;
float Account::interest_rate = 0.05;
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;
}
float Account::query_interest_rate() {
return interest_rate;
}
Static
• Instance methods can make use of static fields.
• Not a great benefit
• Better to make the method static and call it from the class
context.
• No need for the overhead of object instantiation.
• Can still be called as an instance method.
• But no need for it to be done so.
Modified Example
class Account {
private:
int balance;
int overdraft;
static float interest_rate;
public:
int query_balance();
void set_balance (int);
int query_overdraft();
void set_overdraft (int);
static float query_interest_rate();
};
Modified Example
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include "Account.h"
using namespace std;
int main() {
Account *ob;
ob = new Account();
cout << Account::query_interest_rate() << endl;
cout << ob->query_interest_rate() << endl;
return 0;
}
Static in C++
• When the program starts, and before an objects are
instantiated, all static fields are initialized.
• When an object is declared, it gets copies of instance
attributes.
• But no copy of the static data fields.
• This system is equivalent in Java and C++ and C#
• Transferable concept.
Static in C++
• C++ also gives us a little extra somethingsomething.
• We can declare static variables that are local to methods.
• They get created when the method is first called.
• Have visibility only to the method in which they are defined.
• Destroyed when the program ends.
• Not when the method ends
• This is called method scope.
Method Scope - Without
int test_static (int tmp) {
int y = tmp;
return y;
}
int main() {
int ans;
ans = test_static (10);
cout << ans << endl;
ans = test_static (12);
cout << ans << endl;
return 0;
}
Method Scope - With
int test_static (int tmp) {
int y = tmp;
return y;
}
int main() {
int ans;
ans = test_static (10);
cout << ans << endl;
ans = test_static (12);
cout << ans << endl;
return 0;
}
Const
• One of the most useful modifiers we have available is the
const modifier.
• It lets us deal with some of the problems caused by relentless
pointer passing.
• It’s also one of the messiest
• It compensates for missing language features.
• It has several key roles in an object oriented program.
Const
• First and simplest use is to declare a constant, non-
changing value.
• Declare something as constant so it cannot be changed.
• Works much like a define in terms of where it is used.
• However, it is syntactically interpreted by the compiler.
• Defines just get search and replaced into your code.
Const
• const int num = 20;
• Attempting to change this after it has been defined will result in a
compile time error.
• Can be used to make sure there are no side-effects when working with
shared, global variables.
• Or class-wide variables.
• It also works with pointers.
• But in two different ways.
• const int* blah;
• Pointer to a constant integer
• int *const blah;
• Constant pointer to an integer.
Const
• Can also use const to indicate a return type in a function.
• Indicates to the compiler that the return value of a function should
never be altered.
• Returning a constant pointer is a good way to ensure
fidelity of memory.
• You can’t change the value of the pointer once it comes out of the
function.
++OUT OF CHEESE ERROR++
using namespace std;
const int *memory_const (int x) {
return &x;
}
int main() {
int *ptr;
int y = 10;
ptr = memory_const (10);
ptr = &y;
return 0;
}
Const in Parameters
• We can also use const in parameter passing.
• Lets us have pass by reference but also ensures we can’t change
the values sent in.
const int *memory_const (const int x) {
x = 20;
return &x;
}
Const in Object Orientation
• We can use const in methods of objects to bar them from
editing instance variables.
• One of the features of class-wide scope is that any method with
appropriate visibility can impact on any attribute.
• By adding const to a method declaration, we prohibit it
from accessing method attributes.
• We saw this when we looked at pure virtual methods.
Const and Virtual Methods
• When we talked about virtual methods, we used the
following format:
• void function() const = 0;
• And then to override, we use the following:
• void function() const
• This is a precautionary technique.
• The const may be omitted in both conditions.
• This is often used to protect from careless side-effects.

Mais conteúdo relacionado

Mais procurados (20)

Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of C
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Python ppt
Python pptPython ppt
Python ppt
 
C language (Part 2)
C language (Part 2)C language (Part 2)
C language (Part 2)
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 
CPP07 - Scope
CPP07 - ScopeCPP07 - Scope
CPP07 - Scope
 
C programming language tutorial
C programming language tutorialC programming language tutorial
C programming language tutorial
 
Type Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityType Conversion, Precedence and Associativity
Type Conversion, Precedence and Associativity
 
Ch02
Ch02Ch02
Ch02
 
Ch03
Ch03Ch03
Ch03
 
C interview questions
C interview  questionsC interview  questions
C interview questions
 
Java basic operators
Java basic operatorsJava basic operators
Java basic operators
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Unit 4. Operators and Expression
Unit 4. Operators and Expression  Unit 4. Operators and Expression
Unit 4. Operators and Expression
 
Storage Classes and Functions
Storage Classes and FunctionsStorage Classes and Functions
Storage Classes and Functions
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
 
java8
java8java8
java8
 
Operator Precedence and Associativity
Operator Precedence and AssociativityOperator Precedence and Associativity
Operator Precedence and Associativity
 
5.program structure
5.program structure5.program structure
5.program structure
 
Ch06
Ch06Ch06
Ch06
 

Destaque

Access Protection
Access ProtectionAccess Protection
Access Protectionmyrajendra
 
Object-Oriented Programming Concepts
Object-Oriented Programming ConceptsObject-Oriented Programming Concepts
Object-Oriented Programming ConceptsKwangshin Oh
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01Adil Kakakhel
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).pptAlok Kumar
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Conceptsthinkphp
 

Destaque (7)

Access Protection
Access ProtectionAccess Protection
Access Protection
 
Object-Oriented Programming Concepts
Object-Oriented Programming ConceptsObject-Oriented Programming Concepts
Object-Oriented Programming Concepts
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Oops ppt
Oops pptOops ppt
Oops ppt
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 

Semelhante a 2CPP18 - Modifiers

Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Rasan Samarasinghe
 
C++ unit-1-part-11
C++ unit-1-part-11C++ unit-1-part-11
C++ unit-1-part-11Jadavsejal
 
Advance topics of C language
Advance  topics of C languageAdvance  topics of C language
Advance topics of C languageMehwish Mehmood
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringSri Harsha Pamu
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++Manzoor ALam
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2ndConnex
 
Unit3_OOP-converted.pdf
Unit3_OOP-converted.pdfUnit3_OOP-converted.pdf
Unit3_OOP-converted.pdfPowerfullBoy1
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherBlue Elephant Consulting
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
 
5variables in c#
5variables in c#5variables in c#
5variables in c#Sireesh K
 

Semelhante a 2CPP18 - Modifiers (20)

Unit iii
Unit iiiUnit iii
Unit iii
 
C language
C languageC language
C language
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
Basic concept of c++
Basic concept of c++Basic concept of c++
Basic concept of c++
 
Intake 37 2
Intake 37 2Intake 37 2
Intake 37 2
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
C
CC
C
 
02basics
02basics02basics
02basics
 
C++ unit-1-part-11
C++ unit-1-part-11C++ unit-1-part-11
C++ unit-1-part-11
 
Aspdot
AspdotAspdot
Aspdot
 
Advance topics of C language
Advance  topics of C languageAdvance  topics of C language
Advance topics of C language
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational Engineering
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
Intake 38 2
Intake 38 2Intake 38 2
Intake 38 2
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
 
Unit3_OOP-converted.pdf
Unit3_OOP-converted.pdfUnit3_OOP-converted.pdf
Unit3_OOP-converted.pdf
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
5variables in c#
5variables in c#5variables in c#
5variables in c#
 
C language
C languageC language
C language
 

Mais 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
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - AbstractionMichael Heron
 

Mais 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
 
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
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
 

Último

Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
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
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
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
 
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
 
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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
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
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...software pro Development
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
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
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 

Último (20)

Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
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...
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
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
 
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 ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
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
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
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 ...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
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
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 

2CPP18 - Modifiers

  • 2. Introduction • Modifiers are used in C++ to change default behaviour of functions and variables. • Powerful tools, but to be used with caution. • In this lecture we are going to talk about the way in which some of these work. • You’ve already seen some of them. • Public • Private • Both of these are modifiers for visibility
  • 3. Static • Static methods and attributes are a common part of C# and Java • They indicate that the function or attribute belongs to a class rather than an object. • Each object that is instantiated makes use of the same static variables. • Change it on object, and you change it in all of them. • Only one copy of a static field is ever created, • All objects get their own bit of memory for everything else. • instance variables
  • 4. Static • Static methods similarly are methods that belong to a class. • They do not require the context of an object in order to be used. • Often used to provide ‘utility methods’ that do not require object instantiation. • Integer.parseInt for example • Must indicate the method to be called by the class name. • Not an object name.
  • 5. Static • Static methods are limited. • They can only make use of other static methods and static variables. • In Java the main method is a static method. • It should serve to bootstrap the program by instantiating the appropriate objects. • Programming around this can be awkward. • You may have seen this yourself in previous years.
  • 6. Static in C++ • Static in C++ works conceptually identically. • Minor variations • Use the scope resolution operator to access static methods in a class. • Static variables cannot be set an initial value in a class declaration. • Must be done in the accompanying CPP file.
  • 7. Static Example class Account { private: int balance; int overdraft; static float interest_rate; public: int query_balance(); void set_balance (int); int query_overdraft(); void set_overdraft (int); float query_interest_rate(); };
  • 8. Static Example #include "Account.h" #include <iostream> #include <fstream> using namespace std; float Account::interest_rate = 0.05; 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; } float Account::query_interest_rate() { return interest_rate; }
  • 9. Static • Instance methods can make use of static fields. • Not a great benefit • Better to make the method static and call it from the class context. • No need for the overhead of object instantiation. • Can still be called as an instance method. • But no need for it to be done so.
  • 10. Modified Example class Account { private: int balance; int overdraft; static float interest_rate; public: int query_balance(); void set_balance (int); int query_overdraft(); void set_overdraft (int); static float query_interest_rate(); };
  • 11. Modified Example #include <iostream> #include <fstream> #include <string> #include <iomanip> #include "Account.h" using namespace std; int main() { Account *ob; ob = new Account(); cout << Account::query_interest_rate() << endl; cout << ob->query_interest_rate() << endl; return 0; }
  • 12. Static in C++ • When the program starts, and before an objects are instantiated, all static fields are initialized. • When an object is declared, it gets copies of instance attributes. • But no copy of the static data fields. • This system is equivalent in Java and C++ and C# • Transferable concept.
  • 13. Static in C++ • C++ also gives us a little extra somethingsomething. • We can declare static variables that are local to methods. • They get created when the method is first called. • Have visibility only to the method in which they are defined. • Destroyed when the program ends. • Not when the method ends • This is called method scope.
  • 14. Method Scope - Without int test_static (int tmp) { int y = tmp; return y; } int main() { int ans; ans = test_static (10); cout << ans << endl; ans = test_static (12); cout << ans << endl; return 0; }
  • 15. Method Scope - With int test_static (int tmp) { int y = tmp; return y; } int main() { int ans; ans = test_static (10); cout << ans << endl; ans = test_static (12); cout << ans << endl; return 0; }
  • 16. Const • One of the most useful modifiers we have available is the const modifier. • It lets us deal with some of the problems caused by relentless pointer passing. • It’s also one of the messiest • It compensates for missing language features. • It has several key roles in an object oriented program.
  • 17. Const • First and simplest use is to declare a constant, non- changing value. • Declare something as constant so it cannot be changed. • Works much like a define in terms of where it is used. • However, it is syntactically interpreted by the compiler. • Defines just get search and replaced into your code.
  • 18. Const • const int num = 20; • Attempting to change this after it has been defined will result in a compile time error. • Can be used to make sure there are no side-effects when working with shared, global variables. • Or class-wide variables. • It also works with pointers. • But in two different ways. • const int* blah; • Pointer to a constant integer • int *const blah; • Constant pointer to an integer.
  • 19. Const • Can also use const to indicate a return type in a function. • Indicates to the compiler that the return value of a function should never be altered. • Returning a constant pointer is a good way to ensure fidelity of memory. • You can’t change the value of the pointer once it comes out of the function.
  • 20. ++OUT OF CHEESE ERROR++ using namespace std; const int *memory_const (int x) { return &x; } int main() { int *ptr; int y = 10; ptr = memory_const (10); ptr = &y; return 0; }
  • 21. Const in Parameters • We can also use const in parameter passing. • Lets us have pass by reference but also ensures we can’t change the values sent in. const int *memory_const (const int x) { x = 20; return &x; }
  • 22. Const in Object Orientation • We can use const in methods of objects to bar them from editing instance variables. • One of the features of class-wide scope is that any method with appropriate visibility can impact on any attribute. • By adding const to a method declaration, we prohibit it from accessing method attributes. • We saw this when we looked at pure virtual methods.
  • 23. Const and Virtual Methods • When we talked about virtual methods, we used the following format: • void function() const = 0; • And then to override, we use the following: • void function() const • This is a precautionary technique. • The const may be omitted in both conditions. • This is often used to protect from careless side-effects.