0% found this document useful (0 votes)
38 views

Introduction To Programming Using C++: Lecture Five: Introducing Classes

This document introduces classes in C++. It begins by congratulating the reader for learning basic C++ programming and explaining that object-oriented programming using classes is the next step. It then discusses types in C++ and how classes allow users to create their own custom types. The document provides an example class to store information about cars and demonstrates how to declare classes, define member variables and functions, and access members using the dot operator. It also discusses public and private access specifiers and accessor methods. Finally, it presents an example class to represent points in 3D space.

Uploaded by

Alen Bajrovic
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Introduction To Programming Using C++: Lecture Five: Introducing Classes

This document introduces classes in C++. It begins by congratulating the reader for learning basic C++ programming and explaining that object-oriented programming using classes is the next step. It then discusses types in C++ and how classes allow users to create their own custom types. The document provides an example class to store information about cars and demonstrates how to declare classes, define member variables and functions, and access members using the dot operator. It also discusses public and private access specifiers and accessor methods. Finally, it presents an example class to represent points in 3D space.

Uploaded by

Alen Bajrovic
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Introduction to

Programming using C++


Lecture Five: Introducing Classes

Carl Gwilliam

[email protected]
http://hep.ph.liv.ac.uk/~gwilliam/cppcourse

The Next Step


If you have made it this far

Congratulations! You can program in C++!


But if you stop here you might as well have learnt a less
syntactically complicated language.
The next half of the course will be spent introducing
Object Orientated (OO) programming.

Types Revisited
A type defines the information
that can be held by an object.
A type limits the actions that can
be performed on the object.
A type is a method of
determining the amount of
memory that needs to be
allocated for a new object.

// C++ built-in types


int a;

//integer

float b;

//real

double c; //real
bool d;

//boolean

char e;

//character

float height = 1.76;


// float type
unsigned integer counter = 5; // type limits to int above 0
counter = counter / 3.6;
// int conversion of rhs

Extending Types
Types are not just a method of expressing the precision
of a value. A type is a category.
The key to OO programming in C++ is the ability to
create user defined types.

// some declarations
int x, y;
Particle electron, muon;
Department physics, chemistry;
Car myFiesta;
If the new types are declared and defined in the correct
manner then all of the above statements are valid C++.

Is there a need for new types?


You have already written programs to model several
real-world situations without need for new object types.

Modeling Complex Systems


Can the same programming logic be applied to the
following complex systems?
Car engine performance
Resource optimisation within a company
Particle interaction with detector material
Yes! Split problem into small group of calculations and store
relevant values in variables that have labels relevant to problem.

BUT:
OO programming allows the creation of new types that
more accurately reflect the scenario to be modeled.
A problem can be modeled in terms of objects and the
interaction between different objects.
This seems contrary to our obsession with reducing any situation
into a series of abstract mathematical statements

Layers of Abstraction
Object Orientated programming is just a higher level of
abstraction than you are currently used to.

What is the bit sequence for the


number 3?
What memory addresses are being
used to store your variables?
How does program interpret
keyboard signals into ASCII
values?

objects
modules
statements
assembler
language
bitwise operations

ABSTRACTION

Your programs are already written in a high-level


language. Can you answer these questions? Do you
care?

Layers of Abstraction
Dealing with objects and object interaction enables
programs to be designed on a more intuitive level.

Planet a,b;
a.force(b);

// information determined
// by class decleration

mass1 = getMass(1);
// functions called to
force = getForce (G,mass1,mass2,dist); //retrieve properties

mass1 = density1 * volume1;


// statements establishing
mass2 = density2 * volume2;
// values of properties
force = (G * mass1 * mass2) /pow(dist,2);

ABSTRACTION

C++ provides the syntax to allow you to manipulate user


defined objects in the same way that integers and
floating numbers are manipulated.

Introducing Classes
User defined types are referred to as classes.
An object is an instance of class. A class is a category
of objects. Several objects of a certain class can be
instantiated (just like built in types).
int x;
// equivalent
Car myFiesta, myFerrari; // statements
A car can be declared in the same way that an integer
can be declared. The variable myFiesta is associated
with an object of type Car.
An object instance is not a single value. Math operators
have to be assigned a new meaning in this context.
float someValue = myFerrari myFiesta;

Declaring a Class
A simple car class will be designed to introduce the
basic concepts of class construction.
In the first iteration, a car object consists of two
characteristics, the age and retail price of the car.
A car class is declared using the
// car declaration
class keyword followed by the
class Car {
name of the class.
public:
The variables declared inside
int ageInYears;
the block are associated with
int priceInGBP;
this class.
}; // semi-colon
// terminated
These are known as member
variables or member data.

myFiesta (previous slide) is an object that contains two integers

Accessing Member Variables


Member variables are accessed by the dot operator.
The dot operator is placed after name of the object and
followed by the name of the desired member variable.
myFiesta.ageInYears = 5;
Some common misunderstandings:
This statement is trying to assign an age to the idea of a car,
rather than age of particular car
Car.ageInYears = 5;
(does int = 5; make any sense?)
This statement is accessing age without the dot operator. The
car member variables only exist within the scope of the car class
(else how do we know if want
ageInYears = 5;
age of myFiesta or myFerrari?) .

Simpler Data Structures


The car class has no advantages
over using a one dimensional
array.
An array can only hold variables of the
same type whilst classes can contain
variables of multiple types.

The class is just being written as


a data structure. A C-style struct
can be used for this purpose.
True, but classes are much more
powerful than structs.
E.g. Unlike structs, members of a
class are private by default, which
encourages encapsulation (see later).

int Car = {5,2000}


class Car {
public:
int ageInYears;
int priceInGBP;
};
struct Car {
int ageInYears;
int priceInGBP;
} //no semi-colon

Member Functions
A class is a collection of member variables and a set of
related functions, known as member functions or class
methods.
Member functions are also
class Car {
accessed using the dot operator.
public:
int ageInYears;
They are distinguished from
int priceInGBP;
member variables by the use of
void brake();
parentheses.
void accelerate();
Like other functions they can take
};
arguments
Member functions have a role specific to
the class they are declared in. They are
primarily used to access and manipulate
class member data.

Car myFiesta;
myFiesta.brake();

Writing Member Functions


The difference between a normal function definition and
a member function is the form of the function name.

The member function name needs to be prefixed with


the class it belongs to followed by the scope resolution
operator ::.
This syntax indicates to the compiler that the function is
local to the Car class and can only be accessed through
a Car object.
// brake member function
void Car::brake() {
cout << "Slowing down << endl;
}

Private and Public Member data


All members of a class are declared class Car {
int ageInYears;
private by default.
int priceInGBP;
If public keyword is removed from
void brake();
class declaration the member
void accelerate();
};
variables and methods cannot be
accessed from outside the class.
Why should the member data be
private? I created the object so I should
have access to all of its information.

Car myFiesta;
// error here
myFiesta.ageInYears = 5;

Think of the declaration as the acquisition of an object


rather than the creation of an object.
The inner workings are hidden from you for your own
protection! You dont need to know how the object works,
all you need is an interface to the object. This is known as
encapsulation or information hiding.

Accessor Methods
class Car {
Private member data can be
modified by calling public member public:
void brake();
functions known as accessor
void accelerate();
methods. Accessor methods are
void setAge(int age);
int getAge();
commonly known as getters and
void setPrice(int price);
setters.
int getPrice();
private:
Why go the trouble hiding the member
int ageInYears;
data? It is easier for me to access the data
int priceInGBP;
directly through the dot operator rather
};
than through this level of indirection.

An accessor method will allow you to change the name


of a member variable. This change is hidden from the
user because of encapsulation.

A Point Class
The remainder of this lecture will be used to construct a
point class.
int main() {
Point a, b;
:
}
To design the interface, think in terms of the point object:

What is my identity?
What messages can you give me?
What is my distance from the origin?
What is my distance from another point in space?

Point class declaration


The initial interface design
contains just accessor methods.
The member data is private and
the accessor functions are public.

The class declaration, or


interface, is put into a separate
header file (this allows to
minimise the dependencies
between different pieces of code).

// point class
// declaration
class Point {
public:
void setX(float x);
void setY(float y);
void setZ(float z);
float getX();
float getY();
float getZ();
private:
float itsX;
float itsY;
float itsZ;
[Point.h]
};

Preprocessor Macros
Before the compiler interprets code it is passed through
the preprocessor, whose task is to find preprocessor
directives, or macros.
Preprocessor macros are indicated by lines beginning
with a hash, #.
In fact, we have already been using the #include macro.

Macros can also be used for other purposes, such as


defining constants, although they are generally
#ifndef MYHEADER_H
considered bad practice.
#define MYHEADER_H
One place where macros are
// code
useful is to prevent a header file :
#endif
being included multiple times.
For more information on macros see:
http://www.cplusplus.com/doc/tutorial/preprocessor.html

Accessor Implementation
The implementation of the
#include point.h
accessor functions, along with int main() {
Point a;
other class methods, are
// set coordinates for point a
placed in a source file,
a.setX(2); a.setY(1); a.setZ(5);
// display coordinates
seperate from the header file
cout <<"vector coordinates a: "
and the main program.
<<a.getX()<<","<< a.getY()
<<","<<a.getZ()<<endl;
The implementation is totally
}
[UsePoint.cpp]
separate from the interface.
#include point.h
void Point::setX(float x) {
itsX = x;
}
float Point::getX() {
return itsX;
}
[Point.cpp]

A user of the point class will just


need to include the header file
at the top of the program.
The coordinates of the point are
set and retrieved in main().

Distance of Point from Origin


A public class method is included that returns the
distance of a point instance from the origin.
// declare point class
class Point {
public:
:
float distanceFromOrigin();
private:
:
};
[Point.h]

:
// get distance from origin
float Point::distanceFromOrigin() {
float distance = sqrt( pow(itsX,2)
+ pow(itsY,2) + pow(itsZ,2) );
return distance;
}
:
[Point.cpp]

Note that private member variables can be used in


public class methods from the same class.

Distance between Points


What is the points distance from another point in space?
:
[Point.cpp]
// distance between points
float Point::distanceFromPoint(float x, float y, float z) {
float difX = itsX - x;
:
[UsePoint.cpp]
float difY = itsY - y;
int main() {
float difZ = itsZ - z;
:
float distance = sqrt( pow(difX,2)
float x = b.getX();
+ pow(difY,2)
float y = b.getY();
+ pow(difZ,2) );
float z = b.getZ();
return distance;
float dist =
}
a.distanceFromPoint(x,y,z);
:
:
}

In this first iteration the x,y and z coordinates of one of the Points is
passed into the new Points membre function. Theres a better way

Passing Objects into Functions

The point object can


be passed directly
into the member
function.

class Point {
public:

[Point.h]

float distanceFromPoint(Point anotherPoint);


:

: };
The member variables
// distance between points
from another point obj
float Point::distanceFromPoint(Point anotherPoint) {
have to be accessed
float difX = itsX - anotherPoint.itsX;
via the dot operator.
float difY = itsY - anotherPoint.itsY;
N.B. another objects
float difZ = itsZ - anotherPoint.itsZ;
member data can be
float distance = sqrt( pow(difX,2) + pow(difY,2) +
accessed directly by
pow(difZ,2) );
an object of the same
[Point.cpp]
return distance;
class without calling
}
:
public accessor func. :
int main() {
:
C++ is not a pure object
float distance = a.distanceFromPoint(b);
orientated language!
:
(theres a compromise to
[UsePoint.cpp]
}
enhance functionality)

Overloading Class Methods


The two distance functions have different input args.
Therefore a single member function distance can be
overloaded (polymorphism).
Overloading similar functions simplifies the class interface
class Point {
public:

[Point.h]

float distanceFromOrigin();
float distanceFromPoint(Point anotherPoint);
:

};

class Point {
public:
:

float distance(); // from origin


float distance(Point anotherPoint);
:

};

Point Class Declaration


// point class declaration
class Point {
public:
Point(float x, float y, float z); // constructors
Point();
~Point();
// destructor
void setX(float x);
// accessors
void setY(float y);
void setZ(float z);
float getX();
float getY();
float getZ();
float distance();
float distance(Point anotherPoint);
private:
float itsX;
// member variables
float itsY;
float itsZ;
};

What are

these?

You might also like