C/C++ Projects :: Blog


June 02, 2008

Friend Function : As we know, private class members can not be accessed from outside the class. By using private class members, we can reduce the possibility of a program misusing a member's value, since the program must access the class members using an interface function. Sometime, we would like two classes to share a particular function. In such situation, C++ allows the common function to be made friendly with both classes, thereby allowing the function to have access to the private data of these classes. Such a function need not be a member of any of these classes.

To make an outside function 'friendly' to a class, we have to simply declare this function as a friend of the class. The function declaration should be preceded by the keyword friend. While the function definition does not use either the keyword friend or scope resolution operator (::). The function that are declared with the keyword friend are known as friend functions. A function can be declared friend in any number of classes.

A friend function possesses certain characteristics :

  • It can be declared either in the public or private part of a class without affecting its meaning.
  • Usually, it has objects as arguments.
  • Its scope is not limited to the class in which it has been declared as friend. It can not be called using the object of that class. It can be invoked like a normal function without the help of any object.
  • Unlike the normal member functions, it can not access the member names directly. It has to use an object name and dot membership operator with each member name.

Example,

#include <iostream.h>

class sample

{

   int a;

   int b;

   public :

      void setvalue( int al, int bl)

     {

        a = a1;

        b = b1;

     }

      friend float mean (sample s);  //friend declared

};

float mean(sample s)     //function definition

{

   return float(s.a + s.b) / 2;   //accessing private members


void main ()

{

   sample x;  //create an object x

   x.setvalue(25,40);

   cout  << "Mean Value : " << mean(x) << endl;

}

 

All the member functions of one class can be declared as friend functions of another class. In such a case,the class is called a friend class. This can be specified as follows:

class X;

class Z

{

   ......

   friend class X;  //all member functions of X are friends to Z

};

 

Constructors : These are special member functions that are used to initialize the objects, as soon as they are created. Thst is, you can create an object and simultaneously pass the value to the parameters of the object. The constructors should have exactly the same name as that of class of which they are members. The constructor function does not have a return value. They should be declared in public section. To understand how constructors are used, let's try the example of displaying the area of square by using constructors :

Example, 

class Square

{

   public :

   int dim;

   Square(int d);   //Declaring a Constructor Function

   {

      dim = d;

   }

   void DisplayArea()

   {

      cout << "The area of the square : "<<dim*dim;

   }

   void main ()

   {

      Square S1(10), S2(15);    //the constructor function will be called automatically

      cout << "The dimension of the square is : " << s1.dim;

      S1.DisplayArea();

      cout << "The dimension of the square is :" << s1.dim;

      S2.DisplayArea();

   }

 

The output of the program will be :

The dimension of the square is 10

The area of the square : 100

The dimension of the square is 15

The area of the square : 225 

 

Copy Constructor : It is used to declare an object and the values of these objects are initialized from other object. Note that a copy constructor takes a reference to an object of the same class. We can not pass the argument by value to a copy constructor.

Example,

#include <iostream.h> 

class Square

{

   int dim;

   public :

   Square(); 

   {  }

   Square (int I)

   {

       dim = I;

    }

   Square (Square & j)    //passing the argument through reference not by value

   {  dim = x.dim; } 

   void Display()

   {

        cout << dim;
        cout << "\n The area is : "<<dim*dim;

   }

}; 

main ()

{

      Square   Square1(10);

      Square   Square1(Square2);  //declaring a copy constructor

      Square Square3 = Square1;  //declaring a copy constructor

      cout << "\n length of square1 " ;

      Square1.Display();

      cout << "\n length of square2 " ;

      Square2.Display();

      cout << "\n length of square3 " ;

      Square3.Display();

 

}

 

The output is :

Length of square1 : 10

The area is : 100

length of square2 : 10

The area is : 100

Length of Square3 : 10

The area is : 100

 

Dynamic Constructors : They are used to allocate memory to objects at the time of their creation. Normally we can allocate fixed amount of memoryby using array but in many situations, we are not sure how much memory we need until runtime.  For example, space required to store the length of string entered by user.

In such case, we use 'new' operator. This operator obtains memory space from operating system and returns a pointer to its starting point. We can use 'new' operators in constructors to dynamically assign storage space when objects are created. 

 

Keywords: class, constructor, copy constructor, dynamic, friend function

Posted by C/C++ Projects - Rahul | 0 comment(s)


May 25, 2008

Function Calls

The program executes the function statements by calling the function.We can pass the information to the called function in two ways :

  • Call by Value : The following program demonstrates how the information is passed to the called function by passing the value of parameters. This program uses the function display_values to display the value of variables before and after the function call.

          ex.

          #include <iostream.h>

          void display_values( int a, int b)

          {

             a = 100;

             b = 200;

             cout << "The values within the function are : "<< a << "and" << b << endl << endl;

          }

          void main()

          {

              int x = 1001;

              int y = 2001;

              cout << " Before Function Call " << endl;

              cout << "The value of x and y is " << x << "and" << y << endl << endl;

              display_values(x,y);

              cout << " After function call " << endl;

              cout << " The value of x and y is "<< x << "and" << y << endl;
 

           }

 


The output is :

Before Function call

The value of x and y is 1001 and 2001

The values within the function are: 100 and 200

After function call

The value of x and y is 1001 and 2001

 

As you can see, the parameter values have been changed to 100 and 200 within the display-values functions. However, when the function ends, the values of the variables x and y within main() have not changed. Because when program pass a parameter to a function, C++ makes a copy of the parameter's valus and places the copy into a temporary memory location called stack. The function then uses the copy of the value. When the function ends, C++ discards the stack contents and any changes the function has made to the copy.

 

  • Call by Reference : In Call-By-Value, the called function does not have access to the actual variables in the calling program and only works on the copies of the values. This mechanism is fine if the function does not need to alter the values of the original variables in the calling function. Sometimes, we need to change the value of variables in the calling function. For example, in the bubble sort program, we compare two adjacent elements in the list and interchange their values if the first element is greater than the second. If a function is used for bubble sort, then it should be able to alter the values of variables in the calling program, which is not possible if the call-by-value method is used.

          Ex :

          #include<iostream.h>

          void display_values( int *a, int *b )  //creating pointers to type int

         {

              *a = 100;

              *b = 200;

              cout << "The values within the function are : "<< *a << "and" <<*b << endl << endl;

          }

          main (void)

          {

              int x = 1001;

              int y = 2001;

              cout << "Before function call " << endl;

              cout << " The value of x and y is " << x << and << y << endl << endl;

              display_values ( &x, &y );

              cout << " After function call " << endl;

              cout << " The value of x and y is " << x << "and" << y << endl;

              }

 

The output is :
 

Before function call

The value of x and y is 1001 and 2001

The values within the function are: 100 and 200

After function call

The value of x and y is 100 and 200

 

This is all about calling the functions in different ways. In next post, we will discuss about the various types of functions and their usage.

Keywords: call by reference, call by value, Function

Posted by C/C++ Projects - Rahul | 0 comment(s)


May 23, 2008

Object oriented programming is defined as a method of implementation in which programs are organized as cooperative collection of objects, each of which is an instance of some class.  Object based programming languages support the following features :

  • Data Abstraction
  • Data Encapsulation
  • Inheritance
  • Polymorphism

Now we will explain each one of them with examples :

Data Abstraction : "Abstraction refers to the act of representing the essential features without including the background details or explanations." It is the enforcement of a clear separation between the abstract properties of a data type and the concrete details of its implementation. The abstract properties are those that are visible to client code that makes use of the data type--the interface to the data type--while the concrete implementation is kept entirely private, and indeed can change, for example to incorporate efficiency improvements over time. The idea is that such changes are not supposed to have any impact on client code, since they involve no difference in the abstract behaviour.

For example, one could define an abstract data type called lookup table, where keys are uniquely associated with values, and values may be retrieved by specifying their corresponding keys. Such a lookup table may be implemented in various ways: as a hash table, a binary search tree, or even a simple linear list. As far as client code is concerned, the abstract properties of the type are the same in each case.

Data Encapsulation : "Data encapsulation, sometimes referred to as data hiding, is the mechanism whereby the implementation details of a class are kept hidden from the user." The user can only perform a restricted set of operations on the hidden members of the class by executing special functions commonly called methods. The actions performed by the methods are determined by the designer of the class, who must be careful not to make the methods either overly flexible or too restrictive. This idea of hiding the details away from the user and providing a restricted, clearly defined interface is the underlying theme behind the concept of an abstract data type.

For example, to create a stack class which can contain integers, the designer may choose to implement it with an array, which is hidden from the user of the class. The designer then writes the push() and pop() methods which puts integers into the array and removes them from the array respectively. These methods are made accessible to the user. Should an attempt be made by the user to access the array directly, a compile time error will result. Now, should the designer decide to change the stack's implementation to a linked list, the array can simply be replaced with a linked list and the push() and pop() methods rewritten so that they manipulate the linked list instead of the array. The code which the user has written to manipulate the stack is still valid because it was not given direct access to the array to begin with.

The concept of data encapsulation is supported in C++ through the use of the public, protected and private keywords which are placed in the declaration of the class. Anything in the class placed after the public keyword is accessible to all the users of the class; elements placed after the protected keyword are accessible only to the methods of the class or classes derived from that class; elements placed after the private keyword are accessible only to the methods of the class.

Inheritance : "It refers to a way to form new classes (instances of which are called objects) using classes that have already been defined." The new classes, known as derived classes, take over (or inherit) attributes and behavior of the pre-existing classes, which are referred to as base classes (or ancestor classes). It is intended to help reuse existing code with little or no modification.

For example, manager is a part of class employee. Here class manager acquires the characteristics of class employee. There are many types of inheritance, some of which are listed below.

  • Single Inheritance : When a class is derived from only one base class, it is called single inheritance.
  • Multiple Inheritance : Inheritance in which a derived class has several base classes.
  • Multilevel Inheritance : The method of deriving a class from another derived class is called multilevel inheritance.
  • Hierarchical Inheritance : When the traits of one class are inherited by more than one class.
  • Hybrid Inheritance : A method of inheritence where a class is derived from several derived classes.


Polymorphism : "Polymorphism is the process of using an operator or function in different ways for different set of inputs given." More precisely, polymorphism (object-oriented programming theory) is the ability of objects belonging to different types to respond to method calls of the same name, each one according to an appropriate type-specific behavior. The programmer (and the program) does not have to know the exact type of the object in advance, so this behavior can be implemented at run time (this is called late binding or dynamic binding).

It means that if class B inherits from class A, it doesn’t have to inherit everything about class A; it can do some of the things that class A does differently.means that if class B inherits from class A, it doesn’t have to inherit everything about class A; it can do some of the things that class A does differently.

 

Keywords: class, data abstraction, data encapsulation, inheritance, object oriented, polymorphism, programming

Posted by C/C++ Projects - Rahul | 0 comment(s)