An introduction to C++

An Introduction to C++

Classes

Classes provide the basic data/code organization construct within C++
Classes are (roughly) comprised of two parts:
Data members (properties)
Code members (methods)
Class support inheritance – we don’t have time to cover this
Recommendation – if you are not familiar with inheritance, do not try to learn how to use it during the MFE
class myFirstClass
{
public:
// Some properties
int integerProperty;
double floatingPointProperty;
char characterArray[254];

// some methods
// a constructor
myFirstClass()
{
integerProperty = 12;
floatingPointProperty = 25.2;
strcpy(characterArray, « yo yo yo »);
}

// a destructor
virtual ~myFirstClass()
{
}

void doSomething()
{
… some code would go here …
}
};
There are other features to classes including:
Information hiding (public, protected, private)
Virtual functions
They are extremely powerful and useful, but now is not the time to play with these.
Classic interview question: What is the difference between a class and an object?
Better interview question: Can an object ever be a class?

Pointers

Pointers are a special type of variable
Pointers hold the address of data, not the data
Pointers must be assigned values before they can be used.
Pointers are a special type of variable
Pointers hold the address of data, not the data

int a1; // a1 is not a pointer
int *a2; // a2 is a pointer
a1 = 10;
a2 = &a1; // a2 now points to a1
*a2 = 5; // we ‘dereference’ a2 to assign a value
printf(« %d %d\n », a1, *a2); // what will this print?
Be very careful with pointers
Someone once estimated that 90% of all C++ bugs can be traced back to bad pointers

Memory Allocation / Arrays

C++ supports both statically and dynamically allocated arrays
If you dynamically allocate an array, make sure to deallocate it when you are done using it.
Make sure you are really done using it before you deallocate!

int myArray[10]; // this is statically allocated array

for (int i = 0; i < 10; i++)
{
// Assign a value to each member of the array
// Notice that the array is ‘referenced’ from 0 to 9
// Arrays in C++ ‘start’ at 0
myArray[i] = i * i + 1;
}


// this is dynamically allocated array
// it looks suspiciously like a pointer!
int *myArray;

// first we allocate it
myArray = new int[10];

// this is what a for loop looks like
for (int i = 0; i < 10; i++)
{
// Assign a value to each member of the array
// Notice that the array is ‘reference’ from 0 to 9
// Arrays in C++ ‘start’ at 0
myArray[i] = i * i + 1;
}

// now we deallocate it
delete[] myArray;


Question: when should you dynamically allocate an array?

When should static allocation be used?

Cours gratuitTélécharger le cours complet

Télécharger aussi :

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *