SlideShare une entreprise Scribd logo
1  sur  26
An introduction to C++
Prepare yourselves for working with an evolving ‘modern’ language.
This presentation will cover important things that you may not know about that I feel
will be beneficial to know.
I will attempt to be light hearted and informative but this is the first brown bag so be
lenient.
Overview
• C++ key differences
• Brief information on the language
• Including a mini table of helpful libraries
• Pointers! The stack, the heap and what you want.
• Allocation types
• Nullptr
• Allocation types
• Header files & Source files
• Header directives in C++, What are they and how are they used?
• Example of functional C++ class (Header & Source)
• Protection levels in C++ (Already partial encountered in C#)
• Polymorphism (special thing involving inheritance)
• Casting (Boxing in the C# world)
• C++ extra top tips to enhance your C++ experience (seriously)
I’m aware that some of you have had lessons on C++ so I shall try to omit some recurring slides from the presentation, but the slides I have kept I feel are important to cover again even
in brief.
C++ Differences
• C++ doesn’t have garbage collection.
• this is both good and bad because it means you can control more but you have to be careful with what you do.
• It is much harder to include external usable code.
• In C++ you would have to share the header file with your code base to know of the implementation and potentially
have to link the compiled code into your solution (This can really suck at times).
• There is some annoying key word re-use
• The Const key word literally causes 4 different results depending on where and how you use it.
• Templates… These are actually really cool and helpful!
• You can create functions that accept and work on multiple types.
• Templates are calculated at compile-time (I will get into templates very briefly later)
• Polymorphic Casting
• Ever been working on something that used inheritance and been like I want this object to be treated as a specific
object type. Well you can!
Information about the language platform
You may be saying. “What is this? Surely there is only one language?”. Nope!
The C++ language is actively being developed as such there are multiple compiler
versions. But more importantly, there are 2 distributions of the compiler:
• GCC (GNU Compiler Collection). An open source compiler distribution.
• VC++ (Microsoft Visual C++). Microsoft’s C++ compiler packaged with Visual Studio.
If you have used multiple versions of visual studio you have probably used slightly different C++ versions
Visual Studio Version Visual C++ Version C++ Distribution Improvements
Visual Studio 2010 Visual C++ 10.0 Only partial C++11 support
Visual Studio 2012 Visual C++ 11.0 C++ 11
Visual Studio 2013 Visual C++ 12.0 C++ 11 (Supports some of 14)
Visual Studio 2015 Visual C++ 14.0 C++ 14 (There is support for some of 17)
The standard Library
People coming from the C# world are used to a library of functionality they can use. C++ has an actively developed standard
library implementation that can be very useful. Just like with C# you have to declare you are using the library.
A lot of new things were added to the C++ 11 standard that can be very helpful to new developers.
Library Information
<regex> Regex library. Allows you to work with patterns and find things from text.
<chrono> Time library. Helpful for doing time things…
<vector> A specialized container template.
<array> An array with additional functionality and supporting features on top of the array.
<queue> A queue. First in – first out.
<utility> This holds vague utility features such as those required for move semantics (ADVANCED).
<iostream> You guys know iostream. Input, output stream, helpful for console and file management.
<algorithm> Algorithms for findings data within data. (not to be confused with regex)
<map> Map object A with Object B. Very useful tool alongside <set>
<string> A string utility for string types. This is nice as the string implementation holds useful things like size.
<memory> ADVANCED. Used to access smart pointers.
Pointers
Magical things! They are used to refer to things strictly by memory you can even have them refer to
functions as well as objects.
However you must be really careful with how you use them.
Declaring a pointer:
Creates a pointer object to an object of the type
Creating a pointer to an existing object:
Example of creating a object and creating a pointer to the object.
Dereferencing a pointer:
This now is technically the object we were pointing to in memory
Getting the address of a pointer:
Address of pointer object
Getting the address of the object a pointer points to:
You need to dereference the pointer before you call the address (&)
References
References are a type of pointer. Denoted by a & prefix after the type. There are some unique rules
and cool features of references.
• A reference cannot be NULL. You can assign to it only when you create it.
• A reference can’t have it value reassigned.
• A reference can only ‘refer’ to a variable with allocated memory (not temporary objects)
• Example: Notice the reference doesn’t take a memory address but the dereferenced object.
• You cannot have a standard library container of references. As the container expects to be able to
allocate and deallocate memory for it’s objects, but a reference is immutable.
• A reference to the object lets you treat the object exactly as the original variable
• Object& obj = variable; variable.MemberFunction();
Nullptr (Pointer default location)
You should attempt to always initialize pointers assigned to something. In new C++ the default location that
pointers point to when created is NULL (assigned to nullptr), it can be checked using the keyword ‘nullptr’.
Nullptr is the correct way to check if a pointer is valid.
WARNING: They could still be freely dangling after an object is destroyed. Try to avoid this pattern but if it happens make sure to set the dangling pointer to nullptr.
It is very good practice to check your pointers before you use them. You should always check them when the pointers are
unknown, E.G a pointer provided to a function as an argument. The example below is going to be safe but is used as a
demonstration of its usage.
nullptr is a replacement for
literal 0 and NULL macros
which has historically been
used for null pointing
pointers.
Reminder: Setting pointers to null by
default is implementation specific, some
implementations could leave them
random.
• Always initialize your pointers to
something, including null.
• The compiler will prevent you from
creating unassigned pointers by
default.
• Class construction will initialize
unassigned pointer members to NULL
for you.
Examples of Allocation
Don’t underappreciate this slide. There are a lot of bad C++ programmers who only create objects on the heap.
I will demonstrate a stack verses a heap allocation.
Benefits of using a stack object are that it is faster to allocate and once the object goes out of scope it is
destroyed (destructor invoked) automatically for you.
Stack Static Allocation(Temporary) Heap Dynamic allocation (Permanent)
Technically the same. Compiler should
optimize away the copy operation. But be
warned all the same.
Headers
Headers are files that get linked with source files by the compiler
• They should only hold the necessary data for compiling. More on this Later
• Headers should only hold function declarations not function definitions
• Okay not entirely true there are cases where the definition is needed by the header
• Inline Code requires definition
• Templates requires definition
Source Files
• These files will need the header files to know the logic about other
defined types.
• E.G A vehicle source file (Vehicle.cpp) might need the header for People.h if it
is to use multiple Person or do anything with a Person type.
• Don’t re-declare headers that are included by the source files header
file.
• This file holds all the implementation and definition logic of you
header.
Header Directives
What are they
Technically they are a type of pre-processor directives. They are
handled by the pre-processor, consider them like small
instructions and directions that are performed initially before
the compiler.
Important Preprocessors you will encounter
Pragma Once
This is very important and should appear in nearly all header
files. It causes only a single compilation of the source file.
Include File
Include the file in this compilation unit. The entire file contents
is processed with the file.
Include Header
Include header is used for including header files and system
provided files in the compilation unit.
“Include Header” and “Include File” are used
interchangeably, but you should use the
appropriate one for your need.
Creating a working class
Header file <.h> Source File <.cpp>
A very basic example. Notice how the cpp includes the header file that it provides definitions for. Notice how the
header file has to have the <string> header to provide a definition of what the string type is because it has a
member variable of string type.
Protection levels in classes
Every thing beneath this is public.
Accessible to derived classes and
external classes.
Special kind of private protection. Only this class and
any children derived from this class can access
protected members.
Pure virtual function. It must be defined in
a derived classes, you can’t make an
instance of this class only it’s children
Private protection. The private members are only
available to this class in-particular, not even its
children.
Polymorphism
This is something you will hear about and though it may sound very advanced you will likely see it and in some
cases will have used it prior to this lecture.
Polymorphism is just a powerful way of using inheritance (that concept I’m sure you are all very familiar with now).
Polymorphism can only be done on dynamic types (the heap one).
Polymorphism is about treating an object in memory as a different object. The next few slides go into it in
detail but here is a very quick example.
They are the same exact object in memory.
Except they are treated different depending on
the type we have declared the pointer.
Casting
Casting is a method of reinterpreting data as a different type. The most common example is for
handling polymorphic objects. You will probably become familiar with the first two.
Casting in C++ is probably the first example of a template function you will see (Notice the < > brackets)
• 4 Types of casting
1. Static Casting
2. Dynamic Casting
3. Const Casting
4. Reinterpret Casting
Implicit Cast Example Explicit Cast Example
Static Casting
You should only use this if you know the casting type.
If you attempt a static_cast on a type which can’t be cast to, your
program WILL crash.
If you are intending to cast. You will/should probably use this in most
cases. The common case being up casting to a base type.
Dynamic Casting
• Can cast a pointer of type to another pointer of type in runtime
• Will return null if the cast is unsuccessful.
This is an impossible cast but it is safe because
dynamic cast will return a null pointer which I
can check before using it.
A legal dynamic cast. Though in this case I know exactly what it will be I
should have used a static cast (or at least check my dynamic cast)
Top Tips
Helpful things as a bonus or things that were not as important as the
other slides but are worth mentioning.
• Iterating over a collection without an index increment.
• Forward declare pointers to avoid including files.
• If you are using inheritance make your destructor’s virtual.
• Initializer lists.
• Const usage (ughhhhh)
• Parsing by value compared to reference
Iterating over a collection
If you have a collection of objects like a standard library vector you can iterate over it with out an
explicitly declared increment.
In this example each iteration over the collection
creates a reference (Non-null pointer) to the
element of the container.
• Don’t have to keep track of iterating over the loop.
• Easier to access the elements within the container this way.
• Few other benefits that can be found by experimenting with its usage.
Forward declaring pointer types
• This is more of a standard than a tip. It is highly encouraged that header files should only include
files if the declared class needs to know about the type.
• Pointers are guaranteed to be a fixed size (4 Bytes) so the class implementing the pointer doesn’t
need to know the type.
• The source file (cpp) will still need the header for what the type is meant to be to use it.
Virtual destructors
This specifically related to polymorphism and inheritance.
Calling delete on a base object that has been created from a derived object will result in only the base
version of the destructor being called. This causes a memory leak as the child class is never deleted.
Using a virtual destructor fixes this and ensures the derived objects destructor is invoked if delete is called
on the base object.
ALWAYS HAVE A VIRTUAL DESTRUCTOR IN PARENT CLASSES THAT USE INHERITANCE.
Or make the destructor protected in the base class so you can’t call delete on the base object.
Initializer lists
Most of you are probably familiar with creating an object like this:
In C++ You can initialize members like this:
An initializer list is just a bunch of constructor calls to be completed before the main object (in this Case Rectangle) is
created.
There are advantages of doing it like this. If you had object classes as a member (variable) inside Rectangle it would
attempt to call a default constructor first. This method lets you handle the member construction instead yourself.
A good example of its use is to set References (things from earlier) before your object gets constructed; if you don’t the
compiler will complain that the reference is null (not set) when constructed.
Const usage
Const has a few different meanings depending on how you use it. It can quite easily become confusing.
Basically a const to the right of something means that ‘thing’ cannot change while to the left means that ‘thing’ is a const ‘thing’.
A simple const int. Must be initialized to value when created.
A int pointer that is constant. The pointer can not be reassigned.
A method that takes a const int.
Method takes an int type but the method cannot change the value of the int.
A const function. This function does not allow the function to change the class.
Passing by value or reference
A method parameter is basically a variable that gets constructed from arguments provided to the
method. By comparison C# would always* pass by reference.
So consider what your method should be doing.
Copying (value):
DoThingToObject(Type object);
Reference:
DoThingToObject(Type& object_ref);
Pointer:
DoThingToObject(Type* object_pointer);
*always except in the case of primitive types (integers, floats, etc) which were passed by value (copied).
More advanced stuff!
Don’t trouble your heads too much with this stuff. Some of it is so advanced there are
whole talks(by more qualified people) on the subjects.
• Advanced Templating
• Variance templates
• Templating full classes not just functions
• Lambda Functions
• Aka mini-functions created in code.
• Std::bind and std::function
• Special types of code wrappers that can be invoked to call logic outside the callers scope.
• Yes these two types have different usage.
• Smart pointers
• Helpful tools for managing memory for you.
• There are costs and trade offs for which ones you use.
• Move semantics
• More efficient memory management.

Contenu connexe

Tendances

Intro to Objective C
Intro to Objective CIntro to Objective C
Intro to Objective CAshiq Uz Zoha
 
Codegeneration Goodies
Codegeneration GoodiesCodegeneration Goodies
Codegeneration Goodiesmeysholdt
 
Using Xcore with Xtext
Using Xcore with XtextUsing Xcore with Xtext
Using Xcore with XtextHolger Schill
 
Python introduction
Python introductionPython introduction
Python introductionRoger Xia
 
Turning Ideas Into Code Faster
Turning Ideas Into Code FasterTurning Ideas Into Code Faster
Turning Ideas Into Code Fastermeysholdt
 
How to really obfuscate your pdf malware
How to really obfuscate your pdf malwareHow to really obfuscate your pdf malware
How to really obfuscate your pdf malwarezynamics GmbH
 
Structured web programming
Structured web programmingStructured web programming
Structured web programmingahfast
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Fwdays
 
Reflection Madness - Dr. Heinz Kabutz
Reflection Madness - Dr. Heinz KabutzReflection Madness - Dr. Heinz Kabutz
Reflection Madness - Dr. Heinz KabutzJAXLondon2014
 
Smoke and Mirrors - Reflection in C#
Smoke and Mirrors - Reflection in C#Smoke and Mirrors - Reflection in C#
Smoke and Mirrors - Reflection in C#Wekoslav Stefanovski
 
TypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersTypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersRutenis Turcinas
 

Tendances (20)

Intro to Objective C
Intro to Objective CIntro to Objective C
Intro to Objective C
 
Codegeneration Goodies
Codegeneration GoodiesCodegeneration Goodies
Codegeneration Goodies
 
Using Xcore with Xtext
Using Xcore with XtextUsing Xcore with Xtext
Using Xcore with Xtext
 
Python introduction
Python introductionPython introduction
Python introduction
 
Turning Ideas Into Code Faster
Turning Ideas Into Code FasterTurning Ideas Into Code Faster
Turning Ideas Into Code Faster
 
Jvm2
Jvm2Jvm2
Jvm2
 
Guild Prototype
Guild PrototypeGuild Prototype
Guild Prototype
 
Typescript
TypescriptTypescript
Typescript
 
How to really obfuscate your pdf malware
How to really obfuscate your pdf malwareHow to really obfuscate your pdf malware
How to really obfuscate your pdf malware
 
Structured web programming
Structured web programmingStructured web programming
Structured web programming
 
EMF Tips n Tricks
EMF Tips n TricksEMF Tips n Tricks
EMF Tips n Tricks
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
Reflection Madness - Dr. Heinz Kabutz
Reflection Madness - Dr. Heinz KabutzReflection Madness - Dr. Heinz Kabutz
Reflection Madness - Dr. Heinz Kabutz
 
Smoke and Mirrors - Reflection in C#
Smoke and Mirrors - Reflection in C#Smoke and Mirrors - Reflection in C#
Smoke and Mirrors - Reflection in C#
 
TypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersTypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack Developers
 
Overview of CoffeeScript
Overview of CoffeeScriptOverview of CoffeeScript
Overview of CoffeeScript
 
Ahieving Performance C#
Ahieving Performance C#Ahieving Performance C#
Ahieving Performance C#
 
Iphone course 1
Iphone course 1Iphone course 1
Iphone course 1
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
OOP Day 1
OOP Day 1OOP Day 1
OOP Day 1
 

Similaire à C++ Introduction brown bag

2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and ClassesMichael Heron
 
Programming Languages #devcon2013
Programming Languages #devcon2013Programming Languages #devcon2013
Programming Languages #devcon2013Iván Montes
 
CPP13 - Object Orientation
CPP13 - Object OrientationCPP13 - Object Orientation
CPP13 - Object OrientationMichael Heron
 
Csharp introduction
Csharp introductionCsharp introduction
Csharp introductionSireesh K
 
Programming Language
Programming  LanguageProgramming  Language
Programming LanguageAdeel Hamid
 
2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation Fundamentals2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation FundamentalsMichael Heron
 
Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Codersebbe
 
TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!Alessandro Giorgetti
 
introduction to c #
introduction to c #introduction to c #
introduction to c #Sireesh K
 
Introduction to the intermediate Python - v1.1
Introduction to the intermediate Python - v1.1Introduction to the intermediate Python - v1.1
Introduction to the intermediate Python - v1.1Andrei KUCHARAVY
 
CPP02 - The Structure of a Program
CPP02 - The Structure of a ProgramCPP02 - The Structure of a Program
CPP02 - The Structure of a ProgramMichael Heron
 
Data abstraction and object orientation
Data abstraction and object orientationData abstraction and object orientation
Data abstraction and object orientationHoang Nguyen
 
Instagram filters (8 24)
Instagram filters (8 24)Instagram filters (8 24)
Instagram filters (8 24)Ivy Rueb
 
Software Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural PatternsSoftware Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural PatternsSergey Aganezov
 
Summer Training Project On C++
Summer Training Project On  C++Summer Training Project On  C++
Summer Training Project On C++KAUSHAL KUMAR JHA
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building BlocksCate Huston
 

Similaire à C++ Introduction brown bag (20)

2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
 
Programming Languages #devcon2013
Programming Languages #devcon2013Programming Languages #devcon2013
Programming Languages #devcon2013
 
CPP13 - Object Orientation
CPP13 - Object OrientationCPP13 - Object Orientation
CPP13 - Object Orientation
 
Csharp introduction
Csharp introductionCsharp introduction
Csharp introduction
 
Programming Language
Programming  LanguageProgramming  Language
Programming Language
 
Introduction to c ++ part -1
Introduction to c ++   part -1Introduction to c ++   part -1
Introduction to c ++ part -1
 
2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation Fundamentals2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation Fundamentals
 
2CPP02 - C++ Primer
2CPP02 - C++ Primer2CPP02 - C++ Primer
2CPP02 - C++ Primer
 
C++ l 1
C++ l 1C++ l 1
C++ l 1
 
Javasession6
Javasession6Javasession6
Javasession6
 
Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Code
 
TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!
 
introduction to c #
introduction to c #introduction to c #
introduction to c #
 
Introduction to the intermediate Python - v1.1
Introduction to the intermediate Python - v1.1Introduction to the intermediate Python - v1.1
Introduction to the intermediate Python - v1.1
 
CPP02 - The Structure of a Program
CPP02 - The Structure of a ProgramCPP02 - The Structure of a Program
CPP02 - The Structure of a Program
 
Data abstraction and object orientation
Data abstraction and object orientationData abstraction and object orientation
Data abstraction and object orientation
 
Instagram filters (8 24)
Instagram filters (8 24)Instagram filters (8 24)
Instagram filters (8 24)
 
Software Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural PatternsSoftware Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural Patterns
 
Summer Training Project On C++
Summer Training Project On  C++Summer Training Project On  C++
Summer Training Project On C++
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building Blocks
 

Dernier

Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
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
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
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
 
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
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
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
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile EnvironmentVictorSzoltysek
 
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
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
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
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 

Dernier (20)

Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
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
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
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
 
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
 
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 🔝✔️✔️
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
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
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
 
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...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
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
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 

C++ Introduction brown bag

  • 1. An introduction to C++ Prepare yourselves for working with an evolving ‘modern’ language. This presentation will cover important things that you may not know about that I feel will be beneficial to know. I will attempt to be light hearted and informative but this is the first brown bag so be lenient.
  • 2. Overview • C++ key differences • Brief information on the language • Including a mini table of helpful libraries • Pointers! The stack, the heap and what you want. • Allocation types • Nullptr • Allocation types • Header files & Source files • Header directives in C++, What are they and how are they used? • Example of functional C++ class (Header & Source) • Protection levels in C++ (Already partial encountered in C#) • Polymorphism (special thing involving inheritance) • Casting (Boxing in the C# world) • C++ extra top tips to enhance your C++ experience (seriously) I’m aware that some of you have had lessons on C++ so I shall try to omit some recurring slides from the presentation, but the slides I have kept I feel are important to cover again even in brief.
  • 3. C++ Differences • C++ doesn’t have garbage collection. • this is both good and bad because it means you can control more but you have to be careful with what you do. • It is much harder to include external usable code. • In C++ you would have to share the header file with your code base to know of the implementation and potentially have to link the compiled code into your solution (This can really suck at times). • There is some annoying key word re-use • The Const key word literally causes 4 different results depending on where and how you use it. • Templates… These are actually really cool and helpful! • You can create functions that accept and work on multiple types. • Templates are calculated at compile-time (I will get into templates very briefly later) • Polymorphic Casting • Ever been working on something that used inheritance and been like I want this object to be treated as a specific object type. Well you can!
  • 4. Information about the language platform You may be saying. “What is this? Surely there is only one language?”. Nope! The C++ language is actively being developed as such there are multiple compiler versions. But more importantly, there are 2 distributions of the compiler: • GCC (GNU Compiler Collection). An open source compiler distribution. • VC++ (Microsoft Visual C++). Microsoft’s C++ compiler packaged with Visual Studio. If you have used multiple versions of visual studio you have probably used slightly different C++ versions Visual Studio Version Visual C++ Version C++ Distribution Improvements Visual Studio 2010 Visual C++ 10.0 Only partial C++11 support Visual Studio 2012 Visual C++ 11.0 C++ 11 Visual Studio 2013 Visual C++ 12.0 C++ 11 (Supports some of 14) Visual Studio 2015 Visual C++ 14.0 C++ 14 (There is support for some of 17)
  • 5. The standard Library People coming from the C# world are used to a library of functionality they can use. C++ has an actively developed standard library implementation that can be very useful. Just like with C# you have to declare you are using the library. A lot of new things were added to the C++ 11 standard that can be very helpful to new developers. Library Information <regex> Regex library. Allows you to work with patterns and find things from text. <chrono> Time library. Helpful for doing time things… <vector> A specialized container template. <array> An array with additional functionality and supporting features on top of the array. <queue> A queue. First in – first out. <utility> This holds vague utility features such as those required for move semantics (ADVANCED). <iostream> You guys know iostream. Input, output stream, helpful for console and file management. <algorithm> Algorithms for findings data within data. (not to be confused with regex) <map> Map object A with Object B. Very useful tool alongside <set> <string> A string utility for string types. This is nice as the string implementation holds useful things like size. <memory> ADVANCED. Used to access smart pointers.
  • 6. Pointers Magical things! They are used to refer to things strictly by memory you can even have them refer to functions as well as objects. However you must be really careful with how you use them. Declaring a pointer: Creates a pointer object to an object of the type Creating a pointer to an existing object: Example of creating a object and creating a pointer to the object. Dereferencing a pointer: This now is technically the object we were pointing to in memory Getting the address of a pointer: Address of pointer object Getting the address of the object a pointer points to: You need to dereference the pointer before you call the address (&)
  • 7. References References are a type of pointer. Denoted by a & prefix after the type. There are some unique rules and cool features of references. • A reference cannot be NULL. You can assign to it only when you create it. • A reference can’t have it value reassigned. • A reference can only ‘refer’ to a variable with allocated memory (not temporary objects) • Example: Notice the reference doesn’t take a memory address but the dereferenced object. • You cannot have a standard library container of references. As the container expects to be able to allocate and deallocate memory for it’s objects, but a reference is immutable. • A reference to the object lets you treat the object exactly as the original variable • Object& obj = variable; variable.MemberFunction();
  • 8. Nullptr (Pointer default location) You should attempt to always initialize pointers assigned to something. In new C++ the default location that pointers point to when created is NULL (assigned to nullptr), it can be checked using the keyword ‘nullptr’. Nullptr is the correct way to check if a pointer is valid. WARNING: They could still be freely dangling after an object is destroyed. Try to avoid this pattern but if it happens make sure to set the dangling pointer to nullptr. It is very good practice to check your pointers before you use them. You should always check them when the pointers are unknown, E.G a pointer provided to a function as an argument. The example below is going to be safe but is used as a demonstration of its usage. nullptr is a replacement for literal 0 and NULL macros which has historically been used for null pointing pointers. Reminder: Setting pointers to null by default is implementation specific, some implementations could leave them random. • Always initialize your pointers to something, including null. • The compiler will prevent you from creating unassigned pointers by default. • Class construction will initialize unassigned pointer members to NULL for you.
  • 9. Examples of Allocation Don’t underappreciate this slide. There are a lot of bad C++ programmers who only create objects on the heap. I will demonstrate a stack verses a heap allocation. Benefits of using a stack object are that it is faster to allocate and once the object goes out of scope it is destroyed (destructor invoked) automatically for you. Stack Static Allocation(Temporary) Heap Dynamic allocation (Permanent) Technically the same. Compiler should optimize away the copy operation. But be warned all the same.
  • 10. Headers Headers are files that get linked with source files by the compiler • They should only hold the necessary data for compiling. More on this Later • Headers should only hold function declarations not function definitions • Okay not entirely true there are cases where the definition is needed by the header • Inline Code requires definition • Templates requires definition
  • 11. Source Files • These files will need the header files to know the logic about other defined types. • E.G A vehicle source file (Vehicle.cpp) might need the header for People.h if it is to use multiple Person or do anything with a Person type. • Don’t re-declare headers that are included by the source files header file. • This file holds all the implementation and definition logic of you header.
  • 12. Header Directives What are they Technically they are a type of pre-processor directives. They are handled by the pre-processor, consider them like small instructions and directions that are performed initially before the compiler. Important Preprocessors you will encounter Pragma Once This is very important and should appear in nearly all header files. It causes only a single compilation of the source file. Include File Include the file in this compilation unit. The entire file contents is processed with the file. Include Header Include header is used for including header files and system provided files in the compilation unit. “Include Header” and “Include File” are used interchangeably, but you should use the appropriate one for your need.
  • 13. Creating a working class Header file <.h> Source File <.cpp> A very basic example. Notice how the cpp includes the header file that it provides definitions for. Notice how the header file has to have the <string> header to provide a definition of what the string type is because it has a member variable of string type.
  • 14. Protection levels in classes Every thing beneath this is public. Accessible to derived classes and external classes. Special kind of private protection. Only this class and any children derived from this class can access protected members. Pure virtual function. It must be defined in a derived classes, you can’t make an instance of this class only it’s children Private protection. The private members are only available to this class in-particular, not even its children.
  • 15. Polymorphism This is something you will hear about and though it may sound very advanced you will likely see it and in some cases will have used it prior to this lecture. Polymorphism is just a powerful way of using inheritance (that concept I’m sure you are all very familiar with now). Polymorphism can only be done on dynamic types (the heap one). Polymorphism is about treating an object in memory as a different object. The next few slides go into it in detail but here is a very quick example. They are the same exact object in memory. Except they are treated different depending on the type we have declared the pointer.
  • 16. Casting Casting is a method of reinterpreting data as a different type. The most common example is for handling polymorphic objects. You will probably become familiar with the first two. Casting in C++ is probably the first example of a template function you will see (Notice the < > brackets) • 4 Types of casting 1. Static Casting 2. Dynamic Casting 3. Const Casting 4. Reinterpret Casting Implicit Cast Example Explicit Cast Example
  • 17. Static Casting You should only use this if you know the casting type. If you attempt a static_cast on a type which can’t be cast to, your program WILL crash. If you are intending to cast. You will/should probably use this in most cases. The common case being up casting to a base type.
  • 18. Dynamic Casting • Can cast a pointer of type to another pointer of type in runtime • Will return null if the cast is unsuccessful. This is an impossible cast but it is safe because dynamic cast will return a null pointer which I can check before using it. A legal dynamic cast. Though in this case I know exactly what it will be I should have used a static cast (or at least check my dynamic cast)
  • 19. Top Tips Helpful things as a bonus or things that were not as important as the other slides but are worth mentioning. • Iterating over a collection without an index increment. • Forward declare pointers to avoid including files. • If you are using inheritance make your destructor’s virtual. • Initializer lists. • Const usage (ughhhhh) • Parsing by value compared to reference
  • 20. Iterating over a collection If you have a collection of objects like a standard library vector you can iterate over it with out an explicitly declared increment. In this example each iteration over the collection creates a reference (Non-null pointer) to the element of the container. • Don’t have to keep track of iterating over the loop. • Easier to access the elements within the container this way. • Few other benefits that can be found by experimenting with its usage.
  • 21. Forward declaring pointer types • This is more of a standard than a tip. It is highly encouraged that header files should only include files if the declared class needs to know about the type. • Pointers are guaranteed to be a fixed size (4 Bytes) so the class implementing the pointer doesn’t need to know the type. • The source file (cpp) will still need the header for what the type is meant to be to use it.
  • 22. Virtual destructors This specifically related to polymorphism and inheritance. Calling delete on a base object that has been created from a derived object will result in only the base version of the destructor being called. This causes a memory leak as the child class is never deleted. Using a virtual destructor fixes this and ensures the derived objects destructor is invoked if delete is called on the base object. ALWAYS HAVE A VIRTUAL DESTRUCTOR IN PARENT CLASSES THAT USE INHERITANCE. Or make the destructor protected in the base class so you can’t call delete on the base object.
  • 23. Initializer lists Most of you are probably familiar with creating an object like this: In C++ You can initialize members like this: An initializer list is just a bunch of constructor calls to be completed before the main object (in this Case Rectangle) is created. There are advantages of doing it like this. If you had object classes as a member (variable) inside Rectangle it would attempt to call a default constructor first. This method lets you handle the member construction instead yourself. A good example of its use is to set References (things from earlier) before your object gets constructed; if you don’t the compiler will complain that the reference is null (not set) when constructed.
  • 24. Const usage Const has a few different meanings depending on how you use it. It can quite easily become confusing. Basically a const to the right of something means that ‘thing’ cannot change while to the left means that ‘thing’ is a const ‘thing’. A simple const int. Must be initialized to value when created. A int pointer that is constant. The pointer can not be reassigned. A method that takes a const int. Method takes an int type but the method cannot change the value of the int. A const function. This function does not allow the function to change the class.
  • 25. Passing by value or reference A method parameter is basically a variable that gets constructed from arguments provided to the method. By comparison C# would always* pass by reference. So consider what your method should be doing. Copying (value): DoThingToObject(Type object); Reference: DoThingToObject(Type& object_ref); Pointer: DoThingToObject(Type* object_pointer); *always except in the case of primitive types (integers, floats, etc) which were passed by value (copied).
  • 26. More advanced stuff! Don’t trouble your heads too much with this stuff. Some of it is so advanced there are whole talks(by more qualified people) on the subjects. • Advanced Templating • Variance templates • Templating full classes not just functions • Lambda Functions • Aka mini-functions created in code. • Std::bind and std::function • Special types of code wrappers that can be invoked to call logic outside the callers scope. • Yes these two types have different usage. • Smart pointers • Helpful tools for managing memory for you. • There are costs and trade offs for which ones you use. • Move semantics • More efficient memory management.