CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.

Slides:



Advertisements
Similar presentations
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Advertisements

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.
Classes: A Deeper Look Systems Programming.  constconst  const objects and const member functions   Composition   Friendship  this  this pointer.
Class and Objects.
OOP Using Classes - I. Structures vs. Classes C-style structures –No “interface” If implementation changes, all programs using that struct must change.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
Classes: A Deeper Look Systems Programming.
A Deeper Look at Classes CS-2303, C-Term A Deeper Look at Classes CS-2303 System Programming Concepts (Slides include materials from The C Programming.
Lecture 9 Concepts of Programming Languages
More C++ Classes Systems Programming. Systems Programming: C++ Classes 2 Systems Programming: 2 C++ Classes  Preprocessor Wrapper  Time Class Case Study.
Review of C++ Programming Part II Sheng-Fang Huang.
OOP Languages: Java vs C++
Chapter 12: Adding Functionality to Your Classes.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
CSE 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
You gotta be cool. Access Functions and Utility Functions Preprocessor Wrapper Looking Ahead to Composition and Inheritance Object Size Class Scope and.
Pointer Data Type and Pointer Variables
The Rest of the Story.  Constructors  Compiler-generated  The Initializer List  Copy Constructors  Single-arg (conversion ctors)  The Assignment.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
More C++ Classes Systems Programming. C++ Classes  Preprocessor Wrapper  Time Class Case Study –Two versions (old and new)  Class Scope and Assessing.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
CS212: Object Oriented Analysis and Design Lecture 5: Classes and Objects - II.
Learners Support Publications Classes and Objects.
C++ Class Members Class Definition – class Name – { – public: » constructor(s) » destructor » function members » data members – protected: » function members.
Object Oriented Programming Elhanan Borenstein Lecture #3 copyrights © Elhanan Borenstein.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
More C++ Features True object initialisation
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
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.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
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 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
1 Mr. Muhammad Hanif Lecturer Information Technology MBBS Campus Dadu University of SIndh.
CS212: Object Oriented Analysis and Design Lecture 22: Generic Class Design.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 1.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Structs and Classes Structs A struct can be used to define a data structure type as follows: struct Complex { double real, imag;} // specifying a Complex.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Learners Support Publications Constructors and Destructors.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Object Lifetimes and Dynamic Objects Lecture-7. Object Lifetimes and Dynamic Objects External (Global) Objects Persistent (in existence) throughout the.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Introduction of Object Oriented Programming.
Constructors and Destructors
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Programming with ANSI C ++
Constructor & Destructor
Class: Special Topics Copy Constructors Static members Friends this
Lecture 9 Concepts of Programming Languages
CS212: Object Oriented Analysis and Design
Constructors and destructors
Constructors and Destructors
Classes and Objects.
CS410 – Software Engineering Lecture #5: C++ Basics III
Destructors, Copy Constructors & Copy Assignment Operators
Destructors, Copy Constructors & Copy Assignment Operators
More C++ Classes Systems Programming.
SPL – PS3 C++ Classes.
Object Oriented Programming
Lecture 9 Concepts of Programming Languages
Presentation transcript:

CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors

Recap of Lecture 5 Scope of class members Nesting member function Class members and arrays Static class members

Today’s objective Friendly classes and function Constructors Default Argument Destructors

Friend function A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions. A friend can be a function, function template, or member function, or a class or class template

Properties of friend functions Friend of the class can be member of some other class. Friend of one class can be friend of another class or all the classes in one program: GLOBAL FRIEND. Can access the private or protected members of the class in which they are declared to be friend, but they can use the members for a specific object Do not get “this” pointer. Can be friend of more than one class, hence they can be used for message passing between the classes. Can be declared anywhere (in public, protected or private section) in the class.

When to use friend function Three different circumstances where friend functions are useful Operator overloading - for certain types of operators Creation of I/O operations Multiple classes share common functionality

Friend Class Friendship may allow a class to be better encapsulated by granting per-class access to parts of its API that would otherwise have to be public. This increased encapsulation comes at the cost of tighter coupling between classes Friendships are not symmetric Friendships are not transitive Friendships are not inherited Access due to friendship is inherited

Constructors void foo() { int n = 5; double z[10] = { 0.0 }; struct gizmo { int i, j; } w = { 3, 4 }; ····· } All of the variables are created at block entry when foo() is invoked. Uses a runtime system stack. The class needs a mechanism to specify object creation and destruction so that a client can use objects like native types.

Constructors It is a member function whose name is the same as the class name It creates objects of the class type It involves initializing data members Allocating storage from the heap by using new. The simplest use of a constructor is for initialization. Demonstration

Implicit Constructor An implicitly-declared default constructor is an inline public member of its class It performs the initialization operations that are needed by the implementation to create an object of this type. These operations do not involve initialization of user- declared data members or allocation of memory from the free store Demonstration

Parameterized Constructors It may be necessary to initialize different member variables with different values To achieve this we can pass arguments to a constructor The constructor that can take arguments are called parameterized constructors Implicit and Explicit calling of parameterized constructors Demonstration

Multiple Constructors in a Class There can be multiple constructors in a class Each function has its own significance In some cases it is necessary to have both parameterized and default constructors Avoid Reduplicating Identical Pieces Of Constructors' Code

Efficient constructor design class string { private: char * pc; size_t capacity; size_t length; enum { DEFAULT_SIZE = 32}; public: string(const char * s); string(size_t initial_capacity ); string(); //... };

Efficient … (contd.) class string { private: char * pc; size_t capacity; size_t length; enum { DEFAULT_SIZE = 32}; // following function is called by every constructor void init( size_t cap = DEFAULT_SIZE); public: string(const char * s); string(size_t initial_capacity ); string(); //...other member functions }; void string::init( size_t cap) { pc = new char[cap]; capacity = cap; }

Efficient … (contd.) string::string(const char * s) { size_t size = strlen (s); init(size + 1); length = size; strcpy(pc, s); } string::string(size_t initial_capacity ) { init(initial_capacity); length=0; } string::string() { init(); length = 0; }

Default Argument class Fraction { private: int m_nNumerator; int m_nDenominator; public: // Default constructor Fraction(int nNumerator=0, int nDenominator=1) { m_nNumerator = nNumerator; m_nDenominator = nDenominator; } int GetNumerator() { return m_nNumerator; } int GetDenominator() { return m_nDenominator; } };

A special case Applicable to constructor with exactly one parameter Implicit type conversion Demonstration

Is A Default Constructor Always Necessary? The existence of a user-defined constructor blocks the synthesis of an implicitly-declared default constructor. A class with no default constructor limits its users to a narrower set of allowed uses. Demonstration

Constant Object Class objects can be made constant using the const keyword Constant variables must be initialized at time of creation In the case of classes, this initialization is done via constructors Once initialized via constructor, any attempt to modify the member variables of the object is disallowed It would violate the const(ant)-ness of the object

Constant object Changing member variables directly (if they are public) is not allowed Calling member functions that sets the value of member variables is not allowed const class objects can only call const member functions

Trivial Constructors Compilers synthesize a default constructor for every class unless a constructor was already defined by the user Such a synthesized constructor is redundant A constructor is considered trivial when all the following hold true: Its class has no virtual member functions and no virtual base classes. All the direct base classes of the constructor's class have trivial constructors. All the member objects in the constructor's class have trivial constructors.

Destructors It is a member function whose name is the class name preceded by the tilde ~ character A destructor’s usual purpose is finalizing or destroying objects of the class type. Finalizing objects involves retrieving resources allocated to the object. Requires using delete to deallocate store assigned to the object. They can not be overloaded or take arguments

When constructor and destructors are called An object's constructor is called when the object comes into existence An object's destructor is called when the object is destroyed For a local object: constructor  object's declaration, destructor  reverse order of constructor For a global object: constructor  before main(),, in order of their declaration, within the same file destructor  reverse order of constructor, after main() has terminated

Thank you Next Lecture: Arrays, Pointers and Dynamic Allocation