In this tutorial you will learn the basics of C++ and how to use pointers and references. This will allow you to write a simple C++ program that you will then compile. The program will be a Visual Studio console application
About this Tutorial –
Objectives –
This course is aimed at students who need to get up to speed in C++. The course introduces object-oriented concepts and shows how they are implemented in C++. The course does not require awareness or familiarity with object-oriented programming techniques, but programming experience would be useful but not necessarily required.
Audience
Students who are new to object orientation (or programming) and need to learn C++.
Prerequisites
No previous experience in C++ programming is required. But any experience you do have in programming will help. Also no experience in Visual Studio is required. But again any experience you do have with programming development environments will be a valuable.
Experience using a contemporary OO language such as Java or C# would be useful but is not required.
Contents
The C++ course covers these topics and more:
Introduction to C++: Key features of C++; Defining variables; Formulating expressions and statements; Built-in data types; Console input/output
Operators and types: Assignment; Compound Assignment; Increment and decrement operators; Const declarations; Type conversions
Going Further with Data Types: Enumerations; Arrays; Using the standard vector class; Using the standard string class; Structures
Dereference a pointer, to get the contents of the variable at the address indicated by the pointer
Lab 1: Pointers
Lab 1: Pointers
Declaring Pointers
To declare a pointer:
Use * in the declaration
You don’t have to initialize the pointer in the declaration type * pointerVariable;
Examples: int * int_ptr;
double * double_ptr;
Person * person_ptr;
You can declare several pointers in the same statement
You must use a separate * for each pointer variable int * int_ptr1, * int_ptr2, * int_ptr3;
Setting Pointers
Pointer variables hold addresses
Use & to get the address of a variable pointerVariable = &variable;
To set a pointer:
Either initialize it with an address in the declaration…
And/or assign it an address later on
Examples: int num1, num2; // num1 and num2 are integers.
int * ptr1 = &num1; // ptr1 holds the address of num1.
int * ptr2; // ptr2 is uninitialized, so it could point anywhere!
ptr2 = &num2; // ptr2 now holds the address of num2.
ptr1 = ptr2; // What does this do?
On each iteration, access the current element, and then increment the pointer to the next element int lotteryNumbers[6] = { ... };
int * pCur = &lotteryNumbers[0]; // Can just say "lotteryNumbers" here.
int * pEnd = pCur + 6; // Pointer arithmetic is scaled by element size.
while (pCur < pEnd)
{
cout << *pCur++;
}
Null Pointers
Sometimes you're not sure what to initialize a pointer with
But... uninitialized pointers are very dangerous!!!
Sometimes you want to "unset" a pointer
To indicate that the pointer no longer points to a real value
C++ supports the concept of null pointers for these cases
A null pointer is a pointer with the address 0
You can set a pointer to 0, and test against it safely int * ptr1 = 0; // Set it to a null pointer initially.
...
if (ptr1 != 0) // See if the pointer now holds a real address.
{
// Use ptr1 here.
}
In Visual Studio, create a new C++ project named PointersReferencesApp in the student folder. Write a function as follows:
Takes an array of doubles, and returns the average value. Use pointers to traverse the array (to practice using pointer arithmetic) double CalculateAverage(const double *pData, int count)
{
const double *pEnd = pData + count;
double total = 0;
while (pData != pEnd)
{
total += *pData++;
}
return total / count;
}
Takes an array of doubles, and returns a pointer to the largest item const double * FindMax(const double *pData, int count)
{
const double *pLargest = pData;
const double *pEnd = pData + count;
// Loop through all elements, to see which is the largest.
for (const double *pEnd = pData + count; pData != pEnd; pData++)
{
if (*pData > *pLargest)
{
pLargest = pData;
}
}
return pLargest;
}
By default in C++, all parameters are passed-by-value
Except arrays, of course!
Here's a quick reminder: // Client
int n = 10;
cout << "Here are 5 numbers, starting at " << n << endl;
displayNumberRange(n, 5);
cout << "Did you notice the first number was " << n << endl;
// Function
void displayNumberRange(int num, int count)
{
int lastNum = num + count;
while (num < lastNum)
cout << num++ << endl;
}
It's extremely common to pass objects as const reference into functions
Pass-by-reference for efficiency (to avoid expensive object copy
Declare as const to protect against unwanted modification
A good example is passing strings into functions
Pass-by-value works (but is inefficient)
Pass-by-const-reference works better (no need for copying) // Client
string firstName = "Michael";
string surName = "Laudrup";
string fullName = getFullName(firstName, surName);
cout << "Full name: " << fullName;
// Function
string getFullName(const string & fn,
const string & sn)
{
return fn + " " + sn;
}
Lab
Using pointers to pointers
Write a function as follows:
Takes an array of doubles, and yields pointers to the min and max elements void FindMinAndMax(const double * pData, int count, const double **ppMin, const double ** ppMax)
{
// Set first element as min and max element, as a starting point.
*ppMin = pData;
*ppMax = pData;
// Loop through all elements, to see which is the smallest and largest.
for (const double *pEnd = pData + count; pData != pEnd; pData++)
{
if (*pData < **ppMin)
{
*ppMin = pData;
}
if (*pData > **ppMax)
{
*ppMax = pData;
}
}
}
If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Manage cookie consent
You can view this website without consenting to extra cookies. However you will need to accept the 'marketing' cookies to send messages via the contact forms & see any maps displayed on the site
Functional
Always active
Cookies necessary for the website to work.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.Cookies used to track user interaction on the site, which helps us to evaluate & improve the website.
Marketing: Forms & additional content (Marketing)
We need your permission to place ‘marketing’ cookies, so you are able to use the contact forms & see embedded content e.g. videos and maps. - - - - We have added protection to our contact forms to help prove that a human (rather than a spambot) is filling
If you would like to see more content like this in the future, please fill-in our quick survey.