C++ Introduction brown bag

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.

Transcript of C++ Introduction brown bag

Page 1: C++ Introduction brown bag

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.

Page 2: C++ Introduction brown bag

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.

Page 3: C++ Introduction brown bag

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!

Page 4: C++ Introduction brown bag

Information about the language platformYou 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)

Page 5: C++ Introduction brown bag

The standard LibraryPeople 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.

Page 6: C++ Introduction brown bag

PointersMagical 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 (&)

Page 7: C++ Introduction brown bag

ReferencesReferences 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();

Page 8: C++ Introduction brown bag

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.

Page 9: C++ Introduction brown bag

Examples of AllocationDon’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.

Page 10: C++ Introduction brown bag

HeadersHeaders 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

Page 11: C++ Introduction brown bag

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.

Page 12: C++ Introduction brown bag

Header DirectivesWhat 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.

Page 13: C++ Introduction brown bag

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.

Page 14: C++ Introduction brown bag

Protection levels in classesEvery 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.

Page 15: C++ Introduction brown bag

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

Page 16: C++ Introduction brown bag

CastingCasting 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 casting1. Static Casting2. Dynamic Casting3. Const Casting4. Reinterpret Casting

Implicit Cast Example Explicit Cast Example

Page 17: C++ Introduction brown bag

Static CastingYou 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.

Page 18: C++ Introduction brown bag

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)

Page 19: C++ Introduction brown bag

Top TipsHelpful 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

Page 20: C++ Introduction brown bag

Iterating over a collectionIf 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.

Page 21: C++ Introduction brown bag

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.

Page 22: C++ Introduction brown bag

Virtual destructorsThis 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.

Page 23: C++ Introduction brown bag

Initializer listsMost 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.

Page 24: C++ Introduction brown bag

Const usageConst 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.

Page 25: C++ Introduction brown bag

Passing by value or referenceA 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).

Page 26: C++ Introduction brown bag

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.