1 of 24

CS300: Object Oriented Analysis and Design

Friends, Constructors and Destructors

(Using C++)

2 of 24

Recap of last week

  • Class and Objects
    • Identification
    • Design of attributes and functionalities
    • Getter and Setters
  • Class Interface

Object Oriented Anslysis and Design (CS 212)

3 of 24

Class Interface Diagram

Private data:

hrs

mins

secs

Set

Increment

Write

Time

Time

Time class

Object Oriented Anslysis and Design (CS 212)

4 of 24

Friend function

  • A friend function of a class is defined
    • Outside that class' scope
    • Has the right to access all private and protected members of the class.

  • Friends are not member functions.

  • Their prototypes appear in the class definition.

  • A friend can be a
    • function

Object Oriented Anslysis and Design (CS 212)

5 of 24

Properties of friend functions

  • Friend of the class can be member of more than one class.
  • Friend of one class can be GLOBAL FRIEND.
  • Can access the private or protected members of the friend.
  • Do not get “this” pointer.
  • They can be used for message passing between the classes.
  • Can be declared anywhere in

Object Oriented Anslysis and Design (CS 212)

6 of 24

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

Object Oriented Anslysis and Design (CS 212)

7 of 24

Friend Class

  • Friendship may allow a class to be better encapsulated

    • 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

Object Oriented Anslysis and Design (CS 212)

8 of 24

Construction and Destruction

Object Oriented Anslysis and Design (CS 212)

9 of 24

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.

Object Oriented Anslysis and Design (CS 212)

10 of 24

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

Object Oriented Anslysis and Design (CS 212)

11 of 24

Implicit Constructor

  • An implicitly-declared default constructor is an inline public member of its class

  • It performs the initialization operations

  • That are needed 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

Object Oriented Anslysis and Design (CS 212)

12 of 24

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

Object Oriented Anslysis and Design (CS 212)

13 of 24

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

Object Oriented Anslysis and Design (CS 212)

14 of 24

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

//...

};

Object Oriented Anslysis and Design (CS 212)

15 of 24

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;

}

Object Oriented Anslysis and Design (CS 212)

16 of 24

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;

}

Object Oriented Anslysis and Design (CS 212)

17 of 24

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

};

Object Oriented Anslysis and Design (CS 212)

18 of 24

A special case

  • Applicable to constructor with exactly one parameter

  • Implicit type conversion

Object Oriented Anslysis and Design (CS 212)

19 of 24

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.

Object Oriented Anslysis and Design (CS 212)

20 of 24

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

Object Oriented Anslysis and Design (CS 212)

21 of 24

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

Object Oriented Anslysis and Design (CS 212)

22 of 24

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.

Object Oriented Anslysis and Design (CS 212)

23 of 24

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.

Object Oriented Anslysis and Design (CS 212)

24 of 24

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

Object Oriented Anslysis and Design (CS 212)