SlideShare una empresa de Scribd logo
1 de 25
C ++  Tutorial Rob Jagnow
Overview ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Pointers int *intPtr; intPtr = new int; * intPtr = 6837; delete intPtr; int otherVal = 5; intPtr =  & otherVal; Create a pointer Allocate memory Set value at given address Change  intPtr  to point to a new location 6837 * intPtr 0x0050 intPtr 5 * intPtr 0x0054 intPtr otherVal & otherVal Deallocate memory
Arrays int intArray[10]; intArray[0] = 6837; int *intArray; intArray = new int[10]; intArray[0] = 6837; ... delete[] intArray; Stack allocation Heap allocation
Strings char myString[20]; strcpy(myString, "Hello World"); myString[0] = 'H'; myString[1] = 'i'; myString[2] = ''; printf("%s", myString); A string in C++ is an array of characters Strings are terminated with the  NULL  or  ''  character output:  Hi
Parameter Passing int add(int a, int b) { return a+b; } int a, b, sum; sum = add(a, b); pass by value int add(int *a, int *b) { return *a + *b; } int a, b, sum; sum = add(&a, &b); pass by reference Make a local copy of  a  and  b Pass pointers that reference  a  and  b .  Changes made to  a  or  b  will be reflected outside the  add  routine
Parameter Passing int add(int &a, int &b) { return a+b; } int a, b, sum; sum = add(a, b); pass by reference – alternate notation
Class Basics #ifndef _IMAGE_H_ #define _IMAGE_H_ #include <assert.h>  #include &quot;vectors.h“ class Image { public: ... private: ... }; #endif Include a library file Include a local file Prevents multiple references Variables and functions accessible from anywhere Variables and functions accessible only from within this class’s functions
Creating an instance Image myImage; myImage . SetAllPixels(ClearColor); Image *imagePtr; imagePtr = new Image(); imagePtr -> SetAllPixels(ClearColor); ... delete imagePtr; Stack allocation Heap allocation
Organizational Strategy image.h Header file: Class definition & function prototypes .C file: Full function definitions Main code: Function references image.C main.C void SetAllPixels(const Vec3f &color); void Image::SetAllPixels(const Vec3f &color) { for (int i = 0; i < width*height; i++) data[i] = color; } myImage.SetAllPixels(clearColor);
Constructors & Destructors class Image { public: Image(void) { width = height = 0; data = NULL; } ~Image(void) { if (data != NULL) delete[] data; } int width; int height; Vec3f *data; }; Constructor: Called whenever a new instance is created Destructor: Called whenever an instance is deleted
Constructors Image(int w, int h) { width = w; height = h; data = new Vec3f[w*h]; } Constructors can also take parameters Image myImage = Image(10, 10); Image *imagePtr; imagePtr = new Image(10, 10); Using this constructor with stack or heap allocation: stack allocation heap allocation
The Copy Constructor Image(Image *img) { width = img->width; height = img->height; data = new Vec3f[width*height]; for (int i=0; i<width*height; i++) data[i] = img->data[i]; } Image(Image *img) { width = img->width; height = img->height; data = img->data; } A default copy constructor is created automatically, but it is often not what you want:
Passing Classes as Parameters bool IsImageGreen(Image img); If a class instance is passed by value, the copy constructor will be used to make a copy. Computationally expensive bool IsImageGreen(Image *img); It’s much faster to pass by reference: bool IsImageGreen(Image &img); or
Class Hierarchy class Object3D { Vec3f color; }; class Sphere : public Object3D { float radius; }; class Cone : public Object3D { float base; float height; }; Child classes inherit parent attributes Object3D Sphere Cone
Class Hierarchy Sphere::Sphere() : Object3D() { radius = 1.0; } Child classes can  call  parent functions Child classes can  override  parent functions class Object3D { virtual void setDefaults(void) { color = RED; } }; class Sphere : public Object3D { void setDefaults(void) { color = BLUE; radius = 1.0 } }; Call the parent constructor Superclass Subclass
Virtual Functions class Object3D { virtual void intersect(Ray *r, Hit *h); }; class Sphere : public Object3D { virtual void intersect(Ray *r, Hit *h); }; myObject->intersect(ray, hit); If a superclass has virtual functions, the correct subclass version will automatically be selected Sphere *mySphere = new Sphere(); Object3D *myObject = mySphere; A superclass pointer can reference a subclass object Actually calls  Sphere::intersect Superclass Subclass
Pure Virtual Functions class Object3D { virtual void intersect(Ray *r, Hit *h)  = 0 ; }; A  pure virtual function  has a prototype, but no definition.  Used when a default implementation does not make sense. A class with a pure virtual function is called a  pure virtual class  and cannot be instantiated. (However, its subclasses can).
The  main  function int main(int argc, char** argv); This is where your code begins execution Number of arguments Array of strings argv[0]  is the program name argv[1]  through  argv[argc-1]  are command-line input
Coding tips #define PI 3.14159265 #define MAX_ARRAY_SIZE 20 Use the  #define  compiler directive for constants printf(&quot;value: %d, %f&quot;, myInt, myFloat); cout << &quot;value:&quot; << myInt << &quot;, &quot; << myFloat << endl; Use the  printf  or  cout  functions for output and debugging assert(denominator != 0); quotient = numerator/denominator; Use the  assert  function to test “always true” conditions
Coding tips delete myObject; myObject = NULL; After you  delete  an object, also set its value to  NULL  (This is not done for you automatically) This will make it easier to debug memory allocation errors assert(myObject != NULL); myObject->setColor(RED);
Segmentation fault (core dumped) int intArray[10]; intArray[10] = 6837; Image *img; img->SetAllPixels(ClearColor); Typical causes: Access outside of array bounds Attempt to access a  NULL  or previously deleted pointer These errors are often very difficult to catch and can cause erratic, unpredictable behavior.
Common Pitfalls void setToRed(Vec3f v) { v = RED; } Since  v  is passed by value, it will not get updated outside of The  set  function The fix: void setToRed(Vec3f  & v) { v = RED; } void setToRed(Vec3f  * v) { * v = RED; } or
Common Pitfalls Sphere* getRedSphere() { Sphere s = Sphere(1.0); s.setColor(RED); return &s; } C++ automatically deallocates stack memory when the function exits, so the returned pointer is invalid.  The fix: Sphere* getRedSphere() { Sphere  * s =  new  Sphere(1.0); s -> setColor(RED); return  s ; } It will then be your responsibility to delete the Sphere object later.
Advanced topics ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

Más contenido relacionado

La actualidad más candente

Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design PatternsStefano Fago
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Sameer Rathoud
 
C++11 smart pointer
C++11 smart pointerC++11 smart pointer
C++11 smart pointerLei Yu
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Abu Saleh
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITEgor Bogatov
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)hhliu
 
Advanced python
Advanced pythonAdvanced python
Advanced pythonEU Edge
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.Russell Childs
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 
C tech questions
C tech questionsC tech questions
C tech questionsvijay00791
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
 
Data Structure Project File
Data Structure Project FileData Structure Project File
Data Structure Project FileDeyvessh kumar
 

La actualidad más candente (20)

Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
 
C++11 smart pointer
C++11 smart pointerC++11 smart pointer
C++11 smart pointer
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
 
Smart pointers
Smart pointersSmart pointers
Smart pointers
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
Advanced python
Advanced pythonAdvanced python
Advanced python
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
Advance java
Advance javaAdvance java
Advance java
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
Smart Pointers in C++
Smart Pointers in C++Smart Pointers in C++
Smart Pointers in C++
 
Unit 3
Unit 3 Unit 3
Unit 3
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
C tech questions
C tech questionsC tech questions
C tech questions
 
Lecture 12: Classes and Files
Lecture 12: Classes and FilesLecture 12: Classes and Files
Lecture 12: Classes and Files
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
cluster(python)
cluster(python)cluster(python)
cluster(python)
 
Smart Pointers
Smart PointersSmart Pointers
Smart Pointers
 
Data Structure Project File
Data Structure Project FileData Structure Project File
Data Structure Project File
 

Destacado

PARAMETER PASSING MECHANISMS
PARAMETER PASSING MECHANISMSPARAMETER PASSING MECHANISMS
PARAMETER PASSING MECHANISMSArpee Callejo
 
שימו לב לסגול הרועד
שימו לב לסגול הרועדשימו לב לסגול הרועד
שימו לב לסגול הרועדnirit68
 
Welcome in Turin
Welcome in TurinWelcome in Turin
Welcome in Turinenzoppi
 
Towards a malaria-free world - Background information
Towards a malaria-free world - Background informationTowards a malaria-free world - Background information
Towards a malaria-free world - Background informationXplore Health
 
Neurox Overview
Neurox OverviewNeurox Overview
Neurox Overviewrock1110
 
Tools of the Trade
Tools of the TradeTools of the Trade
Tools of the Tradejmori1
 
Power Notes - Phase Changes
Power Notes - Phase ChangesPower Notes - Phase Changes
Power Notes - Phase Changesjmori1
 
Juego con vene
Juego con veneJuego con vene
Juego con veneDaisneidy
 
แนะนำทุน พสวท.
แนะนำทุน พสวท.แนะนำทุน พสวท.
แนะนำทุน พสวท.yingsinee
 
Power Notes: Measurements and Dealing with Data-2011
Power Notes:   Measurements and Dealing with Data-2011Power Notes:   Measurements and Dealing with Data-2011
Power Notes: Measurements and Dealing with Data-2011jmori1
 
Koppelen en doorschakelen definitief[1]
Koppelen en doorschakelen   definitief[1]Koppelen en doorschakelen   definitief[1]
Koppelen en doorschakelen definitief[1]Mieke Sanden, van der
 
My life
My lifeMy life
My lifedcbabb
 

Destacado (20)

PARAMETER PASSING MECHANISMS
PARAMETER PASSING MECHANISMSPARAMETER PASSING MECHANISMS
PARAMETER PASSING MECHANISMS
 
Adco teaser
Adco teaserAdco teaser
Adco teaser
 
שימו לב לסגול הרועד
שימו לב לסגול הרועדשימו לב לסגול הרועד
שימו לב לסגול הרועד
 
Welcome in Turin
Welcome in TurinWelcome in Turin
Welcome in Turin
 
Towards a malaria-free world - Background information
Towards a malaria-free world - Background informationTowards a malaria-free world - Background information
Towards a malaria-free world - Background information
 
Unit 7 y 8
Unit 7 y 8Unit 7 y 8
Unit 7 y 8
 
Neurox Overview
Neurox OverviewNeurox Overview
Neurox Overview
 
Tools of the Trade
Tools of the TradeTools of the Trade
Tools of the Trade
 
Power Notes - Phase Changes
Power Notes - Phase ChangesPower Notes - Phase Changes
Power Notes - Phase Changes
 
Juego con vene
Juego con veneJuego con vene
Juego con vene
 
Module 1
Module 1Module 1
Module 1
 
แนะนำทุน พสวท.
แนะนำทุน พสวท.แนะนำทุน พสวท.
แนะนำทุน พสวท.
 
Power Notes: Measurements and Dealing with Data-2011
Power Notes:   Measurements and Dealing with Data-2011Power Notes:   Measurements and Dealing with Data-2011
Power Notes: Measurements and Dealing with Data-2011
 
GO-YOLI BUSINESS
GO-YOLI BUSINESSGO-YOLI BUSINESS
GO-YOLI BUSINESS
 
Koppelen en doorschakelen definitief[1]
Koppelen en doorschakelen   definitief[1]Koppelen en doorschakelen   definitief[1]
Koppelen en doorschakelen definitief[1]
 
My life
My lifeMy life
My life
 
1 16
1 161 16
1 16
 
Cd y ci
Cd y ciCd y ci
Cd y ci
 
Andrés bio
Andrés   bioAndrés   bio
Andrés bio
 
Am 02 osac_kt_swift
Am 02 osac_kt_swiftAm 02 osac_kt_swift
Am 02 osac_kt_swift
 

Similar a C++ Tutorial Guide with Pointers, Arrays, Classes, Inheritance and More

Cppt 101102014428-phpapp01
Cppt 101102014428-phpapp01Cppt 101102014428-phpapp01
Cppt 101102014428-phpapp01Getachew Ganfur
 
C++totural file
C++totural fileC++totural file
C++totural filehalaisumit
 
Learn D3.js in 90 minutes
Learn D3.js in 90 minutesLearn D3.js in 90 minutes
Learn D3.js in 90 minutesJos Dirksen
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumlercorehard_by
 
Dotnet unit 4
Dotnet unit 4Dotnet unit 4
Dotnet unit 4007laksh
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxDeepasCSE
 
OOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxOOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxSirRafiLectures
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...DroidConTLV
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesAndrey Karpov
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
 
C++ AMP 실천 및 적용 전략
C++ AMP 실천 및 적용 전략 C++ AMP 실천 및 적용 전략
C++ AMP 실천 및 적용 전략 명신 김
 
C++tutorial
C++tutorialC++tutorial
C++tutorialdips17
 
Creating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdfCreating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdfShaiAlmog1
 
CPP-overviews notes variable data types notes
CPP-overviews notes variable data types notesCPP-overviews notes variable data types notes
CPP-overviews notes variable data types notesSukhpreetSingh519414
 

Similar a C++ Tutorial Guide with Pointers, Arrays, Classes, Inheritance and More (20)

Cppt 101102014428-phpapp01
Cppt 101102014428-phpapp01Cppt 101102014428-phpapp01
Cppt 101102014428-phpapp01
 
C++totural file
C++totural fileC++totural file
C++totural file
 
C++ tutorial
C++ tutorialC++ tutorial
C++ tutorial
 
Learn D3.js in 90 minutes
Learn D3.js in 90 minutesLearn D3.js in 90 minutes
Learn D3.js in 90 minutes
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumler
 
Dotnet unit 4
Dotnet unit 4Dotnet unit 4
Dotnet unit 4
 
Java Generics
Java GenericsJava Generics
Java Generics
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
 
Managing console
Managing consoleManaging console
Managing console
 
OOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxOOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptx
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error Examples
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 
Day 1
Day 1Day 1
Day 1
 
C++ AMP 실천 및 적용 전략
C++ AMP 실천 및 적용 전략 C++ AMP 실천 및 적용 전략
C++ AMP 실천 및 적용 전략
 
C++tutorial
C++tutorialC++tutorial
C++tutorial
 
Creating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdfCreating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdf
 
Chp4(ref dynamic)
Chp4(ref dynamic)Chp4(ref dynamic)
Chp4(ref dynamic)
 
CPP-overviews notes variable data types notes
CPP-overviews notes variable data types notesCPP-overviews notes variable data types notes
CPP-overviews notes variable data types notes
 

Más de FALLEE31188 (20)

Lecture4
Lecture4Lecture4
Lecture4
 
Lecture2
Lecture2Lecture2
Lecture2
 
L16
L16L16
L16
 
L2
L2L2
L2
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Functions
FunctionsFunctions
Functions
 
Field name
Field nameField name
Field name
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
Cis068 08
Cis068 08Cis068 08
Cis068 08
 
Chapter14
Chapter14Chapter14
Chapter14
 
Chapt03
Chapt03Chapt03
Chapt03
 
C++lecture9
C++lecture9C++lecture9
C++lecture9
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphism
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
C1320prespost
C1320prespostC1320prespost
C1320prespost
 
Brookshear 06
Brookshear 06Brookshear 06
Brookshear 06
 
Book ppt
Book pptBook ppt
Book ppt
 
Assignment 2
Assignment 2Assignment 2
Assignment 2
 
Assignment
AssignmentAssignment
Assignment
 

Último

Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 

Último (20)

Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 

C++ Tutorial Guide with Pointers, Arrays, Classes, Inheritance and More

  • 1. C ++ Tutorial Rob Jagnow
  • 2.
  • 3. Pointers int *intPtr; intPtr = new int; * intPtr = 6837; delete intPtr; int otherVal = 5; intPtr = & otherVal; Create a pointer Allocate memory Set value at given address Change intPtr to point to a new location 6837 * intPtr 0x0050 intPtr 5 * intPtr 0x0054 intPtr otherVal & otherVal Deallocate memory
  • 4. Arrays int intArray[10]; intArray[0] = 6837; int *intArray; intArray = new int[10]; intArray[0] = 6837; ... delete[] intArray; Stack allocation Heap allocation
  • 5. Strings char myString[20]; strcpy(myString, &quot;Hello World&quot;); myString[0] = 'H'; myString[1] = 'i'; myString[2] = ''; printf(&quot;%s&quot;, myString); A string in C++ is an array of characters Strings are terminated with the NULL or '' character output: Hi
  • 6. Parameter Passing int add(int a, int b) { return a+b; } int a, b, sum; sum = add(a, b); pass by value int add(int *a, int *b) { return *a + *b; } int a, b, sum; sum = add(&a, &b); pass by reference Make a local copy of a and b Pass pointers that reference a and b . Changes made to a or b will be reflected outside the add routine
  • 7. Parameter Passing int add(int &a, int &b) { return a+b; } int a, b, sum; sum = add(a, b); pass by reference – alternate notation
  • 8. Class Basics #ifndef _IMAGE_H_ #define _IMAGE_H_ #include <assert.h> #include &quot;vectors.h“ class Image { public: ... private: ... }; #endif Include a library file Include a local file Prevents multiple references Variables and functions accessible from anywhere Variables and functions accessible only from within this class’s functions
  • 9. Creating an instance Image myImage; myImage . SetAllPixels(ClearColor); Image *imagePtr; imagePtr = new Image(); imagePtr -> SetAllPixels(ClearColor); ... delete imagePtr; Stack allocation Heap allocation
  • 10. Organizational Strategy image.h Header file: Class definition & function prototypes .C file: Full function definitions Main code: Function references image.C main.C void SetAllPixels(const Vec3f &color); void Image::SetAllPixels(const Vec3f &color) { for (int i = 0; i < width*height; i++) data[i] = color; } myImage.SetAllPixels(clearColor);
  • 11. Constructors & Destructors class Image { public: Image(void) { width = height = 0; data = NULL; } ~Image(void) { if (data != NULL) delete[] data; } int width; int height; Vec3f *data; }; Constructor: Called whenever a new instance is created Destructor: Called whenever an instance is deleted
  • 12. Constructors Image(int w, int h) { width = w; height = h; data = new Vec3f[w*h]; } Constructors can also take parameters Image myImage = Image(10, 10); Image *imagePtr; imagePtr = new Image(10, 10); Using this constructor with stack or heap allocation: stack allocation heap allocation
  • 13. The Copy Constructor Image(Image *img) { width = img->width; height = img->height; data = new Vec3f[width*height]; for (int i=0; i<width*height; i++) data[i] = img->data[i]; } Image(Image *img) { width = img->width; height = img->height; data = img->data; } A default copy constructor is created automatically, but it is often not what you want:
  • 14. Passing Classes as Parameters bool IsImageGreen(Image img); If a class instance is passed by value, the copy constructor will be used to make a copy. Computationally expensive bool IsImageGreen(Image *img); It’s much faster to pass by reference: bool IsImageGreen(Image &img); or
  • 15. Class Hierarchy class Object3D { Vec3f color; }; class Sphere : public Object3D { float radius; }; class Cone : public Object3D { float base; float height; }; Child classes inherit parent attributes Object3D Sphere Cone
  • 16. Class Hierarchy Sphere::Sphere() : Object3D() { radius = 1.0; } Child classes can call parent functions Child classes can override parent functions class Object3D { virtual void setDefaults(void) { color = RED; } }; class Sphere : public Object3D { void setDefaults(void) { color = BLUE; radius = 1.0 } }; Call the parent constructor Superclass Subclass
  • 17. Virtual Functions class Object3D { virtual void intersect(Ray *r, Hit *h); }; class Sphere : public Object3D { virtual void intersect(Ray *r, Hit *h); }; myObject->intersect(ray, hit); If a superclass has virtual functions, the correct subclass version will automatically be selected Sphere *mySphere = new Sphere(); Object3D *myObject = mySphere; A superclass pointer can reference a subclass object Actually calls Sphere::intersect Superclass Subclass
  • 18. Pure Virtual Functions class Object3D { virtual void intersect(Ray *r, Hit *h) = 0 ; }; A pure virtual function has a prototype, but no definition. Used when a default implementation does not make sense. A class with a pure virtual function is called a pure virtual class and cannot be instantiated. (However, its subclasses can).
  • 19. The main function int main(int argc, char** argv); This is where your code begins execution Number of arguments Array of strings argv[0] is the program name argv[1] through argv[argc-1] are command-line input
  • 20. Coding tips #define PI 3.14159265 #define MAX_ARRAY_SIZE 20 Use the #define compiler directive for constants printf(&quot;value: %d, %f&quot;, myInt, myFloat); cout << &quot;value:&quot; << myInt << &quot;, &quot; << myFloat << endl; Use the printf or cout functions for output and debugging assert(denominator != 0); quotient = numerator/denominator; Use the assert function to test “always true” conditions
  • 21. Coding tips delete myObject; myObject = NULL; After you delete an object, also set its value to NULL (This is not done for you automatically) This will make it easier to debug memory allocation errors assert(myObject != NULL); myObject->setColor(RED);
  • 22. Segmentation fault (core dumped) int intArray[10]; intArray[10] = 6837; Image *img; img->SetAllPixels(ClearColor); Typical causes: Access outside of array bounds Attempt to access a NULL or previously deleted pointer These errors are often very difficult to catch and can cause erratic, unpredictable behavior.
  • 23. Common Pitfalls void setToRed(Vec3f v) { v = RED; } Since v is passed by value, it will not get updated outside of The set function The fix: void setToRed(Vec3f & v) { v = RED; } void setToRed(Vec3f * v) { * v = RED; } or
  • 24. Common Pitfalls Sphere* getRedSphere() { Sphere s = Sphere(1.0); s.setColor(RED); return &s; } C++ automatically deallocates stack memory when the function exits, so the returned pointer is invalid. The fix: Sphere* getRedSphere() { Sphere * s = new Sphere(1.0); s -> setColor(RED); return s ; } It will then be your responsibility to delete the Sphere object later.
  • 25.

Notas del editor

  1. This tutorial will be best for students who have at least had some exposure to Java or another comparable programming language.
  2. Advanced topics: friends, protected, inline functions, const, static, virtual inheritance, pure virtual function (e.g. Intersect(ray, hit) = 0), class hierarchy.
  3. C++ arrays are zero-indexed.
  4. Note that “private:” is the default
  5. Stack allocation: Constructor and destructor called automatically when the function is entered and exited. Heap allocation: Constructor and destructor must be called explicitly.
  6. Warning: if you do not create a default (void parameter) or copy constructor explicitly, they are created for you.