C++ TutorialOverviewPointersArraysStringsParameter PassingSlide 7Class BasicsCreating an instanceOrganizational StrategyConstructors & DestructorsConstructorsThe Copy ConstructorPassing Classes as ParametersClass HierarchySlide 16Virtual FunctionsThe main functionCoding tips“Segmentation fault (core dumped)”Advanced topicsC++ TutorialRob JagnowOverview•Pointers•Arrays and strings•Parameter passing•Class basics•Constructors & destructors•Class Hierarchy•Virtual Functions•Coding tips•Advanced topicsPointersint *intPtr;intPtr = new int;*intPtr = 6837;delete intPtr;int otherVal = 5;intPtr = &otherVal;Create a pointerAllocate memorySet value at given addressChange intPtr to point toa new location6837*intPtr0x0050 intPtr5*intPtr0x0054 intPtr otherVal&otherValDeallocate memoryArraysint intArray[10];intArray[0] = 6837;int *intArray;intArray = new int[10];intArray[0] = 6837;...delete[] intArray;Stack allocationHeap allocationStringschar myString[20];strcpy(myString, "Hello World");myString[0] = 'H';myString[1] = 'i';myString[2] = '\0';printf("%s", myString);A string in C++ is an array of charactersStrings are terminated with the NULL or '\0' characteroutput: HiParameter Passingint add(int a, int b) { return a+b;}int a, b, sum;sum = add(a, b);pass by valueint add(int *a, int *b) { return *a + *b;}int a, b, sum;sum = add(&a, &b);pass by referenceMake a local copy of a & bPass pointers that reference a & b. Changes made to a or b will be reflected outside the add routineParameter Passingint add(int &a, int &b) { return a+b;}int a, b, sum;sum = add(a, b);pass by reference – alternate notationClass Basics#ifndef _IMAGE_H_#define _IMAGE_H_#include <assert.h> #include "vectors.h“class Image {public: ...private: ...};#endifInclude a library fileInclude a local filePrevents multiple referencesVariables and functionsaccessible from anywhereVariables and functions accessibleonly from within this classCreating an instanceImage myImage;myImage.SetAllPixels(ClearColor);Image *imagePtr;imagePtr = new Image();imagePtr->SetAllPixels(ClearColor);...delete imagePtr;Stack allocationHeap allocationOrganizational Strategyimage.hHeader file: Class definition & function prototypes.C file: Full function definitionsMain code: Function referencesimage.Cmain.Cvoid 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 & Destructorsclass 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 newinstance is createdDestructor:Called whenever aninstance is deletedConstructorsImage(int w, int h) { width = w; height = h; data = new Vec3f[w*h];}Constructors can also take parametersImage myImage = Image(10, 10);Image *imagePtr;imagePtr = new Image(10, 10);Using this constructor with stack or heap allocation:stack allocationheap allocationThe Copy ConstructorImage(Image *img) { width = img->width; height = img->height; data = new Vec3f[width*height]; for (int i=0; i<width*height; i++) data[i] = new data[i];}Image(Image *img) { width = img->width; height = img->height; data = img->data;}A default copy constructor is created automatically,but it is usually not what you want:Passing Classes as Parametersbool IsImageGreen(Image img);If a class instance is passed by reference, the copy constructor will be used to make a copy.Computationally expensivebool IsImageGreen(Image *img);It’s much faster to pass by reference:bool IsImageGreen(Image &img);orClass Hierarchyclass Object3D { Vec3f color;};class Sphere : public Object3D { float radius;};class Cone : public Object3D { float base; float height;};Child classes inherit parent attributesObject3DSphere ConeClass HierarchySphere::Sphere() : Object3D() { radius = 1.0;}Child classes can cal l parent functionsChild classes can override parent functionsclass Object3D { virtual void setDefaults(void) { color = RED; }};class Sphere : public Object3D { void setDefaults(void) { color = BLUE; radius = 1.0 }};Call the parent constructorVirtual Functionsclass Object3D { virtual void intersect(Vec3f *ray, Vec3f *hit);};class Sphere : public Object3D { virtual void intersect(Vec3f *ray, Vec3f *hit);};myObject->intersect(ray, hit);If a superclass has virtual functions, the correct subclass version will automatically be selectedSphere *mySphere = new Sphere();Object3D *myObject = mySphere;A superclass pointer can reference a subclass objectActually calls Sphere::intersectSuperclassSubclassThe main functionint main(int argc, char** argv);This is where your code begins executionNumber of argumentsArray of stringsargv[0] is the program nameargv[1] through argv[argc-1] are command-line inputCoding tips#define PI 3.14159265#define sinf sinUse the #define compiler directive for constantsprintf("value: %d, %f\n", myInt, myFloat);cout << "value:" << myInt << ", " << myFloat << endl;Use the printf or cout functions for output and debuggingassert(denominator != 0);quotient = numerator/denominator;Use the assert function to test “always true” conditions“Segmentation fault (core dumped)”int intArray[10];intArray[10] = 6837;Image *img;img->SetAllPixels(ClearColor);Typical causes:Access outside ofarray boundsAttempt to accessa NULL or previouslydeleted pointerThese errors are often very difficult to catch and can cause erratic, unpredictable behavior.Advanced topicsLots of advanced topics, but few will be required for this course• friend or protected class members• inline functions• const or static functions and variables• pure virtual functionsvirtual void Intersect(Ray &r, Hit &h) = 0;• compiler directives• operator overloadingVec3f& operator+(Vec3f &a, Vec3f
View Full Document