0% found this document useful (0 votes)
52 views26 pages

C++ Exam Revision: A Guide Only

This document provides an overview of pointers, references, classes, and other C++ concepts for an exam revision. Key points include: - Pointers should be initialized to 0 and can be used to access the value of a variable. - References are aliases that cannot change what they refer to after initialization. - Classes can contain member functions, variables, constructors, and access modifiers like public and private. - Inheritance allows classes to extend other classes in a hierarchy. Abstract classes with pure virtual functions can be used like interfaces. - Static members belong to the class rather than objects, while dynamic arrays of pointers can be used to store objects of a class.

Uploaded by

hvalola
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)
52 views26 pages

C++ Exam Revision: A Guide Only

This document provides an overview of pointers, references, classes, and other C++ concepts for an exam revision. Key points include: - Pointers should be initialized to 0 and can be used to access the value of a variable. - References are aliases that cannot change what they refer to after initialization. - Classes can contain member functions, variables, constructors, and access modifiers like public and private. - Inheritance allows classes to extend other classes in a hierarchy. Abstract classes with pure virtual functions can be used like interfaces. - Static members belong to the class rather than objects, while dynamic arrays of pointers can be used to store objects of a class.

Uploaded by

hvalola
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
You are on page 1/ 26

C++

Exam Revision

A Guide only
Pointers
• Pointers should always be initialised

Type * PointerName = 0;

• If the address is unknown at definition, assign 0 as there is no


address 0
int age(21);
int *ptrToAge = 0;

ptrToAge = &age;

cout << ptrToAge << endl; // displays 0013FF54 on my PC

• When declaring more than one pointer of the same type,


repeat the *
int * a, * b, * c;
Pointers
• Through the pointer we can access the value within the
variable whose address is stored in the pointer.
• The dereference operator * precedes the pointer to return
the variables value.
• The dereference operator translates to “value pointed by”

int age(21);
int *ptrToAge;

ptrToAge = &age;

cout << *ptrToAge << endl; // displays 21


References
• An alias for a variable, through which the data within the
variable can be modified.
• The reference holds the address of a variable.
• The reference is declared using the reference operator &
• The reference must be initialise during definition
type& referencename = value;
• Once initialised the reference address can’t change (unlike a
pointer).
• After declaration the reference can be treated as a normal
variable.
char gender = 'M';
char& ref = gender;
ref = 'F';
cout << ref << endl; // Outputs F
cout << gender << endl; // Outputs F
Constant Parameters
• By preceding a parameter with the const keyword we can
ensure that its value is not changed within the function.
type FunctionName(const type ParameterName)
bool IsRetired(const int age){
if (age >= 65)
return true;
else
return false;
}
• In the case of a reference, the value the reference referrers to,
can’t be changed. The reference is a const anyway.
bool IsRetired(const int& age){
if (age >= 65)
return true;
else
return false;
}
Default Parameters
• The last parameter/s can be assigned default values.
• If when invoking the function, the arguments are not passed,
the default values will be assigned.
type FunctionName(type identifier = value)
• If an argument is passed the default will be ignored.
float CalculateTax(float income,float taxRate = 0.20){
return (income - (income * taxRate));
}

int main(){
cout << CalculateTax(32000) << endl;
return 0;
}

• It is illegal to assign the first parameter a default and not the


second.
Defining Classes
The class keyword precedes the class’s name which must
conform to identifier naming conventions.
class NameOfClass {

} optional variable/s;

Member Functions and Variables belonging to the class may


be placed inside the { } Note the ; after the class’s closing bracket.
class BasicPlayer {
int size;
void DoSomething() {
cout << “Something” << endl;
}
};
Functions defined inside the class are implicitly inline
Access Modifiers
• Determine the visibility of members.
• public – visible to any member of any class
• private – accessible from within the same class
• protected – as private + its derived classes
class NameOfClass {
private:
one or more variable declarations or
member functions
protected:
one or more variable declarations or
member functions
public:
one or more variable declarations or
member functions
};
Default Constructors
• A default constructor is one that can be invoked without
passing parameters.
• If you don’t define it, the compiler may create a default one
for you within the executable.
• A Complier generated default constructors will allocate
memory but not initialise values
• Below is an example of a user defined default constructor
class MyClass{
private:
int value;
public:
MyClass(){
value = 0;
}
};
Non Default Constructors
• A Single class may contain multiple overloaded constructors
class MyClass{
private:
int a, b;
public:
MyClass(int n){
a = n;
b = 0;
}
MyClass(int n, int m){
a = n;
b = m;
}
};
• If a non default constructor is defined the compiler will not
automatically create a default constructor.
• If a non default constructor is defined and no default
constructor is defined the following will generate a compiler
error.
MyClass myObject;
Constructors & Inheritance
• Constructors can be invoked class Model{
from within the derived classes private:
int id;
constructor as part of the public:
initialisation list. Model(int modelID){
• The parent’s constructor name id = modelID;
follows the colon after the }
}
child’s Constructor.
• Arguments can be passed to class Car:public Model{
the parents constructor. public:
Car(int carID):Model(carID){
• In this example the carID }
parameter that is assigned a };
value of 3 is passed up to the
Model’s constructor. int main(){
Car *carB = new Car(3);
}
Copy Constructor
• Copy constructor is a member function with the same name as
the class. It takes a single argument (usually const) that is a
reference to an object of the same class.
class MyClass{
public:
MyClass(const MyClass& obj){ }
};

• The copy constructor is invoked when


1. Initialise one object from another of the same type
2. Copy an object to pass as an argument to a formal parameter
3. Copy an object to return it from a function
4. Initialise the elements in a sequential container
5. Initialise the elements in an array when an initializer list is used.
Inheritance
• Typically classes have relationships with one another.
• Some classes being specialised versions of more general
classes.
• This could be modelled as a class hierarchy.
• Examples
dog is a type of animal
house is a type of building
npc is a type of gameObject
• The general class is known as the parent and the specialised
class the child
class ChildClassName:ParentClassName{

}
Abstract Member Functions
• Also know as pure virtual member functions.
• A function that has no implementation.
• It is virtual as subclasses must override it.
virtual type MemberFunctionName() = 0;
• When declared within a class it prevents the class from being
instantiated (an abstract class).
• Only derived classes that implement the pure virtual member
functions can be instantiated.
class Person { class Soldier : public Person {
public: public:
virtual void Move() = 0; void Move(){ }
}; };

• Classes with one or more abstract member functions could be


used as an alternative to Java / C# interfaces.
UML Class
class name

private data member


protected data member

public data member

public member function


private member function

protected member function

General
padlock : private
key : protected
neither : public
Static Data Members
• Static members can be either variables or functions.
• Static variables (class variables) belong to the class. A single value
for all objects instantiated from the class.
• Similar to global variables but within the scope of the class and
must obey access modifier rules.
static type identifier;

class Player{
public:
static int instances;
Player(){
instances++;
}
};

• Static data members are not initialised in the constructor.


Dynamic Arrays of Pointers to Objects
• The array name is a pointer to a pointer
type **identifier;
• Each element is a pointer
identifier = new type *[size];

• Each index must be dynamically assigned an object of the


class type.

identifier[index] = new ClassName();

• May not require a default constructor


• Dereference *indentifier
Dynamic Sized Arrays of Pointers Example

class Group{
private:
GameObject** objects;
int size;
public:
Group(int n):size(n){
objects = new GameObject*[size];
for(int n=0;n<size;n++)
objects[n] = new GameObject(n);
}
void Display(){
for(int n=0;n<size;n++)
objects[n]->Display();
}
};
Polymorphism
Model’s Draw member class Model{
public:
function is virtual. This virtual void Draw(){
cout << "Draw Model \n";
ensures objects of type Car }
will invoke the Car’s Draw };

member function even


class Car : public Model {
thought they might be public:
void Draw(){
stored within a pointer of cout<< "Draw Car \n";
the Base type. }
};

int main(int argc,char* argv[]){


Model *model = new Car();
Car *car = new Car();
model->Draw();
car->Draw();
return 0;
}
Friend Functions
• Private and protected members can’t be accessed from
outside of the class / class hierarchy.
• An external function can be declared as a friend of a class,
which allows it access to these class members.

class ClassName{
friend returnType functionName(parameter/s);
}
• In the next example the friend function creates an array of
all the unMounted weapons in a game. isMounted is a
private member so the function is declared as a friend of
the class.
Friend Function Example
class Weapon{
private:
bool isMounted;
public:
string name;
Weapon(string desc,bool mounted):name(desc),isMounted(mounted){}
friend Weapon** UnmountedWeapons(Weapon **,int* );
};

Weapon** UnmountedWeapons(Weapon **weaponList,int *size){


Weapon **unMounted = new Weapon*[*size];
int i = 0;
for(int n=0;n < *size;n++){
if (!weaponList[n]->isMounted){
unMounted[i] = weaponList[n];
i++;
}
}
*size = i;
return unMounted;
}
Memory Managment
• Dynamic memory should be freed when the object is no
longer required.
• Unlike variables stored on the stack heap memory must be
explicitly freed.
• Delete must be followed by a pointer containing either a value
of NULL or an area of memory allocated by the new keyword.

delete pointer;

MyClass *myObject = new MyClass();


// Process object myObject
delete myObject;
Delete arrays
• New used to allocate memory for an array
type *pointer = new type[size];

• Array memory is deallocated using delete[]

delete[] pointer;

• Delete must be followed to a pointer containing either a value


of NULL or an area of memory allocated by the new keyword.
int *marks = new int[100]
// Process marks
delete[] marks;
Stack Design
List Design
Basic Design
The Node may be derived from the
item being stored within the tree or
as in this case maintain a reference
to it.

You might also like