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

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

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

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

CS212: Object Oriented Analysis and Design

Lecture 6: Friends, Constructor and destructors

Page 2: 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

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

Today’s objective

• Friendly classes and function

• Constructors

• Default Argument

• Destructors

Page 4: CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and 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

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

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.

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

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

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

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

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

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.

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

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

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

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

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

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

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

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

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

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();

//...};

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

Efficient … (contd.)

class string{

private:char * pc;size_t capacity;size_t length;enum { DEFAULT_SIZE = 32};

// following function is called by every constructorvoid 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;

}

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

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;

}

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

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; }};

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

A special case

• Applicable to constructor with exactly one parameter

• Implicit type conversion

• Demonstration

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

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

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

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

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

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

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

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.

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

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

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

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

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

Thank youNext Lecture: Arrays, Pointers and Dynamic Allocation