You are on page 1of 39

ACCESS FUNCTIONS,FRIEND FUNCTIONS,

CONST FUNCTIONS & DYNAMIC ARRAYS


Static Member Functions
• By simply making the static utility
functions members, they have class tree {
direct access to the node class' •••
public members, even if the node private:
node* root; //root node of tree
class is defined in the tree class' static void copy(node* &, const node*);
private section. This can be done static void destroy(node*);
without declaring our functions as static tree::node* add(node*, node*);
static void traverse(const node*);
friends.
• Static member functions do not
have a this pointer, just like non-
member functions.

This pointer -> current obj


Static Member Functions
tree::tree(const tree &tree) : //copy constructor
root(0) {
copy(root, tree.root);
}

//This is the implementation of a static member function


void tree::copy(node* &new_node, const node* old_node) {
if(old_node) {
new_node = new node(old_node->emp);
copy(new_node->left, old_node->left);
copy(new_node->right, old_node->right);
}
}
Static Members
• Shared properties are represented by static class members.
Static class members can be either static data members or
static member functions. These members can be declared in
either the public, protected, or private sections of a class
interface.
• When a member function is declared as static, we are not
limited to using this function through an object of that class.
This function can be used anywhere it is legal to use the class
itself. This is because static member functions are invoked
independent of the objects and do not contain a this pointer.
• It can be called via: class::function(args)
Static Members
• To specify static member functions, we must declare the
functions to be static in the class definition (interface file) using
the keyword static .
• Then, define those static member functions in the class
implementation file.
• The definition of our static member functions should look
identical to the definition of non-static member functions.
• The scope of a static member function is the same as that of a
non-static member function.
• Access to a static member function from outside the class is the
same as access to a non-static member function and depends on
whether the member is declared as public, protected, or private.
Class Student
Static Data Members {
private:
• When we use the keyword static in the static int marks;
declaration a data member, only one occurrence };
Int main()
of that data member exists for all instances of
{
the class. Such data members belong to the class
student s1, s2;
and not to an individual object and are called
static data members. Static data represents class
data rather than object data. marks
• To specify a static data member, we must supply s1
the declaration inside the class interface and the
definition outside the class interface. Unlike a
non-static data member, a static data member's
s2
declaration does not cause memory to be
allocated when an object is defined.

OBJECT -> INSTANCE OF A CLASS


Static Data Members
//static data member declaration (class interface)
class class_name {
...
static data_type static_data_member=7;
...
};
• A static data member's definition must be supplied only once and is
usually placed in the class implementation file. A static data
member's definition must be preceded by the class name and the
scope resolution operator before the static data member's identifier.

//static data member definition (class implementation)


data_type class_name::static_data_member = initial_value;
• data_type class_name:: Static_data_member++;
Static Data Members
• It is important to realize that memory is allocated for
static data members when we explicitly define those
static data members, not when we declare the static data
members as part of a class definition. Think of the static
data member declarations within a class as external
references to data members defined elsewhere.
• Clients can access a public static data member by saying
class_name::static_data_member
• It is also possible for clients to access a public static data
member once an object is defined for that class by saying
object_name.static_data_member.
Access functions

• To allow clients to read the value of private data, the class can provide a get function.
• To allow clients to modify private data, the class can provide a set function.
 

ACCESSOR VS MUTATOR
#include <iostream> void main()
 
class rectangle {
{ rectangle rc(1.0, 3.0);
private:
float height; float rectangle::get_height() float value;
float width; {
int xpos; return (height);  
}
int ypos;  
value = rc.get_height();
void rectangle::set_height(float h)
public: {
rectangle(float, float); // height = h; cout << "height: " << value << endl;
}
constructor    
void draw(); // draw rc.set_height(10.0);
member function
void posn(int, int); // position value = rc.get_height();
member function
void move(int, int); // move cout << "height: " << value << endl;
member function  
float get_height(); // }
access function
void set_height(float); //
access function
};
How to Define Function equal
12/12 12TH Dec Equal -> dates if they are same

• The function equal, is not a member function Get_month() & get_day() :


• It must use public accessor functions to obtain the member fun of DAY of Year
day and month from a DayOfYear object
• equal can be defined in this way:

bool equal(DayOfYear date1, DayOfYear date2)


{
return ( date1.get_month( ) == date2.get_month( )
&&
date1.get_day( ) == date2.get_day( ) );
}
A More Efficient equal
• As defined here, equal is more efficient,
but not legal
bool equal(DayOfYear date1, DayOfYear date2)
{
return (date1.month = = date2.month
&&
date1.day = = date2.day );
}
• The code is simpler and more efficient
• Direct access of private member variables is not legal!
Friend functions
• Class operations are typically • friend in the class definition
implemented as member functions • A friend function is not a member
• Some operations are better implemented function
as ordinary (nonmember) functions • A friend function is an ordinary function
• • A friend function has extraordinary
Friend functions are not members of a
class, but can access private member access to data members of the class
variables of the class • As a friend function, the more
• To declare a function as a friend of a class, efficient version of equal is legal
precede the function prototype in the class
definition with the keyword friend.
Friend Declaration
Syntax • EXAMPLE:
• The syntax for declaring friend function is The function equal is declared a friend in the
class class_name abbreviated class definition here
{ class DayOfYear
{
private: public:
Private_Member_Declarations friend bool equal(DayOfYear date1,DayOfYear date2);
public: // The rest of the public members
private:
friend Declaration_for_Friend_Function_1 // the private members
friend Declaration_for_Friend_Function_2 };

Member_Function_Declarations

};
Using A Friend Function Are Friends Needed?
• A friend function is declared as a • Friend functions can be written as
friend in the non-friend
class definition functions using the normal accessor

and mutator
A friend function is defined as a functions that should be part of the
nonmember class
function without using the "::"
operator • The code of a friend function is

simpler and it is
A friend function is called without more efficient
using the
'.' operator
Choosing Friends
• How do you know when a function should be
a friend or a member function?
• In general, use a member function if the task performed by the function involves only one
object
• In general, use a nonmember function if the task performed by the function involves more than
one object
• Choosing to make the nonmember function a friend is a decision of efficiency and personal taste
EXAMPLE
class rectangle {

   private:
void set_value(rectangle &rc, float h)
float height;
{
float width;

int xpos; rc.height = h;


int ypos; }
public:  
friend void set_value(rectangle&, float); // friend declaration
void main()
rectangle(float, float); // constructor
{
void draw(); // draw member function
rectangle rc(1.0, 3.0);
void posn(int, int); // position member function

void move(int, int); // move member function  


float get_height(); // access function set_value(rc, 10.0);
void set_height(float); // access function }
};
Class Parameters
• It can be much more efficient to use call-by-reference parameters when the
parameter is of a class type
• When using a call-by-reference parameter
• If the function does not change the value of the
parameter, mark the parameter so the compiler
knows it should not be changed
const Parameter Modifier
• To mark a call-by-reference parameter so it
cannot be changed:
• Use the modifier const before the parameter type
• The parameter becomes a constant parameter
• const used in the function declaration and definition

const int NUMBER= 10;


NUMBER++; //error

Slide 11- 19
Int fun1(int&, const int);

const Parameter Example Int fun1(int& a, const int b)


{}

• A function declaration with constant parameters


• Money add(const Money& amount1, const Money& amount2) const;

• A function definition with constant parameters


• Money add(const Money& amount1, const Money& amount2)
{

}

Slide 11- 20
const Considerations
• When a function has a constant parameter,
the compiler will make certain the parameter
cannot be changed by the function
• What if the parameter calls a member function?

Money add(const Money& amount1,


const Money& amount2)
{ …
amount1.input( cin );
}

• The call to input will change the value of amount1!

Slide 11- 21
const
And Accessor Functions
• Will the compiler accept an accessor function
call from the constant parameter?

Money add(const Money& amount1,


const Money& amount2)
{ …
amount1.output(cout);
}

• The compiler will not accept this code


• There is no guarantee that output will not change the
value of the parameter

Slide 11- 22
const Modifies Functions
• If a constant parameter makes a member function
call…
• The member function called must be marked so
the compiler knows it will not change the parameter
• const is used to mark functions that will not change
the value of an object
• const is used in the function declaration and the
function definition

Slide 11- 23
Function Declarations
With const
• To declare a function that will not change the
value of any member variables:
• Use const after the parameter list and
just before the semicolon

class Money
{
public:

void output (ostream& outs) const ;

Slide 11- 24
Function Definitions With const
• To define a function that will not change the
value of any member variables:
• Use const in the same location as the function
declaration

void Money::output(ostream& outs) const


{
// output statements
}

Slide 11- 25
const Problem Solved
• Now that output is declared and defined using the const modifier, the
compiler will accept
this code

• Money add(const Money& amount1,


const Money& amount2)
{ …
amount1.output(cout);
}

Slide 11- 26
Use const Consistently
• Once a parameter is modified by using const to
make it a constant parameter
• Any member functions that are called by the
parameter must also be modified using const to
tell the compiler they will not change the parameter

• It is a good idea to modify, with const, every


member function that does not change a member
variable

Slide 11- 27
CLASSES AND
DYNAMIC ARRAYS
Accessing Array Elements
• Class TemperatureList includes an array
• • The array, named list, contains
To access the array elements within
a structure temperatures
• Use the dot operator to identify the • Member variable size is the number of
array within the structure items stored
• Use the [ ]'s to identify the indexed class TemperatureList
variable desired {
• Example: my_best.time[i] private:
references the ith indexed variable of
double list [MAX_LIST_SIZE];
the variable time in the structure
my_best int size;
public:
TemperatureList( ); //Member functions

};
Class Student
{
private:
int marks; Array is allocated memory at compile
float Q[100]; time:
Public: 1. Array size is mentioned before the
Student (int, float); array is used
Student(): marks(m), Q();
setmarks();
getmarks();
setQaray(int a)
{int temp=a;
Q[temp];
};
Int main()
{
int size;
cin>> size;
Student s1;
S1.set(){};
For (int i=0;i<=2;i++)
{}
Dynamic Memory Allocation with Operators new and delete
• new and delete
• Used for dynamic memory allocation
• Superior to C’s malloc and free
• new
• Creates an object of the proper size, calls its constructor and returns a pointer of the
correct type
• delete
• Destroys object and frees space
• Examples of new
TypeName *typeNamePtr;
• Creates pointer to a TypeName object
typeNamePtr = new TypeName[];
• new creates TypeName object, returns pointer (which typeNamePtr is set equal
to)
Dynamic Memory Allocation with Operators new and delete
• Examples of delete Int arr[50];
delete typeNamePtr; Int *arr= new
• Calls destructor for TypeName object and frees memory int[65];// 50+65
Delete [] arrayPtr;
• Used to dynamically delete an array

• Initializing objects
double *thingPtr = new double( 3.14159 );
• Initializes object of type double to 3.14159
int *arrayPtr = new int[ 15];
• Creates a ten element int array and assigns it to arrayPtr
Classes and Dynamic Arrays
Program Example:
A String Variable Class
• A dynamic array can have a class as its
We will define the class StringVar
base type StringVar objects will be
• A class can have a member variable that string variables
is a StringVar objects use
dynamic arrays whose size is
dynamic array
determined when the
program is running
• In this section you will see a class using a
dynamic array as a member variable.
The StringVar The StringVar
Constructors Interface
• The default StringVar constructor creates an • In addition to constructors, the StringVar
object with a maximum string length of 100 interface includes:
• Member functions
• Another StringVar constructor takes an
• int length( );
argument
of type int which determines the maximum • void input_line(istream& ins);
string length of the object • friend ostream& operator << (ostream&
outs,const StringVar& the_string);
• A third StringVar constructor takes a C-string
argument and…
• sets maximum length to the length of the C-
string
• copies the C-string into the object's string value
The StringVar Implementation
• StringVar uses a dynamic array to store its string
• StringVar constructors call new to create the dynamic array for member variable value
• '\0' is used to terminate the string
• The size of the array is not determined until the
array is declared
• Constructor arguments determine the size
Array of objects
• Like array of other user-defined data types, an array of type class can also be
created.
• The array of type class contains the objects of the class as its individual elements.
Thus, an array of a class type is also known as an array of objects.
• An array of objects is declared in the same way as an array of any built-in data
type.

Syntax:
class_name array_name [size]
void books :: putdata () The output of the program is
#include<iostream>  
using namespace std; { Enter details of book 1
class books cout<<"Title:"<<title<< "\n"; Title: c++
{ cout<<"Price:"<<price<< "\n”; Price: 325
const int size=3 ; Enter details of book 2
char tit1e [30]; Title: DBMS
float price ; int main () Price:. 455
{ Enter details of book 3
public:
books book[size] ; Title: Java
void getdata (); for(int i=0;i<size;i++) Price: 255
void putdata (); { Book 1
}; cout<<"Enter details o£ book "<<(i+1)<<"\n"; Title: c++
Price: 325
void books :: getdata () book[i].getdata();
Book 2
{ } Title: DBMS
cout<<"Title:”; for(int i=0;i<size;i++) Price: 455
{ Book 3
Cin>>title;
cout<<"\nBook "<<(i+l)<<"\n"; Title: Java
cout<<"Price:”; book[i].putdata() ; Price: 255
cin>>price; }
  return 0;
} }
 
In this example, an array book of the type class books and
size three is declared. This implies that book is an array of
three objects of the class books. Note that every object in
the array book can access public members of the class in
the same way as any other object, that is, by using the dot
operator. For example, the statement book [i] . getdata ()
invokes the getdata () function for the ith element of array
book.
When an array of objects is declared, the memory is
allocated in the same way as to multidimensional arrays.
For example, for the array book, a separate copy of title
and price is created for each member book[0], book[l] and
book[2]. However, member functions are stored at a
different place in memory and shared among all the array
members. For instance, the memory space is allocated to
the the array of objects book of the class books,
                         
Class Name
{ Int fun4( const int a)
private: {
char b=‘a’; Name n;
const int a=10; }
public:
Name();
Name(int);
int fun1(const int);
// int fun 2(const & int);
// Name fun3 ( const& int, const int);
// void fun 4( int, int) const;
};

You might also like