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

C++ 040 Ctor

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

C++ 040 Ctor

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

Advanced Programming Techniques

Constructors and Destructors


State_C ontrol
Signal_A dapter C
State_C ontrol_A UDI o
on_ select_prev () n
init() on_select_next() t
raise_tick() on_tick() on_select_next() r
raise_select_prev () on_triptime_alarm() on_tick() o
raise_select_next() 1 on_mem_lev el_dow n() on_triptime_alarm() l
raise_triptime_alarm() on_mem_lev el_up() on_ select_prev ()
raise_ignition_on() on_mem_lev el_dow n() S
on_ignition_on() e
raise_ignition_off() on_ignition_off() on_mem_lev el_up() c
raise_reset_program() on_reset_program() on_ignition_off() t
raise_reset_all_programs() on_reset_all_programs() on_ignition_on() i
raise_eeprom_changed() on_eeprom_changed() reset_program() o
raise_memlev el_dow n() reset_all_programs() n
<<ctor>> init()
raise_memlev el_up() C reate()

Impl_Tripdistance_A U DI C
Impl_Tripdistance
Program a
Data_A dapter l
c
calc_v alue() : v oid u
display () : v oid Imp_Triptime_Alarm l
ignition_on() : v oid Impl_Triptime_A larm_A U DI a
ignition_off() : v oid t
i
reset() : v oid Impl_Triptime o
<<?>> eeprom_changed() : ... n
need_recalc() : bool
Impl_Mean_C onsumption_A U DI S
Impl_Mean_C onsumption e
c
t

Prof. Dr.-Ing. Peter Fromm Impl_C urrent_C onsumption

Impl_Average_Speed
i
Impl_C urrent_C onsumption_A U DIo
n

Prof. Dr.-Ing. Michael Lipp clear()


Display _A dapter
Impl_Range

w rite_str()
<<draft>> w rite_sy mbol()
<<ctor>> init()
D
i
s
D isplay _Triptime_A larm_A UDI p
D isplay _Triptime_A larm l
Display _V alue a
O SEK-V GC y
(from SY S) show (v alue : dw ord) : v oid Display _M ean_C onsumtion_A U DI
D isplay _M ean_C onsumption S
e
c
t
i
O SEK-w in32 Display _C urrent_C onsumption_A U DIo
D isplay _C urrent_C onsumption
(from SY S) n

Display _Tripdistance_A U DI
Display _Tripdistance
console-w in32
(from SY S)

"classes " of lefthand coloumns in the middel build up the trip computer core. The classes on the right side all
coloumn act as inerface to A ll code has to be independent of manufacturer. belong to the A UDI package
harew are and O S . They and are not part of the main class
are declared abstract in the The Impl_XXX and Display _XXX classes describe w hat flav ours of program hierarchy .
main class hierarchy and functionality are expected
implemented in sev eral They are included to show w here
SYS packages. the main class hierarchy has to be
expanded for manufactorer's
requirements
 Learn about class initialization
 Understand the this-Pointer
 Understand the task of the
Constructor and Destructor
 Understand Default Parameters
 Understand the Copy Constructor

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 2
 Learned the difference between classes and objects
 We did some scoping using private, protected and public
 Implemented some methods and attributes
 Learned more about requirements
 Functional requirements
 Non-Functional requirements

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 3
Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 4
 The C++ programming language allows programmers to define
program-specific data types through the use of structures and
classes.
 Instances of these datatypes are known as objects and can contain
member variables, constants, member functions, and overloaded
operators defined by the programmer.
 Syntactically, structures and classes are extensions of the C struct
datatype, which cannot contain functions or overloaded operators.

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 5
Differences between C structs and C++ classes

 C structs only contain globally visible data types

 C++ classes include data types (attributes) and in addition member


functions (methods) and overloaded operators
 C++ classes have different sections to control the visibility of the
attributes and methods
 C++ classes support inheritance and polymorphism (will be shown
later)

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 6
 Direct access to data controllable via scope
 private  only methods of the class
 protected  only methods from the class or from derived classes
 public  all classes
 Better coding style: provide getter and setter functions
 access is controlled
 illegal parameters and operations can be avoided
 exceptions can be handled
 Initialization via Constructors
 Initialization supports different parameter sets
 Copy-Constructor supports controlled copying of contents of other
objects

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 7
One major problem of programming are variables containing the wrong
data
 Ariane rocket
 Mars explorer
 …

Causes
 Forgotten initialization (read before write)
 Implementation bugs (meter versus feet)
 Corrupted pointers
 Arrays out of bounces
 Unbalanced operations
 …and some pitfalls of the C-language

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 8
#include <iostream>
#include <stdlib.h>
using namespace std;

#include "CInit.h"

int global_a = 12;


int global_b = global_a;

int main (void)


{
int c = 123;
struct sCoordinate{
int x = 0;
int y = 0;
}

class CCoordinate
{
public:
int m_x = 0;
int m_y = 0;
}

error C2864: 'sCoordinate::x' : only static const integral data members can
be initialized within a class
error C2864: 'CCoordinate::m_x' : only static const integral data members
can be initialized within a class

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 10
To initialize variables, memory must be allocated.

The relevant question seems: When is it allocated


 Global variables  upon declaration
 Local variables  upon declaration

 Structs  upon declaration of a variable using the struct


 Classes  upon declaration of objects of the class

Classes describe the object structure, they do not allocate


memory.

At least not for “normal” member variables  static members will be handled later.

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 11
Classes are comparable to variable types
Objects are comparable to variables

int myIntegerVariable = 0;

Variable Initial
Type
Identifier Value

CCoordinate myCoordinate(0,4)

Object Parameters for


Class
Identifier Constructor

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 12
What’s the difference between:

int a;
int b = 0;
int c = 123;

void main()
{
int aa;
int bb = 0;
int cc = 123;

int d;
d = 123;
}

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 13
Why is this not possible:

CCoordinate myCoordinate1 = (0,4);

But how about this:


string myString = “Hello world”

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 14
The initialization of object is more complex than simple variables

 Several variables inside the object need to be initialized


 Values are checked for valid range
 Dynamic memory is assigned
 …

Initialization of objects is performed by a specific function, the


Constructor

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 15
 Constructors behave “almost” similar to normal operations
 The are called automatically whenever an object is generated
 by declaration
 by allocation using new
 They may be called manually to generate a temporary object (e.g.
parameter, return value)
 Mandatory!

 Conventions
 Name of the Class
 No return value
 Parameters and default parameters supported
 Number of constructors 1..n

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 16
 The “this” Pointer points to the member variables of the object
currently “in use”
 It is automatically added to every method call by the compiler
 It is equal to the address of the first member variable of the object
 It ensures that the operations are performed on the right data

o1

Class m_x = 123 0x1000 o1.this o1.set(1,2)


m_y = 456 0x1004
int m_x;
int m_y; o2

set(int x, int y) m_x = 123 0x1008 o2.this o2.set(3,4)


m_y = 456 0x100C
Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 17
class CCoordinate
{
public:
int m_x;
int m_y;

public:
CCoordinate()
{
cout << "Just generated a CCoordinate object at " << this << endl;
m_x = 0;
m_y = 0; }

};

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 18
class CCoordinate2
{
public:
int m_x;
int m_y;

public:
CCoordinate2(int x, int y)
{
if (x>0 && y>0)
{
m_x = x;
m_y = y;
}
else
{
m_x = 0;
m_y = 0;
}
cout << "Just generated a CCoordinate object at " << this << " with
the values (" << m_x << ", " << m_y << ")" << endl;
}
};

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 19
class CCoordinate3
{
public:
int m_x;
int m_y;
string m_name;

public:
CCoordinate3(int x = 0, int y = 0, string name = "NoName")
{
m_name = name;
if (x>0 && y>0)
{
m_x = x; Default-Parameters are
m_y = y;
}
a new feature of C++
else
{
m_x = 0;
m_y = 0;
}
cout << "Generated a CCoordinate object called " << m_name << " at "
<< this << " with the values (" << m_x << ", " << m_y << ")" << endl;
}
};
Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 20
//Declaration in the class.h file

class myclass{ More about this in the


private: lecture about inheritance
int m_x, m_y;

public:
myclass() {m_x = 0; m_y = 0;}
myclass(int a, int b) : m_x(a), m_y(b) {};
myclass(int a); // Implementation  C file
}

//Definition
myclass::myclass(int a)
{
m_x = a;
m_y = a;
}

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 21
 Always provide a constructor
 Provide parameters including default values for improved flexibility
 Use the constructor for range checks
 Use the this-Pointer for easy trace information

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 22
 Destructors behave “almost” similar like normal operations
 The are called automatically whenever an object is destroyed
 local object after leaving the function
 global object after leaving the program
 deletion of allocated memory
 They should not be called manually
 Only needed when cleanup operations are required (delete dynamic
memory, releasing of ressources)

 Conventions
 Name of the Class, preceded by ~
 No return value, no parameters
 Number of destructors 0..1

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 23
class CCoordinate4
{
public:
int m_x;
int m_y;
string m_name;

public:
CCoordinate4(int x = 0, int y = 0, string name = "NoName");
~CCoordinate()
{
cout << "Destroying CCoordinate4 object at " << this << endl;
}
};

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 24
Definition:

 A copy constructor is a special constructor in the C++ programming


language used to create a new object as a copy of an existing object.
This constructor takes a single argument: a reference to the object to
be copied.
 Normally the compiler automatically creates a copy constructor for
each class (known as an implicit copy constructor) , which performs a
bitwise copy of the data. For special cases this is not sufficient and
the programmer creates the copy constructor, known as an explicit
copy constructor. In such cases, the compiler doesn't create one.
 A copy constructor is generally needed when an object owns pointers
or non-shareable references such as to a file, because the default
copy constructor only copies the pointer to the data structure  both
instances would work on the same memory  conflict

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 25
 The copy constructor is defined by passing a reference to the class
as parameter.
 Additional parameter may be added, but a default value must be
provided

Examples:
 X(X const&);  recommended, because the reference may
not be modified
 X(X&);
 X(X const volatile&);
 X(X volatile&);
 X(X const&, int = 10);
 X(X const&, double = 1.0, int = 40);

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 26
class CCoordinate5
{
public:
int m_x;
int m_y;
string m_name;

public:
CCoordinate5(int x = 0, int y = 0, string name = "NoName");
CCoordinate5(CCoordinate5& origin)
{
cout << "Copy constructor, copying from object " << &origin << " to
" << this << endl;
m_x = origin.m_x;
m_y = origin.m_y;
m_name = "Oh, not him again " + origin.m_name; //Just to see the
difference
cout << " Called " << m_name << " with the values (" << m_x
<< ", " << m_y << ")" << endl;
}
~CCoordinate5();
};

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 27
//Copy Constructor
CCoordinate5 myCoordinate51(1,2,"Joe");
CCoordinate5 myCoordinate52 = myCoordinate51; //Copy constructor called
CCoordinate5 myCoordinate53(myCoordinate51); //Copy constructor called

sampleFunction(myCoordinate53); //Copy constructor called

myCoordinate53 = myCoordinate51; //Not called

Called upon copy-initialization


Called for parameter passing for functions

Not called for assignments  overloaded = operator

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 28
Memory on a CPU is divided into (at least) 2 segments, heap and stack

Stack
 Used in examples up to now
 Implemented as FILO (First In Last Out) buffer
 Used for function/block local variables

Heap
 Known from “C” (malloc/free)
 Used by global data having fixed addresses
 Used for dynamic memory objects (generated e.g. by malloc or new)

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 29
Function local data (Stack)

Dynamic memory
(RAM)

Dynamic global data (Heap)

Static global data Static memory


Program Code (ROM / RAM)

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 30
Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 31
 Size of the matrix is not known at compile time
 Of course we could assume a maximum number of elements, but this
would spoil (expensive) memory

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 32
 The size of the matrix has to be dynamic, i.e. it is defined during
runtime
 Certain operations are only supported for certain sizes

Impact?

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 33
The malloc function is one of the functions in standard C to allocate
memory. Its function prototype is
 void *malloc(size_t size);
which allocates size bytes of memory. If the allocation succeeds, a
pointer to the block of memory is returned, else a null pointer is returned.

Memory allocated via malloc is persistent: it will continue to exist until the
program terminates or the memory is explicitly deallocated by the
programmer (that is, the block is said to be "freed"). This is achieved by
use of the free function. Its prototype is
 void free(void *pointer);

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 34
In the C++ programming language, new is an operator that allows
dynamic memory allocation on the heap for any kind of object incl.
classes.
Syntax:
 p_var = new typename; // Return a typed
pointer to the
allocated memory
 p_var = new typename(5); // Initialisation
 p_var = new typename[3]; // Array

Comparison with malloc


 Returns a typed pointer
 Calls the constructor (primitive types are not initialized!)
 Errors are handled via std::bad_alloc (to be detailed later)
Life Demo:
Free memory: CCoordinate on heap
delete p_var;
delete[] p_var;
Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 35
int *p; // Declaration of a pointer to an integer
p = new(int); // Assigning memory on the heap
*p = 5; // Storing the number 5 at the allocated
// memory

cout << &p; // The address of p on the heap


cout << p; // The content of p
// i.e. the start address of the allocated
// heap memory
cout << *p; // The dereferenced content of the
// allocated memory, 5

Stack (local Variable)


Heap (Dynamic Object)

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, adapted by Prof. Dr.-Ing. M. Lipp 14/10/15 36
// Global section Adress Content
struct twoints{
int struct1; 0x1000 int1 = 4
int struct2;}; 0x1004 s1.struct1 = 10
int int1 = 4 0x1008 s1.struct2 = 11
struct twoints s1; 0x100C ps1 = 0x1020
s1.struct1=10;
s1.struct2=11; 0x1010 ps2 = 0x1020
0x1014
struct twoints* ps1;
struct twoints* ps2; 0x1018
ps1 = malloc(sizeof(twoints));
ps1->struct1=20; 0x101C
ps1->struct2=21;
0x1020 ps1->struct1 = 20
ps2 = ps1; 0x1024 ps1->struct2 = 21
0x1028

...
Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, adapted by Prof. Dr.-Ing. M. Lipp 14/10/15 37
Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, adapted by Prof. Dr.-Ing. M. Lipp 14/10/15 38
Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, adapted by Prof. Dr.-Ing. M. Lipp 14/10/15 39
Basic diagram
 Starting point
 End point
 Activities
 Decisions
 Transitions

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, adapted by Prof. Dr.-Ing. M. Lipp 14/10/15 40
Extensions
 Join and fork show parallel activities
 E.g. tasks in an OS

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, adapted by Prof. Dr.-Ing. M. Lipp 14/10/15 41
Extensions
 Swimlanes indicate processes (e.g. client server)
 Signal receivers can be used to show messages (network, between
processes / threads of an OS)

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, adapted by Prof. Dr.-Ing. M. Lipp 14/10/15 42
Problem: To store more complex data structure in memory, a
transformation has to be defined

Logical structure Physical structure

0,0 0,1 0,2 0,0 0,1 0,2 1,0 1,1 1,2 element
1,0 1,1 1,2 1000 1004 1008 1012 1016 1020 address

address = offset + (element_column + column_size * element_row) * element_size


addres(1,1) = ???

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, adapted by Prof. Dr.-Ing. M. Lipp 14/10/15 43
m_size = m_rows*m_columns ;

//Allocate memory for the matrix


m_pArray = new double[m_size];

//Temporary pointer for iterating through the array


//Note: Never change the variable containing the start adress
double* p=m_pArray ;

//Initialize the matrix


switch (ini_mode)
{
case INIT_ZEROS:
for (int k=0 ; k<m_size; k++) {
*p++ = 0.0;
}
break ;
case INIT_UNIT:
for (int k=0; k<m_size; k++) {
*p++ = 0.0;
}
//This one only works with quadratic matrices Transformation
if (m_rows == m_columns) {
for (int k=0; k<m_columns; k++) {
*(m_pArray+k*m_columns+k) = 1.0 ;
}
break ;
}

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, adapted by Prof. Dr.-Ing. M. Lipp 14/10/15 44
CMatrix::~CMatrix()
{
cout << "Destructor " << m_count << endl ;
//One element less
m_count-- ;
if (m_count == 0){
system("pause") ;
}
delete[] m_pArray ; // free allocated memory
}

With dynamic members, the destructor is mandatory!

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, adapted by Prof. Dr.-Ing. M. Lipp 14/10/15 45
How are we going to implement the copy constructor?

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, adapted by Prof. Dr.-Ing. M. Lipp 14/10/15 46
 Allocation of memory for objects
 This Pointer

 Wrong initialization of data is a common cause of programming errors


 C++ provides the following operations for initialization of data
 Constructor
 Destructor
 Copy Constructor

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 14/10/15 47

You might also like