210 likes | 403 Views
C++ - Lecture 3. True object initialisation Composition (a type of aggregation) Copy constructor and assignment operator = Dynamic Memory Pointers to objects. True object initialisation. Without a constructor function an object’s member data is created with random values
E N D
C++ - Lecture 3 • True object initialisation • Composition (a type of aggregation) • Copy constructor and assignment operator = • Dynamic Memory • Pointers to objects
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.
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
Start of member initialisation list CBulb::CBulb (int p, int s) : state(s), power(p) { } Object Initialisation class CBulb { … As in previous slide }; comma separated list of member data with initial values in parentheses
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)
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
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 asx.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.
User supplied copy constructor • consider class CPatient used in previous slides class 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); }
User supplied operator= Consider class CPatient used in previous slides class 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 }
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
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);
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
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
Dynamic memory • Examples float * 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.
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;
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
Use of new and delete class CPatient { private: char * p; int age; // etc. constructor CPatient::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 memory p = new char[ strlen(n) + 1]; strcpy(p,n); // etc destructor CPatient::~CPatient() { delete p[ ]; } name is replaced with p; a pointer to char Constructor allocates memory dynamically allocating only the memory required for the string Destructor now required to de-allocate memory
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
Use of new and delete name is replaced with p; a pointer to char class CPatient { private: char * p; int age; // etc. constructor CPatient::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 memory p = new char[ strlen(n) + 1]; strcpy(p,n); // etc destructor CPatient::~CPatient() { delete p[ ]; } Constructor allocates memory dynamically allocating only the memory required for the string Destructor now required to de-allocate memory
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
Next lecture • Object Life-times • Aggregation vs composition