Friday, 21 June 2013

the 'this' pointer

“this” pointer:
In addition to the explicit parameters in their argument lists, every class member function (method) receives an additional hidden parameter, the "this" pointer. The "this" pointer addresses the object on which the method was called. Thus, this pointer is used as a pointer to the class object instance by the member function.
                  Each object maintains its own set of data members, but all objects of a class share a single set of methods. This is, a single copy of each method exists within the machine code that is the output of compilation and linking. A natural question is then if only a single copy of each method exists, and its used by multiple objects, how are the proper data members accessed and updated. The compiler uses the "this" pointer to internally reference the data members of a particular object. Suppose, we have an Employee class that contains a salary member and a setSalary method to update it. Now, suppose that two Employees are instantiated.
class Employee
 {
   public:
     void setSalary(double sal)
     { salary = sal; }
    
void display()
            { cout<<"\nThe salary:"<<salary;  }
   private:
      double salary;
 };

int main()
{   Employee programmer;
    Employee managar;
    managar.setSalary(60000.0);
    programmer.setSalary(40000.0);
    managar.display();
    programmer.display();
    }
                      If only one setSalary method exists within the binary that is running, how is the correct Employee's salary updated? The compiler uses the "this" pointer to correctly identify the object and its members. During compilation, the compiler inserts code for the "this" pointer into the function. The setSalary method that actually runs is similar to the following pseudo-code.
void setSalary(Employee *this, float sal)
{
    this->salary = sal;
}
The correct object is identified via the "this" pointer. 

Example: This example show the use of this for displaying starting address of object

class this_example
  {
   private:
       int a;
       float data;
   public:
      void address()               // display address of the object which calls the function
       {  cout<<"\nThe address of object is "<<this;   }
  };
  void main()
    {
    this_example obj1, obj2;
    obj1.address();
    obj2.address();
    }


Output:
The address of object is 0x8fd3fff0
The address of object is 0x8fd3ffea

Example: This example shows the use this pointer
#include<iostream.h>
#include<conio.h>
 class this_pointer_example
      {
        int data1;
      public:
         int getdata()   //Function using this pointer for C++ Tutorial
              {   return this->data1;   }
         void setdata(int newval)            //Function without using this pointer
              {  this->data1 = newval;    }  //same as data1=newval;
        };

void main()
  {
   int result;
   this_pointer_example obj;
   obj.setdata(10);
   result=obj.getdata();
  cout<<"\nThe result is: "<<result;;  }

Output:
 The result is 10

   Characteristics of this pointer:
  • this pointer stores the address of the class instance, to enable pointer access of the members to the member functions of the class.
  • this pointers are not accessible for static member functions.
  • this pointers are not modifiable.  

concepts of oop

Object   Oriented   Programming
A type of programming in which programmers define not only the data type of a data structure, but also the types of operations (functions) that can be applied to the data structure.
In this way, the data structure becomes an object that includes both data and functions.
Characteristics of Object Oriented Programming
Data encapsulation - Encapsulation is the process of combining data and functions into a single unit called class.
Using the method of encapsulation, the programmer cannot directly access the data. Data is only accessible through the functions existing inside the class.
Data hiding - Data hiding is the implementation details of a class that are hidden from the user.A class groups its members into three sections:
Private, protected and public
In which private and protected are hidden from the outside world
For example –
class Temp
{
        private:
        int m;      // m is only accessible within the class 
        protected:
        int n  // n is only accessible within the class and 
                // to the subclass of Temp
                  public:
        int p;   // p is  accessible inside and outside the class 
         Temp() // constructor
          {        }
};
Polymorphism – it is a property by which a message can be sent to the objects of different classes and each object will respond in different way.
                               Or
It is the ability for a message or data to be processed in more than one form. An operation may exhibit different
behaviors in different instances. The behavior depends on the data types used in the operation. Polymorphism is extensively used in implementing function overloading.
For example –
class Temp
{
        public:
        Temp()
            {       }
        int area(int a)
         {
          return a*a;
         }
       int area( int a,int b);   //Overloaded function
         {
          return a*b;
         }  
};
Inheritance – It has the property of a class to inherit properties from other class .
                                   Or
Inheritance is the process by which objects can acquire the properties of objects of other class.
In OOP, inheritance provides reusability, like, adding additional features to an existing class without modifying it.
This is achieved by deriving new class from the existing one. The new class will have combined features of both the classes.
For example-
class A
{
         Public :
         int a ,b;
         void show ()
          {
          cout<<a<<b;
          }
};
class B: private A //Use of Inheritance
{
       int c;
       void dispdata ()
        {
         cout<<c;
        }
};

classes and objects


Class -A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions.
Definition:
A class is a group of objects which show a common property.
OR
A class is a collection of objects of similar type.
Once a class is defined, any number of objects can be created which belong to that class.
For example – Define a class to print the values of two numbers.
Class Helloworld
{
    int one;
    int two;
    public:
    void setdata()
      {
        cout<<”enter two numbers”;
        cin>>one>>two;
      }
     void putdata()
      {
      cout<<one<<endl<<two;
      }
};
int main()
    {
     Hellowrold obj;
     Obj.setdata();
     Obj.putdata();
     return 0;
    }
Classes are generally declared using the keyword class, with the following format:
class class_name
{
access_specifier_1:
   member1;
access_specifier_2:
   member2;
...
};
Object -An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable.
                               Or
It may be defined as identifiable identity with some characteristics and behavior.
Syntax of creating Object:
Class_name Object_Name
If we have class named AB then the Object of this class can be created using above syntax as
AB Obj;
Abstract class
An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function.
You declare a pure virtual function by using a pure Specifier
(= 0) in the declaration of a virtual member function in the class declaration.
The following is an example of an abstract class:
class AB {
            public:
            virtual void f() = 0; //Pure virtual Function
             };
Concrete class – it is a derived class that implement all the missing functionality of a abstract class is called a concrete class
The following is an example of an concrete class: 
 class CD : public AB //Here class AB is abstract class
{                          // Declare Above
        public:
        CD()
           {   /* set up the CD */  }
       virtual f()   // implementation of f() of class AB
           {
           /* do stuff of f() */
           }
};

Advantages and disadvantages of object oriented programming
Advantages –
1- Reusability of code.
2- Ease of comprehension.
3- Ease of fabrication and maintenance.
4- Ease of redesign and extension.
5- Data can be divided as public and private.(data protection)
6- Program development becomes easy due to increased modularity.(abstraction and encapsulation)
Disadvantages –
  1. The relation among classes become artificial at times
  2.  The object oriented programming design id difficult.
  3.  OOP is a high level concept so takes more time to execute as many routines run behind at the time of execution.
  4.  Offers less number of functions as compared to low level programming which interacts directly with hardware.
  5.  Increased burden on part of OOP developer.

control flow in c++

When a program is run, the CPU begins execution at the top of main(), executes some number of statements, and then terminates at the end of main(). The sequence of statements that the CPU executes is called the program’s path.  Straight-line programs have sequential flow — that is, they take the same path (execute the same statements) every time they are run (even if the user input changes).
However, often this is not what we desire. For example, if we ask the user to make a selection, and the user enters an invalid choice, ideally we’d like to ask the user to make another choice. This is not possible in a straight-line program.
Fortunately, C++ provides control flow statements (also called flow control statements), which allow the programmer to change the CPU’s path through the program. There are quite a few different types of control flow statements.
Different C++ flow control Statements
  • if statement
  • else if construct
  • switch statement
  • break statement
  • while loop
  • do while loop
  • for loop

Flow of Control

Looping statement

It is also called a Repetitive control structure. Sometimes we require a set of statements to be executed a number of times by changing the value of one or more variables each time to obtain a different result. This type of program execution is called looping. C++ provides the following construct
  • while loop
  • do-while loop
  • for loop

While loop

Syntax of while loop
while(condition)
{
   statement(s); 
}
The flow diagram indicates that a condition is first evaluated. If the condition is true, the loop body is executed and the condition is re-evaluated. Hence, the loop body is executed repeatedly as long as the condition remains true. As soon as the condition becomes false, it comes out of the loop and goes to the statement next to the ‘while’ loop.
while do-while loop

do-while loop

Syntax of do-while loop
do
{
  statements;
} while (condition);
Note : That the loop body is always executed at least once. One important difference between the while loop and the do-while loop the relative ordering of the conditional test and loop body execution. In the while loop, the loop repetition test is performed before each execution the loop body; the loop body is not executed at all if the initial test fail. In the do-while loop, the loop termination test is Performed after each execution of the loop body. hence, the loop body is always executed least once.
for loop

for loop

It is a count controlled loop in the sense that the program knows in advance how many times the loop is to be executed.
syntax of for loop for (initialization; decision; increment/decrement)
{
   statement(s);
}
The flow diagram indicates that in for loop three operations take place:
  • Initialization of loop control variable
  • Testing of loop control variable
  • Update the loop control variable either by incrementing or decrementing.
Operation (i) is used to initialize the value. On the other hand, operation (ii) is used to test whether the condition is true or false. If the condition is true, the program executes the body of the loop and then the value of loop control variable is updated. Again it checks the condition and so on. If the condition is false, it gets out of the loop.

Jump Statements

The jump statements unconditionally transfer program control within a function.
  • goto statement
  • break statement
  • continue statement
The goto statement
goto allows to make jump to another point in the program. goto pqr;
pqr:
 pqr is known as label. It is a user defined identifier. After the execution of goto statement, the control transfers to the line after label pqr.
The break statement
The break statement, when executed in a switch structure, provides an immediate
exit from the switch structure. Similarly, you can use the break statement in
any of the loop. When the break statement executes in a loop, it immediately exits from the loop.
The continue statement
The continue statement is used in loops and causes a program to skip the rest of the body of the loop.
while (condition)            
{
  Statement 1; 
    If (condition)
      continue;     
    statement; 
}
The continue statement skips rest of the loop body and starts a new iteration.
The exit ( ) function
The execution of a program can be stopped at any point with exit ( ) and a status code can be informed to the calling program. The general format is
exit (code) ;
where code is an integer value. The code has a value 0 for correct execution. The value of the code varies depending upon the operating system.

programming paradigms

What are Programming Paradigms?


    Imperative: The language provides statements, such as assignment statements , which explicitly change the state of the memory of the computer.
    Functional: In this paradigm we express computations as the evaluation of mathematical functions.
    Logic: In this paradigm we express computation in exclusively in terms of mathematical logic
    Object-Oriented: In this paradigm we associate behaviour with data-structures called " objects " which belong to classes which are usually structured into a hierarchy.
The paradigms are not exclusive, but reflect the different emphasis of language designers. Most practical imperative, functional and object-oriented languages embody features of more than one paradigm.

The Functional Paradigm

In this we emphasise the idea of computation as being about evaluating mathematical functions combined in expressions . While all languages try to provide a representation of basic functions like addition, functional languages support a functional way of expressing computations on large and complex structures, although some such as Scheme also have imperative features. In a pure functional language a mathematical identity like:
         fred(x) + fred(x) = 2*fred(x)
should hold. This is not necessarily the case for a non-functional language, for example in Pascal or C  fred  might be a procedure which had a side-effect, so that calling it twice has a different effect from calling it once. For example  fred  might contain the assignment  g:=g+1  where  g  is a global variable. The primary motivation of writing functionally is to develop programs whose behaviour can easily be analysed mathematically, and in any case is easy to predict and understand.
The same non-functional aspect holds also for Java. A method call fred(x) will commonly have a side-effect.
However it has been difficult to design languages under the functional paradigm which produce programs which run as fast as under the imperative paradigm. With the high performance of modern computers, this matters less for many applications than the ability to write correct programs. The functional paradigm is hard to implement efficiently because if a storage location is once used to hold a value it is not obvious when it can be re-used - a computer running a program using the functional paradigm can spend a lot of effort determining the reusability of store.
Another way to think of the functional paradigm is to regard it as a way of taking to its limit the advice to avoid harmful side-effects in a program.

The Imperative Paradigm

Languages which reflect this paradigm recognise the fact computers have re-usable memory that can change state. So they are characterised by statements, which affect the state of the machine, for example.
     x := x+1 
This can only be understood mathematically by associating a sequence of values with x let us say x1, x2,..., where xt denotes the value the variable x has at some time t. Thus the above statement can be translated into mathematics as
    xt+1 = xt + 1
This kind of reasoning is discussed in CS250. It gets increasingly hard to do as the state-changes get ever more complex (e.g. by assigning to data-structure components). However imperative languages can relatively easily be translated into efficient machine-code, and so are usually considered to be highly efficient. Many people also find the imperative paradigm to be a more natural way of expressing themselves.
Languages which use the imperative paradigm commonly have functional features - for example the basic functions of arithmetic (addition, subtraction...) are provided.

The Logic Paradigm

While the functional paradigm emphasises the idea of a mathematical function, the logic paradigm focusses on predicate logic, in which the basic concept is arelation. Logic languages are useful for expressing problems where it is not obvious what the functions should be. Thus, for example where people are concerned, it is natural to use relations.
For example consider the uncle relationship: a given person can have many uncles, and a another person can be uncle to many nieces and nephews.
Let us consider now how we can define the brother relation in terms of simpler relations and properties father, mother, male. Using the Prolog logic language one can say:
    brother(X,Y)      /* X is the brother of Y                    */
        :-            /* if there are two people F and M for which*/
        father(F,X),  /*          F is the father of X            */
        father(F,Y),  /*    and   F is the father of Y            */
        mother(M,X),  /*    and   M is the mother of X            */
        mother(M,Y),  /*    and   M is the mother of Y            */
        male(X).      /*    and   X is male                       */
That is  X  is the brother of  Y  if they have the same father and mother and  X  is male. Here " :- " stands for logical implication (written right to left).
Mathematical logic has always had an important role in computation, since boolean logic is the basis of the design of the logic circuits which form the basis of any computer. In the logic paradigm we make use of a more advanced construct, namely predicate logic, to give us languages of enhanced expressive power.

The Object-Oriented Paradigm

The Object Oriented paradigm (often written O-O) focusses on the objects that a program is representing, and on allowing them to exhibit "behaviour". This is contrasted with the typical approach in the imperative paradigm, in which one typically thinks of operating on data with procedures. In the imperative paradigm typically the data are passive, the procedures are active. In the O-O paradigm, data is combined with procedures to give objects, which are thereby rendered active. For example in the imperative paradigm, one would write a procedure which prints the various kinds of object in the program. In the O-O paradigm, each object has a print-method, and you "tell" an object to print itself.
It is however possible to use certain non object-oriented languages to write object-oriented programs. What is required is the ability to create data-structures that contain machine code, or pointers to machine code. This is possible in the C language and in most functional languages (where functions are represented as as code).
Objects belong to classes. Typically, all the objects in a given class will have the same kinds of behaviour.
Classes are usually arranged in some kind of class hierarchy. This hierarchy can be thought of as representing a "kind of" relation. For example, a computational model of the University might need a class person to represent the various people who make up the University. A sub-class of person might be a student; students are a kind of person. Another sub-class might be professor. Both students and professors can exhibit the same kinds of behaviour, since they are both people. They both eat drink and sleep, for example. But there are kinds of behaviour that are distinctive: professors pontificate for example.

The Scheme Language

This course is taught using the language Scheme which provides good support of the functional paradigm, since it contains a functional subset. However it also contains imperative features, which mean that we can look at the imperative paradigm within Scheme. It is a simple language but powerful enough to let us easily implement extensions which illustrate both the logic paradigm and the object-oriented paradigm.
In particular, it is quite easy to implement the object-oriented paradigm in Scheme because the functions available in Scheme can easily be attached to Scheme data-structures providing in effect objects that have behaviour arising from the attached functions.