Вы находитесь на странице: 1из 32

UNIT I

OBJECT ORIENTED PROGRAMMING FUNDAMENTALS

C++ Programming features - Data Abstraction - Encapsulation - class - object constructors static members constant members member functions pointers
references - Role of this pointer Storage classes function as arguments.

1.1 C++ PROGRAMMING FEATURES:


1. The C++ programming language is based on the C language.
2. Although C++ is a descendant of the C language, the two languages are not always
compatible.
3. In C++, you can develop new data types that contain functional descriptions (member
functions) as well as data representations. These new data types are called classes.
4. The work of developing such classes is known as data abstraction. You can work with
a combination of classes from established class libraries, develop your own classes, or
derive new classes from existing classes by adding data descriptions and functions.
5. New classes can contain (inherit) properties from one or more classes. The classes
describe the data types and functions available, but they can hide (encapsulate) the
implementation details from the client programs.
6. You can define a series of functions with different argument types that all use the
same function name. This is called function overloading. A function can have the
same name and argument types in base and derived classes.
7. Declaring a class member function in a base class allows you to override its
implementation in a derived class. If you use virtual functions, class-dependent behavior
may be determined at run time. This ability to select functions at run time, depending
on data types, is called polymorphism.
8. You can redefine the meaning of the basic language operators so that they can
perform operations on user-defined classes (new data types), in addition to operations
on system-defined data types, such as int, char, and float. Adding properties to operators
for new data types is called operator overloading.
9. The C++ language provides templates and several keywords not found in the C
language. Other features include try-catch-throw exception handling, stricter type
checking and more versatile access to data and functions compared to the C language.

1.2 DATA ABSTRACTION:

Data abstraction refers to, providing only essential information to the outside world
and hiding their background details, i.e., to represent the needed information in program
without presenting the details.

Data abstraction is a programming (and design) technique that relies on the separation
of interface and implementation.

Let's take one real life example of a TV, which you can turn on and off, change the
channel, adjust the volume, and add external components such as speakers, VCRs,
and DVD players, BUT you do not know its internal details, that is, you do not know
how it receives signals over the air or through a cable, how it translates them, and finally
displays them on the screen.

Thus, we can say a television clearly separates its internal implementation from its
external interface and you can play with its interfaces like the power button, channel
changer, and volume control without having zero knowledge of its internals.

Now, if we talk in terms of C++ Programming, C++ classes provides great level of
data abstraction. They provide sufficient public methods to the outside world to play
with the functionality of the object and to manipulate object data, i.e., state without
actually knowing how class has been implemented internally.

In C++, we use classes to define our own abstract data types (ADT). You can use the
cout object of class ostream to stream data to standard output like this:

#include <iostream.h>
int main( )
{
cout << "Hello C++" <<endl;
return 0;
}

Here, you don't need to understand how cout displays the text on the user's screen.
You need to only know the public interface and the underlying implementation of
cout is free to change.

Access Labels Enforce Abstraction:

In C++, we use access labels to define the abstract interface to the class. A class may
contain zero or more access labels:

Members defined with a public label are accessible to all parts of the program. The
data-abstraction view of a type is defined by its public members.

Members defined with a private label are not accessible to code that uses the class.
The private sections hide the implementation from code that uses the type.

There are no restrictions on how often an access label may appear. Each access label
specifies the access level of the succeeding member definitions. The specified access
level remains in effect until the next access label is encountered or the closing right
brace of the class body is seen.

Benefits of Data Abstraction:

Data abstraction provides two important advantages:

Class internals are protected from inadvertent user-level errors, which might corrupt
the state of the object.

The class implementation may evolve over time in response to changing requirements
or bug reports without requiring change in user-level code.

By defining data members only in the private section of the class, the class author is
free to make changes in the data. If the implementation changes, only the class code
needs to be examined to see what affect the change may have. If data are public, then
any function that directly accesses the data members of the old representation might
be broken.

Data Abstraction Example:

Any C++ program where you implement a class with public and private members is
an example of data abstraction. Consider the following example:

#include <iostream.h>
using namespace std;

class Adder
{
public:

// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside world
int total;
};
int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout << "Total " << a.getTotal() <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result: Total 60

Above class adds numbers together, and returns the sum. The public members
addNum and getTotal are the interfaces to the outside world and a user needs to
know them to use the class. The private member total is something that the user
doesn't need to know about, but is needed for the class to operate properly.

1.3 DATA ENCAPSULATION:

Data encapsulation is a mechanism of bundling the data, and the functions that use
them and data abstraction is a mechanism of exposing only the interfaces and hiding
the implementation details from the user.

C++ supports the properties of encapsulation and data hiding through the creation of
user-defined types, called classes. We already have studied that a class can contain
private, protected and public members. By default, all items defined in a class are
private.

For example:
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
private:
double length;

// Length of a box

double breadth;

// Breadth of a box

double height;

// Height of a box

};

The variables length, breadth, and height are private. This means that they can be
accessed only by other members of the Box class, and not by any other part of your
program. This is one way encapsulation is achieved.

To make parts of a class public (i.e., accessible to other parts of your program), you
must declare them after the public keyword. All variables or functions defined after
the public specifier are accessible by all other functions in your program.

Making one class a friend of another exposes the implementation details and reduces
encapsulation. The ideal is to keep as many of the details of each class hidden from all
other classes as possible.

Data Encapsulation Example:


Any C++ program where you implement a class with public and private members is an
example of data encapsulation and data abstraction. Consider the following example:

#include <iostream.h>
#include<conio.h>
class Adder
{
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside world
int total;
};
int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);

cout << "Total " ;


cout<< a.getTotal();
cout <<endl;
return 0;
}

When the above code is compiled and executed, it produces the following result: Total 60
Above class adds numbers together, and returns the sum. The public member s
addNum and getTotal are the interfaces to the outside world and a user needs to know them
to use the class. The private member total is something that is hidden from the outside world,
but is needed for the class to operate properly.

Designing Strategy:
Most of us have learned through bitter experience to make class members private by
default unless we really need to expose them. That's just good encapsulation.
This wisdom is applied most frequently to data members, but it applies equally to all
members, including virtual functions.

1.4 CLASS:
In oop, class is a user defined data type that can hold data and their associated functions
into single unit.
The class members are divided into two types:
1. Data Member
2. Function Member
In class there are certain privilege for accessing both data and function members.
They are said to be access specifiers.
It is divided into three categories. They are,
1.Public
2.private
3.Protected
By default the data members are private. So the private members of a class are not
accessible from outside the class. If the data members are specified as public then the
members of a class can be accessible from inside and outside of the class.

Syntax of a class
class class_name
{
Access Specifier:
Data Members
Access Specifier:
Function Members
};

Example:
Consider an example of class
class student
{
public:
int rollno,age;

Data Members

char *name;
void getdetail()
{
Cin>>rollno>>age;
Cin>>name;
}

Function Members

void printdetail()
{
Cout<<rollno<<age;
Cout<<name;
}
};
In this example a class named student with data members such rollno, age and name
and with function members getdetail() and printdetail() is defined within the class.The access
specifiers of this class is public.

Function Definition outside the Class


The function members which are declared inside the class can be defined outside of
the class using Scope Resolution Operator ::

Syntax for Defining the Function outside the Class:


Return Type class_name::function_name()
{
Function Body
}

Return type specifies the type of a function. Class name specifies the name of a class
in which the function belongs. The operator:: denotes scope resolution operator. Function name
specifies the name of a function.

Example:
class student
{
public:
int rollno,age;
char *name;
void getdetail();
void printdetail();
};
void student::getdetail()
{
Cin>>rollno>>age;
Cin>>name;
}
void student::printdetail()
{
Cout<<rollno<<age;
Cout<<name;
}

1.5 OBJECTS:
Objects are the variables of user defined data type called class. Once a Class has been
created we can declare any number of variables belongs to that class. In the above example
class student we can declare any number of variables of class student in the main function.
Using objects we can access any public members of a class using Dot Operator.

For accessing Data Members and assigning value:


object_name.data_member=value;

For accessing Function Members:


Object_name.function_name();

Syntax:
Class_Name object1, object2, object3.object n;
void main ()
{

class Name

student s1, s2,s3;


s1.rollno=28;

s1,s2,s3 are objects(variables) of class Student


Object s1 assigns the value for the data member rollno=28

s1.getdetail (); Object s1 access (call) the function member getdetail () of student class
s1.printdetail ();

Object s1 access (call) the function member


printdetail () of student class

Memory Requirement for Objects and Class:


Once the object is created memory is allocated for the data members of a class and not
for its function Members .So each object holds the total memory size of the data members.
For example in the class student the object s1 holds the memory size of 5 bytes. Char I byte,
int 2 bytes.
Once the class is created only single copy of function member is maintained which
is common for all the objects.

Class student
Function Members:
Void getdetail()
Void printdetail()

Object s1:

Object s2:

Object s3:

Data Member Name

Data Member Name

Data Member Name

Data Member Rollno

Data Member Rollno

Data Member Rollno

Data Member age

Data Member age

Data Member age

1.6 CONSTRUCTOR:
The main use of constructors is to initialize objects. The function of initialization is
automatically carried out by the use of a special member function called a constructor.
General Syntax of Constructor
A constructor is a special member function that takes the same name as the class
name. The default constructor for a class X has the form
X::X()
In the above example, the arguments are optional. The constructor is automatically
named when an object is created. A constructor is named whenever an object is defined or
dynamically allocated using the new operator.
There are several forms in which a constructor can take its shape namely:

Default Constructor:
This constructor has no arguments in it. The default Constructor is also called as the
no argument constructor.
For example:
class Exforsys
{

private:
int a,b;
public:
Exforsys();
...
};

Exforsys :: Exforsys()
{
a=0;
b=0;
}
Parameterized Constructor:
A default constructor does not have any parameter, but if you need, a constructor
can have parameters. This helps you to assign initial value to an object at the time of its creation
as shown in the following example:
#include <iostream>
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor

private:
double length;
};

// Member functions definitions including constructor


Line::Line( double len)
{
cout << "Object is being created, length = " << len << endl;
length = len;

}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// Main function for the program
int main( )
{
Line line(10.0);
// get initially set length.
cout << "Length of line : " << line.getLength() <<endl;
// set line length again
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;

return 0;
}
When the above code is compiled and executed, it produces the following result:
Object is being created, length = 10
Length of line : 10
Length of line : 6

Copy constructor:
This constructor takes one argument, also called one argument constructor. The main
use of copy constructor is to initialize the objects while in creation, also used to copy an object.
The copy constructor allows the programmer to create a new object from an existing one by
initialization.
For example to invoke a copy constructor the programmer writes:
Exforsys e3(e2);
or

Exforsys e3=e2;
Both the above formats can be sued to invoke a copy constructor.

For Example:
#include <iostream>
using namespace std;
class Exforsys
{
private:
int a;
public:
Exforsys()
{
}
Exforsys(int w)
{
a=w;
}
Exforsys(Exforsys& e)
{
a=e.a;
cout << " Example of Copy Constructor";
}
void result()
{
cout<< a;
}
};
void main()
{
Exforsys e1(50);
Exforsys e3(e1);
cout<< "ne3=";e3.result();
}

Destructors
Destructors are also special member functions used in C++ programming language.
Destructors have the opposite function of a constructor. The main use of destructors is to release
dynamic allocated memory.
Destructors are used to free memory, release resources and to perform other clean up.
Destructors are automatically named when an object is destroyed. Like constructors,
destructors also take the same name as that of the class name.

General Syntax of Destructors


~ classname();
The above is the general syntax of a destructor. In the above, the symbol tilda ~
represents a destructor which precedes the name of the class.
Some important points about destructors:

Destructors take the same name as the class name.

Like the constructor, the destructor must also be defined in the public. The destructor
must be a public member.

The Destructor does not take any argument which means that destructors cannot be
overloaded.

No return type is specified for destructors.

For example:
class Exforsys
{
private:
...
public:
Exforsys()
{
}
~ Exforsys()
{
}
}

1.7 STATIC MEMBERS:


The Static Data Member of a class is like a global variable. Once it is defined the static
member will be initialized to zero. When the static member is declared inside the class it
should be defined outside of the class. Static Data Member of a class will be common to all the
objects which are declared in the class.
Syntax:
class stat
{
static int count; //static Data Member Declaration
}
int stat::count; //static Data member Defintion

Example Program:
#include<iostream.h>
#include<conio.h>
class count
{
public:
static int countt;
void dispcount()
{ countt++;
cout<<"Object\t"<<countt<<"\n";
}
};
int count::countt;
void main()
{
count c1,c2,c3,c4,c5;
clrscr();
c1.dispcount();
c2.dispcount();
c3.dispcount();

c4.dispcount();
c5.dispcount();
getch();
}

In this example class count has a static data member countt.This program is used for
counting the number of objects which is declared in the class.So when an object c1 access the
function dispcount() the static variable has the value 1.when s5 access the function the value
will be incremented to 5.

Output:
Object 1
Object 2
Object 3
Object 4
Object 5
NOTE:
Once the static data member is defined it is automatically initialized to zero.

1.8 CONSTANT MEMBERS:


Constant Objects and Constant Functions

Once the object is declared as constant it cannot be modified by any function.

Initially the value for the data members is set by constructor during the object
creation.

Constant objects can access only the constant member function .The constant function
is read only function it cannot alter the value of object data members

Syntax- Constant Function & Constant objects


class class_name{
class_name(parameters)
{

initialize the datamember with parameters;


}
return_type function_name() const

//Constant member function

{
//read only function
}
};
void main()
{
const class_name object( parameter);

//constant objects

object.function(); //constant objects access Constant member function


}

Ex:
void printdetails() const
{
cout<<Roll No is:<<rollno;
cout<<Name is:<<name;
cout<<Address is:<<address;
rollno=10; / / the following line is erroneous
}

Mutable Data Members


In some cases if the static function need to modify the data member of an object, then the
data member should be declared as mutable, so that static function can modify it.
mutable int rollno;
void printdetails() const
{
rollno=10;
}

//it is allowed

Example program for constant function and constant objects


#include<iostream.h>
#include<conio.h>
class time
{
public:
int hour,minute,second;
time(int temphr,int tempmin,int tempsec)
{ hour=temphr;
minute=tempmin;
second=tempsec;
}
void disp() const

//constant member function

{
cout<<"Time is:"<<hour<<"Hour:\t"<<minute<<"Minutes:\t"<<second<<"Seconds:\n";
}
~time()
{
}
void get() const
{
cin>>hour>>minute>>second;
}
};
void main()
{
clrscr();
const time t1(8,55,50);

//Constant objects

t1.disp();
t1.get();
t1.disp();
getch();
}

//cannot modify the datamembers of t1

Output
Time is:8Hour: 55Minutes:

50Seconds:

5
50
40
Time is:8Hour: 55Minutes:

50Seconds:

In this example, the object of this time class is set with the default value of 8 hour 55
minutes and 50 seconds and it is initialized with constructor. Since this object t1 is a n
constant object it cannot be modified and it can access only the constant function in a class.

1.9 MEMBER FUNCTIONS:


1.9.1 Static Function
Static member functions have a class scope and they do not have access to the 'this'
pointer of the class. When a member is declared as static, a static member of class, it has only
one data for the entire class even though there are many objects created for the class. The
main usage of static function is when the programmer wants to have a function which is
accessible even when the class is not instantiated.

Syntax
class stat
{
static return_type function_name()
{
Statement;
}
};
Calling Static Function in the main Function
void main()
{
class_name::static function name();
}

Example:
#include<iostream.h>
#include<conio.h>
class count
{
public:
static int countt;
count()
{ countt++;
cout<<"Object\t"<<countt<<"\n";
}
static void statfun()
{
cout<<"Object\t"<<countt<<"\n";
}
};
int count::countt;
void main()
{
count c1,c2,c3,c4,c5;
clrscr();
count::statfun();//calling the constructor using classname
getch();//scope resolution operator and the static funtion name
}

Output:
Object 5

The programmer must note the following while using static member functions:

A static member function can only access static member data, static member functions
and data and functions outside the class. The programmer must take note not to use
static member function in the same manner as non-static member function, as non- static
member function can access all of the above including the static data member.

A non-static member function can be declared as virtual but care must be taken not to
declare a static member function as virtual.

The programmer must first understand the concept of static data while learning the
context of static functions. It is possible to declare a data member of a class as static
irrespective of it being a public or a private type in class definition. If a data is
declared as static, then the static data is created and initialized only once. Non-static
data members are created again and again. For each separate object of the class, the
static data is created and initialized only once. As in the concept of static data, all objects
of the class in static functions share the variables. This applies to all objects of the class.

A non-static member function can be called only after instantiating the class as an
object. This is not the case with static member functions. A static member function
can be called, even when a class is not instantiated.

A static member function cannot have access to the 'this' pointer of the class.

1.9.2 Inline member Function


We may either define a member function inside its class definition, or you may define
it outside if you have already declared (but not defined) the member function in the class
definition.
A member function that is defined inside its class member list is called an inline member
function. Member functions containing a few lines of code are usually declared inline. In
the above example, add() is an inline member function. If you define a member function outside
of its class definition, it must appear in a namespace scope enclosing the class definition.
You must also qualify the member function name using the scope resolution (::) operator.
An equivalent way to declare an inline member function is to either declare it in the
class with the inline keyword (or define the function outside of its class) or to define it
outside of the class declaration using the inline keyword.

1.10 POINTERS:
Every storage location of memory has an associated address. The address is a number
that grows sequentially. For every program placed in memory, each variable or function in
the program has an associated address.

The address of operator:


The address of operator or Reference operator is denoted by the notation &. When the
user wants to get the address of a variable, then the reference operator & can be used. The
operator & is used to find the address associated with a variable.
The syntax of the reference operator is as follows:
&variablename - This means that the address of the variable name is achieved.

For Example
#include <iostream>
using namespace std;
void main()
{
int exf=200;
int test=300;
cout << endl << &exf << endl << &test;
}

The &exf has the address associated with the integer variable exf and the &test has
the address associated with the integer variable test which are displayed using the cout
statement.
Using the understanding of address of operators, the discussion turns to the concept of
pointers.
exforsys = 100;
test = exforsys;
x = &exforsys;
Using the above information, the assignment takes place as below:

exforsys is an integer variable having the value of 100 stored in memory address location
3501.
When the variable exforsys is assigned to the variable test in the second statement:
test = exforsys;
The value of the variable exforsys 100 is copied to the variable test.
In the third statement, the address of the variable exforsys is denoted by reference operator
&exforsys is assigned to the variable x as:
x = &exforsys;

The address of the variable 3501 and not the contents of the variable exforsys is
copied into the variable x. The pointers concept fits in this statement. Pointers are the
variables that store the reference to another variable. Pointers are variables that store the address
of the variable that it is pointed by. Variable x is referred to as the pointer in the above
example.
The programmer must note that the address operator placed before a variable is not
the same as operator & placed after the variable. For example, &x is not same as x&.
Variable &x refers to address operator whereas x& refer to reference operator&. Pointer is a
variable that holds the address, also called pointer variable.

Defining Pointer Variables or Pointer:


To define pointer variable is as follows:
datatype_of_ variable_pointedto* pointer_varaible;
For example:
char* ch;
This defines that ch is a pointer variable which points to char data type.
int* i;
This defines that i is a pointer variable which points to int data type.
float* f;
This defines that f is a pointer variable which points to float data type.

1.11 REFERENCES:
A reference variable is an alias, that is, another name for an already existing variable.
Once a reference is initialized with a variable, either the variable name or the reference name
may be used to refer to the variable.

C++ References vs Pointers:


1. References are often confused with pointers but three major differences between
references and pointers are:
2. You cannot have NULL references. You must always be able to assume that a
reference is connected to a legitimate piece of storage.
3. Once a reference is initialized to an object, it cannot be changed to refer to another
object. Pointers can be pointed to another object at any time.
4. A reference must be initialized when it is created. Pointers can be initialized at any
time.

Creating References in C++:


Think of a variable name as a label attached to the variable's location in memory. You
can then think of a reference as a second label attached to that memory location. Therefore,
you can access the contents of the variable through either the original variable name or the
reference.
For example, suppose we have the following example:
int

i = 17;

We can declare reference variables for i as follows.


int& r = i;

Read the & in these declarations as reference. Thus, read the first declaration as "r is
an integer reference initialized to i" and read the second declaration as "s is a double
reference initialized to d.". Following example makes use of references on int and double:

#include <iostream.h>
int main ()
{
// declare simple variables
int

i;

double d;
// declare reference variables
int& r = i;
double& s = d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
}
When the above code is compiled together and executed, it produces the following result:
Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7

References are usually used for function argument lists and function return values. So
following are two important subjects related to C++ references which should be clear to a
C++ programmer: we can implement call by reference concept using pointers.

Here is another example of call by reference which makes use of C++ reference:
#include <iostream.h>
// function declaration
void swap(int& x, int& y);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;

/* calling a function to swap the values.*/


swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;

return 0;
}

// function definition to swap the values.


void swap(int& x, int& y)
{
int temp;
temp = x; /* save the value at address x */
x = y;

/* put y into x */

y = temp; /* put x into y */

return;
}

When the above code is compiled and executed, it produces the following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

1.12 ROLE OF this POINTER:


Every object in C++ has access to its own address through an important pointer called
this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside
a member function, this may be used to refer to the invoking object.
Friend functions do not have a this pointer, because friends are not members of a
class. Only member functions have a this pointer.

Example:
#include <iostream.h>

class Box
{
public:
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume()
{
return length * breadth * height;
}
int compare(Box box)
{
return this->Volume() > box.Volume();
}
private:
double length;

// Length of a box

double breadth;

// Breadth of a box

double height;

// Height of a box

};
int main(void)
{
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
if(Box1.compare(Box2))
{
cout << "Box2 is smaller than Box1" <<endl;
}
else
{

cout << "Box2 is equal to or larger than Box1" <<endl;


}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Constructor called.
Constructor called.
Box2 is equal to or larger than Box1

1.13 STORAGE CLASS:


Storage class defined for a variable determines the accessibility and longevity of the
variable. The accessibility of the variable relates to the portion of the program that has access
to the variable. The longevity of the variable refers to the length of time the variable exists
within the program.

Types of Storage Class Variables in C++:


1. Automatic
2. External
3. Static

Automatic:
Variables defined within the function body are called automatic variables. Auto is the
keyword used to declare automatic variables. By default and without the use of a keyword,
the variables defined inside a function are automatic variables.

For instance:
void exforsys( )
{
auto int x;
auto float y;
...
}
is the same as

void exforsys( )
{
int x;
float y;

//Automatic Variables

...
}
In the above function, the variable x and y are created only when the function
exforsys( ) is called. An automatic variable is created only when the function is called. When
the function exforsys( ) is called, the variables x and y are allocated memory automatically.

External:
External variables are also called global variables. External variables are defined outside
any function, memory is set aside once it has been declared and remains until the end of the
program. These variables are accessible by any function. This is mainly utilized when a
programmer wants to make use of a variable and access the variable among different function
calls.
Static:
The static automatic variables, as with local variables, are accessible only within the
function in which it is defined. Static automatic variables exist until the program ends in the
same manner as external variables. In order to maintain value between function calls, the
static variable takes its presence.

For example:
#include <iostream.h>
using namespace std;
int exforsys(int);
int exforsys2(int);
void main( )
{
int in;
int out;
while(1)
{

cout << "nEnter input value:";


cin>>in;
if (in == 0)
break;
out=exforsys(in);
cout << "nResult : " << out;
out=exforsys2(in);
cout << "nResult2: " << out;
}
cout << "n End of Program " ;
}
int exforsys(int x)
{
static int a=0;
a++;
return(a);
}
int exforsys2(int x)
{
int b=0;
b++;
return(b);
}
In the above program, the static variables a is initialized only once in the beginning of
the program. Then the value of the variable is maintained between function calls.

1.14 FUNCTION AS ARGUMENTS:


A function pointer (or subroutine pointer or procedure pointer) is a type of pointer
supported by third-generation programming languages Instead of referring to data values, a
function pointer points to executable code within memory. When dereferenced, a function
pointer can be used to invoke the function it points to and pass it arguments just like a normal
function call. Such an invocation is also known as an "indirect" call, because the function is
being invoked indirectly through a variable instead of directly through a fixed name or

address. Function pointers can be used to simplify code by providing a simple way to select a
function to execute based on run-time values.

#include <iostream.h>
int add(int first, int second)
{
return first + second;
}
int subtract(int first, int second)
{
return first - second;
}
int operation(int first, int second, int (*functocall)(int, int))
{
return (*functocall)(first, second);
}

void main()
{
int a, b;
int (*plus)(int, int) = add;
int (*minus)(int, int) = subtract;
a = operation(7, 5, plus);
b = operation(20, a, minus);
cout << "a = " << a << " and b = " << b << endl;
}

Вам также может понравиться