Sie sind auf Seite 1von 31

„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Effective programming techniques


➢ Course: Effective programming techniques
➢ Lecturer: Jan Kwiatkowski, DEng
➢ Course forms: Lecture, Laboratory
➢ ECTS 5

Communication
➢ For questions, email to jan.kwiatkowski@pwr.edu.pl
with 'Subject=your name”.
➢ Make sure to email from an account I can reply to.
➢ All course information will be available at:
http://www.ii.pwr.wroc.pl/~kwiatkow
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Content
➢ The aim of the course is to present the essential properties of
object-oriented programming languages basing at the C++
programming language.
➢ The course will focus on presenting techniques that guarantee
developing and implementing efficient programs.
➢ The following topics are covered:
objects and classes, encapsulation and information hiding,
constructors and destructors, friend functions and classes,
operators overloading, inheritance, virtual methods and
polymorphism, exception handling, function and class
templates, containers and iterators.
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Literature
➢ B. Stroustrup, The C++ Programming language, Addison-
Wesley Pub. 1993
➢ H.M. Deitel, P.J. Deitel, C++ How to program, Prentice Hall
2003
➢ B. Eckel, Thinking in C++, Pearson Education 2000.
➢ Scott Meyers „Effective modern C++”, O’Reilly Media, 2014.
➢ Documentation of the STL library
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Basic Principles of Object Oriented Programming


➢ Abstraction - A model that includes most important aspects of
a given problem while ignoring less important details.

➢ Encapsulation - Hide implementation from clients - Clients


depend on interface.

➢ Modularity - The breaking up of something complex


intomanageable pieces or modules.

➢ Hierarchy - Level of abstraction.


„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Basic Principles of Object Oriented Programming


Inheritance

➢ Process by which one object acquires of another object.


➢ Supports concept of hierarchical classification.
➢ With inheritance, object only needs to define what makes it
unique within its class.
➢ In OOP, Inheritance means inheriting another object’s
interface, and possibly its implementation.
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Basic Principles of Object Oriented Programming

➢ A class is a description of a group of objects with common


properties (attributes), behaviour (operations), relationships,
and semantics.
➢ An object is an instance of a class.
➢ A class is an abstraction in that it:
▪ Emphasizes relevant characteristics,
▪ Suppresses other characteristics.
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Basic Principles of Object Oriented Programming

• Memory is allocated for each object instantiated (and not for


the class).
• An object of a class can be defined in the same way as any
internal type.
• The function are called member functions and data the data
member.
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

An example of the class


Class declaration

class Point
{
public:
Point();
int Get_x();
int Get_y();
private:
int x,y;
};
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

An example of the class


➢ The definition is not complete we need to implement member
function
Point::Point()
{
x=0;
y=0;
}
int Point::Get_x()
{
cout<<”x coordinate = ”<<x;
}
int Point::Get_y()
{
cout<<”y coordinate = ”<<y;
}
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

An example of the class


➢ We can implement class in the other way
class Point
{
public:
Point()
{ x=0;
y=0; };
int Get_x()
{ cout<<”x coordinate = ”<<x; };
int Get_y()
{ cout<<”y coordinate = ”<<y; };
private:
int x,y;
};
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

An example of the class


Now we can use our class

main()
{
Point p;
p.Get_x();
p.Get_y();
}
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Types of access for a class member


➢ “Class member” refers to data elements or methods within a class
➢ Types of access privileges for a class member:
public:
▪ Class member accessible from anywhere within the application
protected:
▪ Class member accessible from any of the class’s methods;
▪ Class member may be inherited by subclass
▪ Not available elsewhere in application
private:
▪ Class member only available to class’s methods
▪ Not inherited
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Friend functions
➢ Allow non-member functions access to private members of class

class myClass {
int a, b;
public:
myClass(int I, int j) {a=I; b=j;}
friend int comDenom(myClass x);
};
i nt comDenom(myClass x)
{ int max = x.a < x.b ? x.a : x.b;
for (int i=2; i <= max; i++)
if ((x.a%i) == 0 && (x.b%i) == 0) return i;
return 0;
}
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Constructor
➢ Constructors are invoked to initialize the data members of a class.
➢ Can not return any value (not even void).
➢ Can accept any parameters as needed.
➢ Constructors differs from other member functions.
➢ Initializes a newly created object, other member functions are
invoked by existing objects.
➢ A Constructor is invoked automatically when an object is created.
➢ Have the same name as the class.
➢ You can have several constructors for a class by overloading them.
➢ If you implement no constructor, the compiler automatically
generates a default constructor for you
➢ But if you write any constructors at all, the compiler does not supply
a default
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

What is memory Allocation?


There are two ways in which memories can be allocated :
➢ During compile time also called static allocation. In this case
the memory size should be known during compilation time. It
is very important in case of arrays because its size have to be
constant during program execution. For this allocation stack is
used.
➢ During program runtime or dynamic allocation when the
memory is allocated at runtime. In this case the size of the
allocated memory is done dynamically within the program
running, and does not have to be known during compilation
time. For this allocation heap is used and pointers are needed.
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Static Allocation & Dynamic Allocation


void test1()
{
int a;
int *pointer_int;
pointer_int = & a;
int *pi_table;
pi_table = new
}
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Pointers
The pointer is used to indicate (show) objects of a given type, it cannot be used
to point to objects of a different type.
int d = 5; // an object of type int
int k = 3; // an object of type int
int * w; // pointer “w” is defined
w = & k; // setting the pointer to the object "k"
int * w = & k; // it is correct, too
Now you can change the pointed value in two ways:
k = 100; or * w = 100;
The pointer can be set to point to the object "d"
w = & d; // set the pointer to object "d"
But you can't do that
float c;
w = & c; //error ???
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Pointers
➢ Let's define an example class
class test {
public:
int thing; }
➢ How can we relate to class (object) members?
test object1; // we define the object of the class "test"
test * pointer; // we define the pointer
test & object2 = object1; // we define the reference
object1.thing = 10; // by the name of the object
Pointer = & object1;
pointer -> thing = 10; // using the pointer
object2.thing = 10; // using the reference
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Access to class members


➢ The member functions in the public section of a class
can be accessed using the “.” operator for instantiated
objects. (for pointers its -> )
Square s1, *s2;
s1.set_values(5);
s2 = new Square; s2->set_values(10);
➢ Only the public members of an object can be directly
accessed.
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

This pointer
➢ “this” is a pointer to the object through which this method was
invoked
int getSize() { return size; }
int getSize() { return this->size; }
➢ Passed as an implicit argument to every member method
➢ Common uses for “this”:
▪ To call a method in another object, passing the current object as an
argument
▪ To return a pointer to the current object
➢ Friend functions don’t have a “this” pointer, because
➢ friends are not members of a class.
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Dynamic Creation of Objects


➢ The C++ compiler allocates sufficient storage for each variable – this
storage is reserved, whether or not the variable is actually used.
void f(int i) // i allocated during f automatic allocation
{
int j; //local variable j allocated during f automatic allocation
}
....
int k; //k statically allocated
k=9;
f(k); //i and j allocated within f
k=10; //i and j no longer allocated
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Dynamic Creation of Objects


➢ Pointers together with associated support operators new and delete,
allow a programmer to denamically allocate and manage portion of
memory, and to do explicitly
New – allocate a space for a new data value
char *cp;
int *ip;
account *accp;
cp = new char;
ip new int;
accp = new account(11111,50000);
➢ The space alocated for cp and ip is not initialised (to this: *cp =
‘a’;*ip=5; )
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Dynamic Creation of Objects


➢ With regard to the management of dynamically allocated space,
having explicitly allocated memory using new, great care
should be taken not to lose track of it.
account *accountone, *accountTwo;
accountOne = new account(1111,5000);
accountTwo = new account(1111,5000);
........
accountOne = accountTwo;
accountTwo->display(); //second account displayed
accountOne->display(); //second account displayed
➢ A memory block to which there is no pointer referring, is
irrevocably lost to a C++ program
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Dynamic Creation of Objects


➢ Storage allocated using new can be released again by calling
delete
char *cp;
int *ip;
account *accp;
cp = new char;
ip new int;
accp = new account(11111,50000);
delete cp;
delete ip;
delete accp;
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Data structures
➢ Dynamic data structures
▪ Data structures that grow and shrink during execution
➢ Linked lists
▪ Allow insertions and removals anywhere
➢ Stacks
▪ Allow insertions and removals only at top of stack
➢ Queues
▪ Allow insertions at the back and removals from the front
➢ Binary trees
▪ High-speed searching and sorting of data and efficient
elimination of duplicate data items
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Dynamic Creation of Objects


➢ Self-referential structures
▪ Structure that contains a pointer to a structure of the same type
▪ Can be linked together to form useful data structures such as lists, queues, stacks and
trees
▪ Terminated with a NULL pointer (0)
struct node {
int data;
struct node *nextPtr;
}
➢ nextPtr
▪ Points to an object of type node
▪ Referred to as a link
• Ties one node to another node
➢ Dynamic Memory Allocation

15 10
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Separate Source Files


It is a good practice to put each class into a separate
source file

➢ It increases the clarity of your code


➢ It means that changes to the implementation of a single class
do not require you to re-compile the others
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

An example
Let’s define a class account

➢ It should be stored in two files: account.h – the definition of the class and
account.cpp – the definition of the functions
In account.h
class account {
protected:
int accountNumber;
char* owner;
float accountBalance;
public:
account (int theNumber, char* theOwner, float theBalance);
virtual void display();
virtual void makeLodgement(float lodgement);
virtual void makeWithdrawal (float withfrawal);
~account(); };
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

An example
In account.cpp

#include ”account.h”
account::account (int theNumber, char* theOwner, float
theBalance)
{ // code for account::account }
void account::display();
{ // code for account::display }
void account:: makeLodgement(float lodgement);
{ // code for account:: makeLodgement }
void account:: makeWithdrawal (float withfrawal);
{ // code for account:: makeWithdrawal }
account:: ~account()
{ // code for account:: ~account }
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Separate Source Files


➢ Use #include ”file.h” to include one of yours .h files , but
#include <file.h> to include a .h file provided by the system
➢ A file can #include as many files as necessary. Each of these in
turn may #include others. Sometimes the same file can be
included two or even more times, it leads to compilation errors
➢ To avoid above you can use the following structure:
#ifndef account_h
#define account_h
//definition
#endif
„ZPR PWr – Zintegrowany Program Rozwoju Politechniki Wrocławskiej”

Separate Source Files


➢ All classes derived from account, and any classes which use account,
must also include account.h
➢ What if class definitions need to use each other ?
In bank.h
#ifndef bank_h
#define bank_h
class client // it declares client as class
class bank
{ //class definition };
#endif
In client.h
#ifndef client_h
#define client_h
class bank // it declares bank as class
class client
{ //class definition };
#endif

Das könnte Ihnen auch gefallen