SlideShare une entreprise Scribd logo
1  sur  32
C++ PRIMER
Michael Heron
Introduction
• It’s my understanding that you all learned Java as your
main language last year.
• That puts you in a relatively good place for learning C++
• They are somewhat similar languages.
• Where possible, C++ code will be related back to Java in
example code.
• This is not possible in all circumstances.
Java versus C++
• The biggest differences, as far as this module is
concerned, are as follow:
• Java is a platform independent programming language.
• C++ is not
• Java is a pure object oriented language.
• C++ is not
• Java handles memory management transparently
• C++ requires explicit memory management
• Java hides the details of passing by value and reference.
• C++ requires explicit handling
• Java permits single inheritance only
• C++ permits multiple inheritance.
Pure OOP
• Java is a pure object orientation language.
• All code must belong to a class.
• C++ permits a mix and match approach.
• This is stylistically bad.
• For this module, your C++ code should be, as far as is possible, written
as if it were pure object orientation.
• It is possible to have variables and functions that are not part of a class
in C++.
• This will be Frowned Upon
A Simple C++ Program
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
return 1;
}
More C++ Differences
• This simple C++ program highlights several differences to
Java programs.
• First of all, line 1:
• #include <iostream>
• This is known as a preprocessor directive.
• Before any of your C++ code is compiled, the compiler runs a
process called the preprocessor on it.
• It’s essentially a very powerful search and replace routine.
• The #include directive tells C++ to take the file iostream.h
and include it, in its entirety, in the current file.
• More on the preprocessor later.
More C++ Differences
• The second line:
• using namespace std;
• This is something akin to an import in Java.
• It tells C++ we are going to be using the classes and methods that
make up the std set (primarily this is input and output).
• We begin execution from a main method, just as with a
Java program.
• However, in C++ this main method is never contained within a
class.
More C++ Differences
• In Java we use System.out.println to print text to the
console.
• In C++ we make use of an IO Stream… specifically, the
cout. This represents the standard output stream. It is
defined in std.
• The << operator is used to send data to the stream.
• endl is a special symbol – it represents an end of line.
• A n symbol essentially.
Creating a C++ Project in Visual Studio
• There are many development environments available for
C++ development.
• I myself am partial to Netbeans.
• We’ll be using Visual Studio in the labs.
• Start Visual Studio
• Create a new C++ Project
• A Win32 Console Project
Settings
• In Application Settings
• Application type should be Console Application
• Check the Empty Project checkbox
• Or you’ll end up with lots of stuff you don’t want.
• Click finish
• Add a source file.
• Go to the solution explorer
• Right click on the project file
• Add -> Add New Item
• The template should be a C++ (cpp file)
• Enter the filename (say, main.cpp) to get a blank file.
C++ Syntax
• Basic structures of C++ are very similar to Java.
• They are both c-type languages.
• The following are almost syntactically identical:
• If statements
• Switch statements
• Variable declarations
• For loops
• While loops
Some Minor Differences
• While the syntax is very similar (and thus we won’t spend
a lot of time discussing it), there are some minor
differences.
• C++ will interpret any non-zero value as true in an if or
continuation condition:
int blah;
blah = 1;
if (blah) {
cout << "What Up!" << endl;
}
Some Minor Differences
• Strings in C++ are declared in lower case:
string bing;
• Standard decimal data type is a float.
• Not a double.
• Booleans known as bool
• Work the same way.
• Non null values in conditionals evaluate as true.
• They don’t have to explicitly be true or false conditions
Some Major Differences
• Functions in C++ often need to be prototyped.
• This means you provide a little ‘hint’ for the compiler by stating the
function signature at the top of the file.
#include <iostream>
using namespace std;
void print_message (string);
int main() {
print_message ("bing");
return 1;
}
void print_message (string txt) {
cout << txt << endl;
}
Some Major Differences
• C++ programs make constant use of pointers.
• These are references to areas of memory rather than discreet values.
• Java does this too for non-primitive data types.
• It handles it automatically.
• C++ requires you to explicitly manage pointer references yourself.
• Very powerful, but also an easy way to mess up a program!
• We’ll talk about pointers towards the end of this lecture.
C++ File Structure
• The code in a C++ program is usually broken up into two
parts.
• A header file (with the suffix .h) which contains function prototypes
and preprocessor directives.
• A source code file (cpp) which contains the code statements.
• A header file should not contain code.
• A source file can (and sometimes should) contain
prototypes and directives.
The Preprocessor
• Perhaps the most powerful new feature you will instantly
encounter is the preprocessor.
• As indicated previously, it takes on the form of a powerful,
context sensitive search and replace routine.
• The two most common directives are #include and
#define.
• #include we have already seen
The Preprocessor
• #define allows you to create a token that gets replaced
with something during the first runtime pass.
• In C++, these get used in the same way as static consts in a java
class.
• For example, in our header file we might declare the
following:
#define NAME“michael”
The Preprocessor
• Whenever we compile a program, the compiler does a
pass over our code with the preprocessor.
• Every time it sees the token NAME it will replace it with
the string literal “michael”.
• This allows for constant values to be set in one place and
made available to entire programs provided they #include
our header file.
The Preprocessor
• This occurs before any C++ syntax checking in the compiler.
• You can introduce syntax errors this way.
• Some directives allow for conditional inclusions
• For example, the #ifdef directive sets a section of directives to be
contingent on a certain token being defined.
• That range is ended with an #endif
• #else can be used, as in an if-else structure.
• #undef can be used to undefine previous defines.
The Preprocessor
#include <iostream>
#define TESTING 1
#ifdef TESTING
#define TEXT "this is a test"
#else
#define TEXT "this is not a test"
#endif
using namespace std;
void print_message (string);
int main() {
print_message (TEXT);
return 1;
}
void print_message (string txt) {
cout << txt << endl;
}
The Preprocessor
• It’s not terribly important you can see why this is useful at
the moment.
• You should recognise what is happening though, because the
preprocessor is one of the biggest differences in C++ programming.
• We will be making use of the preprocessor as necessary
as we go through the module material.
Input in C++
• Text input in C++ is extremely easy to do.
• Somewhat of a departure from how it is done in Java.
• The cin stream is used for this.
• The >> operator is used to pull information out of a stream
• cin reading terminates whenever it finds a space.
• It is thus fine for reading in single words and atomic data.
Input in C++
#include <iostream>
using namespace std;
void print_message (int);
int main() {
int age;
cout << "What is your age?" << endl;
cin >> age;
print_message (age);
return 1;
}
void print_message (int txt) {
cout << "Your age is " << txt << endl;
}
Input in C++
• For reading in lines of text with spaces, the getline function is
used instead.
• This takes two parameters
• The input stream to use
• The variable into which it should place the received information.
• It returns no value.
• Often getting input to work properly is a vaguely black are.
• We will talk about why later.
Pointers
• Pointers represent the biggest departure from C++.
• They take some getting used to, but become second nature before
too long.
• I am making the assumption here that you understand (in
general, if not in specifics) that you understand how
memory works in a computer program.
• Interrupt now if I’m wrong!
Pointers
• In general, C++ passes primitive variables by value.
• Functions get a copy of the data, not the data itself.
• This means if you change it in one function, it one impact on the
original declaration.
• This is equivalent to what happens in Java.
• But Java gives us limited options for changing the way that works.
Pointers
#include <iostream>
using namespace std;
void add_to_num (int);
int main() {
int num;
num = 10;
add_to_num (num);
cout << "Number is " << num << endl;
return 1;
}
void add_to_num (int num) {
num = num + 1;
}
Pointers
• In C++, we have access to two powerful operators.
• &, which is the reference operator
• You can literally think of this as a shorthand for ‘address of’
• *, which is the dereference operator
• You can think of this as ‘value of’
• We can use this to specialise our variables.
Pointers
#include <iostream>
using namespace std;
void add_to_num (int*);
int main() {
int num;
num = 10;
add_to_num (&num);
cout << "Number is " << num << endl;
return 1;
}
void add_to_num (int *num) {
*num = *num + 1;
}
Pointers
• I only want to touch on this at the moment.
• We don’t need to go into too much depth at this point, we’ll return to
the topic later when it actually starts to matter.
• The important thing is that you recognise these operators
when you see them.
• *num means ‘the value of the memory location pointed to by num’
• &num means ‘the memory location where num resides’
Summary
• C++, like Java, is a C-Type language.
• It has many similarities.
• It has many differences.
• The key differences are:
• the preprocessor
• pointers
• The lack of a pure OOP framework
• Over the coming weeks, we’ll learn more about all of
these.

Contenu connexe

Tendances

WorkinOnTheRailsRoad
WorkinOnTheRailsRoadWorkinOnTheRailsRoad
WorkinOnTheRailsRoadwebuploader
 
Advanced Reflection in Pharo
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in PharoMarcus Denker
 
Build Great Networked APIs with Swift, OpenAPI, and gRPC
Build Great Networked APIs with Swift, OpenAPI, and gRPCBuild Great Networked APIs with Swift, OpenAPI, and gRPC
Build Great Networked APIs with Swift, OpenAPI, and gRPCTim Burks
 
Lock-free algorithms for Kotlin Coroutines
Lock-free algorithms for Kotlin CoroutinesLock-free algorithms for Kotlin Coroutines
Lock-free algorithms for Kotlin CoroutinesRoman Elizarov
 
Is boilerplate code really so bad?
Is boilerplate code really so bad?Is boilerplate code really so bad?
Is boilerplate code really so bad?Trisha Gee
 
A Type-level Ruby Interpreter for Testing and Understanding
A Type-level Ruby Interpreter for Testing and UnderstandingA Type-level Ruby Interpreter for Testing and Understanding
A Type-level Ruby Interpreter for Testing and Understandingmametter
 
Taming the resource tiger
Taming the resource tigerTaming the resource tiger
Taming the resource tigerElizabeth Smith
 
Community Tech Days C# 4.0
Community Tech Days C# 4.0Community Tech Days C# 4.0
Community Tech Days C# 4.0SANKARSAN BOSE
 
introduction to server-side scripting
introduction to server-side scriptingintroduction to server-side scripting
introduction to server-side scriptingAmirul Shafeeq
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisRuslan Shevchenko
 
RESTLess Design with Apache Thrift: Experiences from Apache Airavata
RESTLess Design with Apache Thrift: Experiences from Apache AiravataRESTLess Design with Apache Thrift: Experiences from Apache Airavata
RESTLess Design with Apache Thrift: Experiences from Apache Airavatasmarru
 
Python Lambda Function
Python Lambda FunctionPython Lambda Function
Python Lambda FunctionMd Soyaib
 
Python and Zope: An introduction (May 2004)
Python and Zope: An introduction (May 2004)Python and Zope: An introduction (May 2004)
Python and Zope: An introduction (May 2004)Kiran Jonnalagadda
 
From code to pattern, part one
From code to pattern, part oneFrom code to pattern, part one
From code to pattern, part oneBingfeng Zhao
 
Xtend - better java with -less- noise
Xtend - better java with -less- noiseXtend - better java with -less- noise
Xtend - better java with -less- noiseNeeraj Bhusare
 
Integrated Language Definition Testing: Enabling Test-Driven Language Develop...
Integrated Language Definition Testing: Enabling Test-Driven Language Develop...Integrated Language Definition Testing: Enabling Test-Driven Language Develop...
Integrated Language Definition Testing: Enabling Test-Driven Language Develop...lennartkats
 
PHP, the GraphQL ecosystem and GraphQLite
PHP, the GraphQL ecosystem and GraphQLitePHP, the GraphQL ecosystem and GraphQLite
PHP, the GraphQL ecosystem and GraphQLiteJEAN-GUILLAUME DUJARDIN
 

Tendances (20)

WorkinOnTheRailsRoad
WorkinOnTheRailsRoadWorkinOnTheRailsRoad
WorkinOnTheRailsRoad
 
Intro dotnet
Intro dotnetIntro dotnet
Intro dotnet
 
Advanced Reflection in Pharo
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in Pharo
 
Build Great Networked APIs with Swift, OpenAPI, and gRPC
Build Great Networked APIs with Swift, OpenAPI, and gRPCBuild Great Networked APIs with Swift, OpenAPI, and gRPC
Build Great Networked APIs with Swift, OpenAPI, and gRPC
 
Lock-free algorithms for Kotlin Coroutines
Lock-free algorithms for Kotlin CoroutinesLock-free algorithms for Kotlin Coroutines
Lock-free algorithms for Kotlin Coroutines
 
Is boilerplate code really so bad?
Is boilerplate code really so bad?Is boilerplate code really so bad?
Is boilerplate code really so bad?
 
A Type-level Ruby Interpreter for Testing and Understanding
A Type-level Ruby Interpreter for Testing and UnderstandingA Type-level Ruby Interpreter for Testing and Understanding
A Type-level Ruby Interpreter for Testing and Understanding
 
Taming the resource tiger
Taming the resource tigerTaming the resource tiger
Taming the resource tiger
 
Community Tech Days C# 4.0
Community Tech Days C# 4.0Community Tech Days C# 4.0
Community Tech Days C# 4.0
 
introduction to server-side scripting
introduction to server-side scriptingintroduction to server-side scripting
introduction to server-side scripting
 
Dart programming language
Dart programming languageDart programming language
Dart programming language
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with this
 
RESTLess Design with Apache Thrift: Experiences from Apache Airavata
RESTLess Design with Apache Thrift: Experiences from Apache AiravataRESTLess Design with Apache Thrift: Experiences from Apache Airavata
RESTLess Design with Apache Thrift: Experiences from Apache Airavata
 
Python Lambda Function
Python Lambda FunctionPython Lambda Function
Python Lambda Function
 
Python and Zope: An introduction (May 2004)
Python and Zope: An introduction (May 2004)Python and Zope: An introduction (May 2004)
Python and Zope: An introduction (May 2004)
 
From code to pattern, part one
From code to pattern, part oneFrom code to pattern, part one
From code to pattern, part one
 
Xtend - better java with -less- noise
Xtend - better java with -less- noiseXtend - better java with -less- noise
Xtend - better java with -less- noise
 
Integrated Language Definition Testing: Enabling Test-Driven Language Develop...
Integrated Language Definition Testing: Enabling Test-Driven Language Develop...Integrated Language Definition Testing: Enabling Test-Driven Language Develop...
Integrated Language Definition Testing: Enabling Test-Driven Language Develop...
 
PHP, the GraphQL ecosystem and GraphQLite
PHP, the GraphQL ecosystem and GraphQLitePHP, the GraphQL ecosystem and GraphQLite
PHP, the GraphQL ecosystem and GraphQLite
 
Overview of CoffeeScript
Overview of CoffeeScriptOverview of CoffeeScript
Overview of CoffeeScript
 

Similaire à 2CPP02 - C++ Primer

POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
Object oriented programming 7 first steps in oop using c++
Object oriented programming 7 first steps in oop using  c++Object oriented programming 7 first steps in oop using  c++
Object oriented programming 7 first steps in oop using c++Vaibhav Khanna
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building BlocksCate Huston
 
INTRODUCTION TO C PROGRAMMING in basic c language
INTRODUCTION TO C PROGRAMMING in basic c languageINTRODUCTION TO C PROGRAMMING in basic c language
INTRODUCTION TO C PROGRAMMING in basic c languageGOKULKANNANMMECLECTC
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.pptManiMala75
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.pptManiMala75
 
05 Lecture - PARALLEL Programming in C ++.pdf
05 Lecture - PARALLEL Programming in C ++.pdf05 Lecture - PARALLEL Programming in C ++.pdf
05 Lecture - PARALLEL Programming in C ++.pdfalivaisi1
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and ClassesMichael Heron
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C LanguageMohamed Elsayed
 
Abhishek lingineni
Abhishek lingineniAbhishek lingineni
Abhishek lingineniabhishekl404
 
CPlusPus
CPlusPusCPlusPus
CPlusPusrasen58
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.pptInfotech27
 

Similaire à 2CPP02 - C++ Primer (20)

POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Object oriented programming 7 first steps in oop using c++
Object oriented programming 7 first steps in oop using  c++Object oriented programming 7 first steps in oop using  c++
Object oriented programming 7 first steps in oop using c++
 
C++ l 1
C++ l 1C++ l 1
C++ l 1
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building Blocks
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
INTRODUCTION TO C PROGRAMMING in basic c language
INTRODUCTION TO C PROGRAMMING in basic c languageINTRODUCTION TO C PROGRAMMING in basic c language
INTRODUCTION TO C PROGRAMMING in basic c language
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 
05 Lecture - PARALLEL Programming in C ++.pdf
05 Lecture - PARALLEL Programming in C ++.pdf05 Lecture - PARALLEL Programming in C ++.pdf
05 Lecture - PARALLEL Programming in C ++.pdf
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C Language
 
Presentation c++
Presentation c++Presentation c++
Presentation c++
 
Abhishek lingineni
Abhishek lingineniAbhishek lingineni
Abhishek lingineni
 
CPlusPus
CPlusPusCPlusPus
CPlusPus
 
73d32 session1 c++
73d32 session1 c++73d32 session1 c++
73d32 session1 c++
 
C++primer
C++primerC++primer
C++primer
 
CPP06 - Functions
CPP06 - FunctionsCPP06 - Functions
CPP06 - Functions
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 

Plus 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
 

Plus 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
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
 

Dernier

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
 
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
 
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
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
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
 
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
 
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
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
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
 

Dernier (20)

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...
 
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
 
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
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
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
 
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-...
 
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
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
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
 
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
 
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
 
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
 
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
 
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 🔝✔️✔️
 
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...
 
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
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
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
 

2CPP02 - C++ Primer

  • 2. Introduction • It’s my understanding that you all learned Java as your main language last year. • That puts you in a relatively good place for learning C++ • They are somewhat similar languages. • Where possible, C++ code will be related back to Java in example code. • This is not possible in all circumstances.
  • 3. Java versus C++ • The biggest differences, as far as this module is concerned, are as follow: • Java is a platform independent programming language. • C++ is not • Java is a pure object oriented language. • C++ is not • Java handles memory management transparently • C++ requires explicit memory management • Java hides the details of passing by value and reference. • C++ requires explicit handling • Java permits single inheritance only • C++ permits multiple inheritance.
  • 4. Pure OOP • Java is a pure object orientation language. • All code must belong to a class. • C++ permits a mix and match approach. • This is stylistically bad. • For this module, your C++ code should be, as far as is possible, written as if it were pure object orientation. • It is possible to have variables and functions that are not part of a class in C++. • This will be Frowned Upon
  • 5. A Simple C++ Program #include <iostream> using namespace std; int main() { cout << "Hello World!" << endl; return 1; }
  • 6. More C++ Differences • This simple C++ program highlights several differences to Java programs. • First of all, line 1: • #include <iostream> • This is known as a preprocessor directive. • Before any of your C++ code is compiled, the compiler runs a process called the preprocessor on it. • It’s essentially a very powerful search and replace routine. • The #include directive tells C++ to take the file iostream.h and include it, in its entirety, in the current file. • More on the preprocessor later.
  • 7. More C++ Differences • The second line: • using namespace std; • This is something akin to an import in Java. • It tells C++ we are going to be using the classes and methods that make up the std set (primarily this is input and output). • We begin execution from a main method, just as with a Java program. • However, in C++ this main method is never contained within a class.
  • 8. More C++ Differences • In Java we use System.out.println to print text to the console. • In C++ we make use of an IO Stream… specifically, the cout. This represents the standard output stream. It is defined in std. • The << operator is used to send data to the stream. • endl is a special symbol – it represents an end of line. • A n symbol essentially.
  • 9. Creating a C++ Project in Visual Studio • There are many development environments available for C++ development. • I myself am partial to Netbeans. • We’ll be using Visual Studio in the labs. • Start Visual Studio • Create a new C++ Project • A Win32 Console Project
  • 10. Settings • In Application Settings • Application type should be Console Application • Check the Empty Project checkbox • Or you’ll end up with lots of stuff you don’t want. • Click finish • Add a source file. • Go to the solution explorer • Right click on the project file • Add -> Add New Item • The template should be a C++ (cpp file) • Enter the filename (say, main.cpp) to get a blank file.
  • 11. C++ Syntax • Basic structures of C++ are very similar to Java. • They are both c-type languages. • The following are almost syntactically identical: • If statements • Switch statements • Variable declarations • For loops • While loops
  • 12. Some Minor Differences • While the syntax is very similar (and thus we won’t spend a lot of time discussing it), there are some minor differences. • C++ will interpret any non-zero value as true in an if or continuation condition: int blah; blah = 1; if (blah) { cout << "What Up!" << endl; }
  • 13. Some Minor Differences • Strings in C++ are declared in lower case: string bing; • Standard decimal data type is a float. • Not a double. • Booleans known as bool • Work the same way. • Non null values in conditionals evaluate as true. • They don’t have to explicitly be true or false conditions
  • 14. Some Major Differences • Functions in C++ often need to be prototyped. • This means you provide a little ‘hint’ for the compiler by stating the function signature at the top of the file. #include <iostream> using namespace std; void print_message (string); int main() { print_message ("bing"); return 1; } void print_message (string txt) { cout << txt << endl; }
  • 15. Some Major Differences • C++ programs make constant use of pointers. • These are references to areas of memory rather than discreet values. • Java does this too for non-primitive data types. • It handles it automatically. • C++ requires you to explicitly manage pointer references yourself. • Very powerful, but also an easy way to mess up a program! • We’ll talk about pointers towards the end of this lecture.
  • 16. C++ File Structure • The code in a C++ program is usually broken up into two parts. • A header file (with the suffix .h) which contains function prototypes and preprocessor directives. • A source code file (cpp) which contains the code statements. • A header file should not contain code. • A source file can (and sometimes should) contain prototypes and directives.
  • 17. The Preprocessor • Perhaps the most powerful new feature you will instantly encounter is the preprocessor. • As indicated previously, it takes on the form of a powerful, context sensitive search and replace routine. • The two most common directives are #include and #define. • #include we have already seen
  • 18. The Preprocessor • #define allows you to create a token that gets replaced with something during the first runtime pass. • In C++, these get used in the same way as static consts in a java class. • For example, in our header file we might declare the following: #define NAME“michael”
  • 19. The Preprocessor • Whenever we compile a program, the compiler does a pass over our code with the preprocessor. • Every time it sees the token NAME it will replace it with the string literal “michael”. • This allows for constant values to be set in one place and made available to entire programs provided they #include our header file.
  • 20. The Preprocessor • This occurs before any C++ syntax checking in the compiler. • You can introduce syntax errors this way. • Some directives allow for conditional inclusions • For example, the #ifdef directive sets a section of directives to be contingent on a certain token being defined. • That range is ended with an #endif • #else can be used, as in an if-else structure. • #undef can be used to undefine previous defines.
  • 21. The Preprocessor #include <iostream> #define TESTING 1 #ifdef TESTING #define TEXT "this is a test" #else #define TEXT "this is not a test" #endif using namespace std; void print_message (string); int main() { print_message (TEXT); return 1; } void print_message (string txt) { cout << txt << endl; }
  • 22. The Preprocessor • It’s not terribly important you can see why this is useful at the moment. • You should recognise what is happening though, because the preprocessor is one of the biggest differences in C++ programming. • We will be making use of the preprocessor as necessary as we go through the module material.
  • 23. Input in C++ • Text input in C++ is extremely easy to do. • Somewhat of a departure from how it is done in Java. • The cin stream is used for this. • The >> operator is used to pull information out of a stream • cin reading terminates whenever it finds a space. • It is thus fine for reading in single words and atomic data.
  • 24. Input in C++ #include <iostream> using namespace std; void print_message (int); int main() { int age; cout << "What is your age?" << endl; cin >> age; print_message (age); return 1; } void print_message (int txt) { cout << "Your age is " << txt << endl; }
  • 25. Input in C++ • For reading in lines of text with spaces, the getline function is used instead. • This takes two parameters • The input stream to use • The variable into which it should place the received information. • It returns no value. • Often getting input to work properly is a vaguely black are. • We will talk about why later.
  • 26. Pointers • Pointers represent the biggest departure from C++. • They take some getting used to, but become second nature before too long. • I am making the assumption here that you understand (in general, if not in specifics) that you understand how memory works in a computer program. • Interrupt now if I’m wrong!
  • 27. Pointers • In general, C++ passes primitive variables by value. • Functions get a copy of the data, not the data itself. • This means if you change it in one function, it one impact on the original declaration. • This is equivalent to what happens in Java. • But Java gives us limited options for changing the way that works.
  • 28. Pointers #include <iostream> using namespace std; void add_to_num (int); int main() { int num; num = 10; add_to_num (num); cout << "Number is " << num << endl; return 1; } void add_to_num (int num) { num = num + 1; }
  • 29. Pointers • In C++, we have access to two powerful operators. • &, which is the reference operator • You can literally think of this as a shorthand for ‘address of’ • *, which is the dereference operator • You can think of this as ‘value of’ • We can use this to specialise our variables.
  • 30. Pointers #include <iostream> using namespace std; void add_to_num (int*); int main() { int num; num = 10; add_to_num (&num); cout << "Number is " << num << endl; return 1; } void add_to_num (int *num) { *num = *num + 1; }
  • 31. Pointers • I only want to touch on this at the moment. • We don’t need to go into too much depth at this point, we’ll return to the topic later when it actually starts to matter. • The important thing is that you recognise these operators when you see them. • *num means ‘the value of the memory location pointed to by num’ • &num means ‘the memory location where num resides’
  • 32. Summary • C++, like Java, is a C-Type language. • It has many similarities. • It has many differences. • The key differences are: • the preprocessor • pointers • The lack of a pure OOP framework • Over the coming weeks, we’ll learn more about all of these.