0% found this document useful (0 votes)
20 views25 pages

C++ Tutorial by Rob Jagnow

This document provides a summary of key C++ concepts: - It outlines pointers, arrays, parameter passing, classes, constructors/destructors, class hierarchies, virtual functions, and coding tips. - The main topics covered include pointers and dynamic memory allocation, classes and objects, inheritance and polymorphism, and common programming pitfalls. - Advanced C++ topics like templates, operator overloading, and exceptions are also mentioned but not covered in detail.

Uploaded by

ravi90
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views25 pages

C++ Tutorial by Rob Jagnow

This document provides a summary of key C++ concepts: - It outlines pointers, arrays, parameter passing, classes, constructors/destructors, class hierarchies, virtual functions, and coding tips. - The main topics covered include pointers and dynamic memory allocation, classes and objects, inheritance and polymorphism, and common programming pitfalls. - Advanced C++ topics like templates, operator overloading, and exceptions are also mentioned but not covered in detail.

Uploaded by

ravi90
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

C++ Tutorial

Rob Jagnow

Overview

Pointers
Arrays and strings
Parameter passing
Class basics
Constructors & destructors
Class Hierarchy
Virtual Functions
Coding tips
Advanced topics

Pointers
int *intPtr;

Create a pointer

intPtr = new int;

Allocate memory

*intPtr = 6837;

Set value at given address


6837

*intPtr
intPtr

0x0050

delete intPtr;

Deallocate memory

int otherVal = 5;
intPtr = &otherVal;

Change intPtr to point to


a new location

*intPtr
intPtr

5
0x0054

otherVal
&otherVal

Arrays
Stack allocation
int intArray[10];
intArray[0] = 6837;

Heap allocation
int *intArray;
intArray = new int[10];
intArray[0] = 6837;
...
delete[] intArray;

Strings
A string in C++ is an array of characters
char myString[20];
strcpy(myString, "Hello World");

Strings are terminated with the NULL or '\0' character


myString[0] = 'H';
myString[1] = 'i';
myString[2] = '\0';
printf("%s", myString);

output: Hi

Parameter Passing
pass by value
int add(int a, int b) {
return a+b;
}

Make a local copy


of a and b

int a, b, sum;
sum = add(a, b);

pass by reference
int add(int *a, int *b) {
return *a + *b;
}
int a, b, sum;
sum = add(&a, &b);

Pass pointers that reference


a and b. Changes made to
a or b will be reflected
outside the add routine

Parameter Passing
pass by reference alternate notation
int add(int &a, int &b) {
return a+b;
}
int a, b, sum;
sum = add(a, b);

Class Basics
#ifndef _IMAGE_H_
#define _IMAGE_H_

Prevents multiple references

#include <assert.h>
#include "vectors.h

Include a library file


Include a local file

class Image {
public:
...
private:
...
};
#endif

Variables and functions


accessible from anywhere
Variables and functions accessible
only from within this classs functions

Creating an instance
Stack allocation
Image myImage;
[Link](ClearColor);

Heap allocation
Image *imagePtr;
imagePtr = new Image();
imagePtr->SetAllPixels(ClearColor);
...
delete imagePtr;

Organizational Strategy
image.h

Header file: Class definition & function prototypes

void SetAllPixels(const Vec3f &color);


image.C

.C file: Full function definitions

void Image::SetAllPixels(const Vec3f &color) {


for (int i = 0; i < width*height; i++)
data[i] = color;
}
main.C

Main code: Function references

[Link](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
Constructors can also take parameters
Image(int w, int h) {
width = w;
height = h;
data = new Vec3f[w*h];
}

Using this constructor with stack or heap allocation:


Image myImage = Image(10, 10);

stack allocation

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] = img->data[i];
}

A default copy constructor is created automatically,


but it is often not what you want:
Image(Image *img) {
width = img->width;
height = img->height;
data = img->data;
}

Passing Classes as Parameters


If a class instance is passed by value, the copy constructor will
be used to make a copy.
bool IsImageGreen(Image img);

Computationally expensive

Its much faster to pass by reference:


bool IsImageGreen(Image *img);

or
bool IsImageGreen(Image &img);

Class Hierarchy
Child classes inherit parent attributes
Object3D
class Object3D {
Vec3f color;
};
class Sphere : public Object3D {
float radius;
};
class Cone : public Object3D {
float base;
float height;
};

Sphere

Cone

Class Hierarchy
Child classes can call parent functions
Sphere::Sphere() : Object3D() {
radius = 1.0;
Call
}

the parent constructor

Subclass

Superclass

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 }
};

Virtual Functions
A superclass pointer can reference a subclass object
Sphere *mySphere = new Sphere();
Object3D *myObject = mySphere;

Superclass

class Object3D {
virtual void intersect(Ray *r, Hit *h);
};

Subclass

If a superclass has virtual functions, the correct subclass


version will automatically be selected

class Sphere : public Object3D {


virtual void intersect(Ray *r, Hit *h);
};
myObject->intersect(ray, hit);

Actually calls
Sphere::intersect

Pure Virtual Functions


A pure virtual function has a prototype, but no definition.
Used when a default implementation does not make sense.
class Object3D {
virtual void intersect(Ray *r, Hit *h) = 0;
};

A class with a pure virtual function is called a pure


virtual class and cannot be instantiated. (However, its
subclasses can).

The main function


This is where your code begins execution
int main(int argc, char** argv);

Number of
arguments
argv[0]
argv[1]

Array of
strings

is the program name


through argv[argc-1] are command-line input

Coding tips
Use the #define compiler directive for constants
#define PI 3.14159265
#define MAX_ARRAY_SIZE 20

Use the printf or cout functions for output and debugging


printf("value: %d, %f\n", myInt, myFloat);
cout << "value:" << myInt << ", " << myFloat << endl;

Use the assert function to test always true conditions


assert(denominator != 0);
quotient = numerator/denominator;

Coding tips
After you delete an object, also set its value to NULL
(This is not done for you automatically)
delete myObject;
myObject = NULL;

This will make it easier to debug memory allocation errors


assert(myObject != NULL);
myObject->setColor(RED);

Segmentation fault (core dumped)


Typical causes:
int intArray[10];
intArray[10] = 6837;

Access outside of
array bounds

Image *img;
img->SetAllPixels(ClearColor);

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;
}

or
void setToRed(Vec3f *v) {
*v = RED;
}

Common Pitfalls
Sphere* getRedSphere() {
Sphere s = Sphere(1.0);
[Link](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
Lots of advanced topics, but few will be required for this course

or protected class members


inline functions
const or static functions and variables
compiler directives
operator overloading
friend

Vec3f& operator+(Vec3f &a, Vec3f &b);

Common questions

Powered by AI

When using pointers and memory allocation in C++, it is important to manage memory carefully to avoid errors such as memory leaks, segmentation faults, and dangling pointers. Memory leaks occur when memory is allocated but not deallocated, leading to wasted resources. Segmentation faults can result from accessing memory outside array bounds or using null or deleted pointers. Dangling pointers occur if a pointer is not updated to null after deletion, leading to undefined behavior when accessed . Proper use of 'delete' and setting pointers to NULL after deallocation is crucial to mitigate these issues .

Virtual functions in C++ allow a subclass to provide a specific implementation of a function that is already defined in its superclass, supporting runtime polymorphism. When a subclass overrides a virtual function, the correct version of the function is automatically selected at runtime based on the type of the object that is making the call. This mechanism enables the use of a superclass pointer (or reference) to refer to objects of any subclass, allowing flexible and scalable code .

Pure virtual functions are beneficial when a class needs to define a common interface for its subclasses while not providing a default implementation for the function. This is useful in an abstract class context where functionality must differ among subclasses. Pure virtual functions enforce subclasses to provide their implementation, ensuring that they are correctly tailored to specific needs. This design pattern supports flexible and extensible software architecture by allowing clean abstract interfaces .

The inheritance hierarchy in C++ facilitates object-oriented programming by allowing a subclass to inherit the properties and behaviors of a superclass, enabling code reusability and extension. This hierarchy allows the creation of a common interface for a group of related classes. Subclasses can override or extend base class functionalities, promoting polymorphism and dynamic method binding. By inheriting common attributes and methods, subclasses save on redundant code and can be specialized for more specific functionalities .

Constructors and destructors are crucial for resource management in C++ classes. A constructor is executed whenever a new instance of a class is created, allowing the initialization of its resources. Conversely, a destructor is called when an instance is deleted, facilitating resource deallocation. This ensures that memory and other resources are allocated and freed appropriately, preventing resource leaks and ensuring the clean-up of class-owned data .

In C++, dynamic memory allocation is done using the 'new' keyword, which allocates memory on the heap and returns a pointer to the allocated memory. It is essential to manage this memory properly by deallocating it using the 'delete' keyword to prevent memory leaks. After deleting a dynamically allocated object, setting its pointer to NULL is recommended for easier debugging and avoiding dangling pointer issues. This process ensures that resources are efficiently utilized and prevents erratic behavior due to inaccessible or non-existent memory locations .

Copy constructors are used to create a new object as a copy of an existing object. Challenges arise when default copy constructors are not suitable because they perform shallow copying, which can lead to shared pointers to memory, corruption of object state, or resource leaks. This issue is addressed by implementing a custom copy constructor that performs deep copying, ensuring that each object has its own copy of memory resources. Properly managing resources, particularly for dynamic allocations, ensures stability and correctness in C++ programs .

Coding tips in C++ tutorials help prevent common programming pitfalls by providing best practices and optimizations. For instance, using '#define' for constants, 'assert' for invariant checking, and the 'printf' or 'cout' functions for debugging are essential tips for maintaining code quality. Additionally, setting pointers to NULL post-deletion prevents dangling pointers, and checking array bounds safeguards against segmentation faults. These practices help developers write cleaner, robust, and more understandable code .

To handle segmentation faults in C++, programmers can adopt several strategies, including rigorous checking of array bounds to prevent access violations and using smart pointers like std::shared_ptr or std::unique_ptr to better manage memory allocation and deallocation. Regularly using debugging tools like gdb to track memory access issues and implementing guards such as assertions to validate assumptions during development are also effective. These strategies lead to more stable and error-resistant code by addressing the root causes of segmentation faults .

Passing parameters by reference in C++ is generally faster and more efficient than passing by value, especially for complex data types like class instances. When passing by value, a copy of the object is created, which can be computationally expensive. In contrast, passing by reference allows the function to access the original object directly without making a copy, thus improving performance .

You might also like