Quick C++ Tutorial
Quick C++ Tutorial
Rob Jagnow
This tutorial will be best for students who have at least had some exposure to Java or another comparable programming language.
Overview
• Pointers
• Arrays and strings
• Parameter passing
• Class basics
• Constructors & destructors
• Class Hierarchy
• Virtual Functions
• Coding tips
• Advanced topics
Advanced topics: friends, protected, inline functions, const, static, virtual inheritance, pure virtual function (e.g. Intersect(ray, hit) = 0), class hierarchy.
Pointers
int *intPtr; Create a pointer
*intPtr 5 otherVal
intPtr 0x0054 &otherVal
Arrays
Stack allocation
int intArray[10];
intArray[0] = 6837;
Heap allocation
int *intArray;
intArray = new int[10];
intArray[0] = 6837;
...
delete[] intArray;
int a, b, sum;
sum = add(a, b);
pass by reference
int add(int *a, int *b) { Pass pointers that reference
return *a + *b; a & b. Changes made to a
} or b will be reflected
int a, b, sum;
outside the add routine
sum = add(&a, &b);
Parameter Passing
pass by reference – alternate notation
int a, b, sum;
sum = add(a, b);
Class Basics
#ifndef _IMAGE_H_ Prevents multiple references
#define _IMAGE_H_
#endif
Note that “private:” is the default
Creating an instance
Stack allocation
Image myImage;
myImage.SetAllPixels(ClearColor);
Heap allocation
Image *imagePtr;
imagePtr = new Image();
imagePtr->SetAllPixels(ClearColor);
...
delete imagePtr;
Stack allocation: Constructor and destructor called automatically when the function is entered and exited.
Heap allocation: Constructor and destructor must be called explicitly.
Organizational Strategy
image.h Header file: Class definition & function prototypes
void SetAllPixels(const Vec3f &color);
myImage.SetAllPixels(clearColor);
Constructors & Destructors
class Image {
public:
Image(void) { Constructor:
width = height = 0; Called whenever a new
data = NULL; instance is created
}
~Image(void) {
Destructor:
if (data != NULL)
delete[] data; Called whenever an
} instance is deleted
int width;
int height;
Vec3f *data;
};
Constructors
Constructors can also take parameters
Image(int w, int h) {
width = w;
height = h;
data = new Vec3f[w*h];
}
Image *imagePtr;
imagePtr = new Image(10, 10); 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] = new data[i];
}
Warning: if you do not create a default (void parameter) or copy constructor explicitly, they are created for you.
Passing Classes as Parameters
If a class instance is passed by reference, the copy constructor
will be used to make a copy.
Computationally expensive
class Object3D {
virtual void intersect(Vec3f *ray, Vec3f *hit);
};
Number of Array of
arguments strings