more c++ features true object initialisation composition (a type of aggregation) copy constructor...

21
More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to objects

Upload: chloe-harper

Post on 05-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

More C++ Features

True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to objects

Page 2: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

True object initialisation

Without a constructor function an object’s member data is created with random values

A constructor function can assign values to the member data overwriting the random values

True initialisation allows the constructor to create the member data with an initial value – subtly different from assignment!

Initialisation is achieved through the member initialisation list

Allows initialisation of constants in member data.

Page 3: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

Object Assignment

class CBulb {public:

CBulb(int p, int s);private:

int power;int state;

};CBulb::CBulb (int p, int s){

state = s;power = p;

}

Note: This is not a complete class definition. Only the statements relevant to the topic are shown

When the object is created :-CBulb billy(60, 0);state and power are created

with random values and immediately overwritten with new values in the assignment

Page 4: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

Object Initialisation

class CBulb {

… As in previous slide

};

CBulb::CBulb (int p, int s) : state(s), power(p){}

Start of member initialisation list

comma separated list of member data with initial values in parentheses

Page 5: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

Aggregation

Object relationships Aggregation of objects Aggregation forms object hierarchies The “has a” or “part of” relationship between

objects 1 to 1 1 to n (n = 0,1,… up to n)

Page 6: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

Composition - CLamp class

A CBulb class – example code A CSwitch class – example code A lamp is composed of a bulb and a switch or

– A lamp “has a “ bulb– A lamp “has a” switch

A composite class – CLamp– Clamp has an instance of a CSwitch and a CBulb as

member data

Composition is one type of aggregation

Page 7: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

Copy constructor and assignment

When a copy of an object is required (e.g. passing an object by value) a copy is required.

Assignment operator =– Consider :- CAny x, y; and the statement x = y;– binary operators such as = are interpreted as

x.operator=(y) – i.e. x is an instance of a class with a member function called

operator with an argument y.– operator= also requires a copy to be performed.

The compiler supplied default copy constructor does a member-wise copy; often this is sufficient.

The compiler supplied default operator= does a member-wise copy; again often sufficient.

Page 8: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

User supplied copy constructor• consider class CPatient used in previous slidesclass CPatient {private:

char name[30];int age;char gender;

public:CPatient (const CPatient & s); //copy constructor// etc.

copy constructor is defined:-CPatient::CPatient (const CPatient & s){

gender = s.gender;age = s.age;strcpy(name, s.name);

}

Page 9: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

User supplied operator=Consider class CPatient used in previous slidesclass CPatient {private:

char name[30];int age;char gender;

public:const CPatient& operator= (const CPatient& s); // assignment operator// etc.

Assignment operator is defined:-const CPatient& CPatient::operator= (const CPatient& s){

if (this == &s) // avoid self assignment – “this” is a pointer to the invoking object{

gender = s.gender;age = s.age;strcpy(name, s.name);

}return (*this); // return the invoking object

}

Page 10: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

The default copy constructor and operator=

The previous copy constructor and assignment operator are exactly the same as those that would be supplied by the compiler.

Therefore we can often use the defaults provided by the compiler

The operator= function is an example of operator overloading. Most of the standard operators may be overloaded

The operator= function must be a member function of the class

Page 11: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

Pointers

In many cases it is often preferable to manipulate objects via pointers rather than directly.

Direct method– An object can be created :- CAny x;– manipulated directly using

x.member_function(any_arguments); Using pointers

– CAny *op; //op is a pointer to an object of the class CAny– op = &x; //op is now pointing at x– member functions are invoked using ->– op->member_function(any_arguments);

Page 12: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

Dynamic memory

Global variables and objects – are stored in static memory – exist during the life of a program

Local variables and objects – are stored in the stack memory – use stack memory that is allocated and de-allocated automatically– are allocated at point of declaration– are de-allocated when they go out of scope

Dynamic variables and objects– Use the Heap memory– programmer is responsible for allocation and de-allocation of heap memory– new keyword allocates memory– delete keyword de-allocates memory

Page 13: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

new keyword

new allocates memory space from heap new returns with a pointer to the allocated memory new returns with 0 if no memory is available Good for creating variable length arrays at run-time General format

– for primitive data types pointer = new data_type; //single variable pointer = new data_type[ number required]; //array

– for user defined types i.e. classes pointer = new classname(constructor arguments); //single object pointer = new classname[number required]; //array – must have a

default constructor

Page 14: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

Dynamic memory

Examplesfloat * fp = new float; // creates 1 float

int * p = new int[50]; // creates an array of 50 int’s accessible either through the pointer p or using conventional array notation p[index]

CBulb * bp = new CBulb(60,0); // creates the bulb object in the heap memory and bp is set pointing at the bulb.

Page 15: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

delete keyword

delete de-allocates the memory originally allocated by new.

must use the pointer that was allocated with new

Examples– delete fp;– delete [ ]p; // notice empty [ ] for releasing arrays– delete bp;

Page 16: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

Use of new and delete

Consider CPatient class in previous lecture The data member name was a fixed char

array of 30 characters What if name is more than 30 characters? Most names are less than 30 characters –

wastes space Use dynamic memory

Page 17: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

Use of new and deleteclass CPatient {private:

char * p;int age;// etc.

constructorCPatient::CPatient(char * n, int a, char g){

// find length of n and add 1 for null character //allocate that many chars and set p pointing //at the allocated memoryp = new char[ strlen(n) + 1];strcpy(p,n);// etc

destructorCPatient::~CPatient(){

delete p[ ];}

Constructor allocates memory dynamicallyallocating only the memory required for the

string

Destructor now required to de-allocate memory

name is replaced with p; a pointer to char

Page 18: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

Issues with use of new in classes

What about assignment operator = What about copy constructor? Defaults supplied by compiler perform “member-

wise” copy Problems with pointers!

– member-wise copy only pointer is copied – shallow copy– copy pointer and data pointed to by pointer - Deep copy

Page 19: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

Use of new and delete

class CPatient {private:

char * p;int age;// etc.

constructorCPatient::CPatient(char * n, int a, char g){

// find length of n and add 1 for null character //allocate that many chars and set p pointing //at the allocated memoryp = new char[ strlen(n) + 1];strcpy(p,n);// etc

destructorCPatient::~CPatient(){

delete p[ ];}

Constructor allocates memory dynamicallyallocating only the memory required for the string

Destructor now required to de-allocate memory

name is replaced with p; a pointer to char

Page 20: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

Deep copy

Need to copy member data and any data that is used by pointers

May also need to modify other member functions

See Cpatient modifications

Page 21: More C++ Features True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to

Next lecture

Object Life-times Aggregation vs composition