More C++ Features True object initialisation

Slides:



Advertisements
Similar presentations
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Advertisements

Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
Introduction to Programming Lecture 39. Copy Constructor.
Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
C++ Lecture 6 Object Life-times Creating objects using new Using pointers to objects Aggregation (Containment –UML speak) Other C++ class features.
Classes: A Deeper Look Systems Programming.  constconst  const objects and const member functions   Composition   Friendship  this  this pointer.
Class and Objects.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Classes Separating interface from implementation
Classes: A Deeper Look Systems Programming.
Copy Constructors Shallow Copy: –The data members of one object are copied into the data members of another object without taking any dynamic memory pointed.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Operator Overloading in C++
Review of C++ Programming Part II Sheng-Fang Huang.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
Pointer Data Type and Pointer Variables
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Pointer and Array Lists Chapter 3, Summary CS 244 Brent M. Dingle, Ph.D. Game Design and Development Program Department of Mathematics, Statistics, and.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Object-Based Programming Mostly Review. Objects Review what is object? class? member variables? member functions? public members? private members? friend.
Chapter 9 Classes: A Deeper Look, Part I Part II.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
1 CSC241: Object Oriented Programming Lecture No 05.
1 Mr. Muhammad Hanif Lecturer Information Technology MBBS Campus Dadu University of SIndh.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 1.
1 Memory as byte array Pointers Arrays relationship to pointers Operator ‘new’ Operator ‘delete’ Copy ctor Assignment operator ‘this’ const pointer Allocating.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
Object Lifetimes and Dynamic Objects Lecture-7. Object Lifetimes and Dynamic Objects External (Global) Objects Persistent (in existence) throughout the.
Yan Shi CS/SE 2630 Lecture Notes
Pointers and Dynamic Arrays
Learning Objectives Pointers as dada members
The C++ programming language
Andy Wang Object Oriented Programming in C++ COP 3330
Constructor & Destructor
Class: Special Topics Copy Constructors Static members Friends this
Memberwise Assignment / Initialization
This pointer, Dynamic memory allocation, Constructors and Destructor
Dynamically Allocated Memory
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
9-10 Classes: A Deeper Look.
Recitation Course 0603 Speaker: Liu Yu-Jiun.
CS410 – Software Engineering Lecture #5: C++ Basics III
The C++ programming language
COP 3330 Object-oriented Programming in C++
COP 3330 Object-oriented Programming in C++
Class: Special Topics 2 For classes using memory allocation
Destructors, Copy Constructors & Copy Assignment Operators
Destructors, Copy Constructors & Copy Assignment Operators
9-10 Classes: A Deeper Look.
SPL – PS3 C++ Classes.
Presentation transcript:

More C++ Features 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 What about default function argument? What about a default constructor?

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

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 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.

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