Global and Local Variables

A scope is a region of the program and broadly speaking there are three places, where variables can be declared:

  • Inside a function or a block which is called local variables,
  • In the definition of function parameters which is called formal parameters.
  • Outside of all functions which is called global variables.

We will learn what is a function and it’s parameter in subsequent chapters. Here let us explain what are local and global variables.

#include <iostream>
using namespace std;

int main ()
{
  // Local variable declaration:
  int a, b;
  int c;

  // actual initialization
  a = 10;
  b = 20;
  c = a + b;

  cout << c;

  return 0;
}

Global Variables:

Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the life-time of your program.

A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables:

#include <iostream>
using namespace std;

// Global variable declaration:
int g;

int main ()
{
  // Local variable declaration:
  int a, b;

  // actual initialization
  a = 10;
  b = 20;
  g = a + b;

  cout << g;

  return 0;
}

A program can have same name for local and global variables but value of local variable inside a function will take preference. For example:

#include <iostream>
using namespace std;

// Global variable declaration:
int g = 20;

int main ()
{
  // Local variable declaration:
  int g = 10;

  cout << g;

  return 0;
}

When the above code is compiled and executed, it produces the following result:

10

Initializing Local and Global Variables:

When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows:

Data Type Initializer
int 0
char ‘\0’
float 0
double 0
pointer NULL

It is a good programming practice to initialize variables properly, otherwise sometimes program would produce unexpected result.

Factory Methods init-alloc, new

Objects Are Created Dynamically

 

Memory is allocated dynamically for an Objective-C object. The first step in creating an object is to make sure enough memory is allocated not only for the properties defined by an object’s class, but also the properties defined on each of the superclasses in its inheritance chain.

The NSObject root class provides a class method, alloc, which handles this process for you:

+ (id)alloc;

Notice that the return type of this method is id. This is a special keyword used in Objective-C to mean “some kind of object.” It is a pointer to an object, like (NSObject *), but is special in that it doesn’t use an asterisk.

The alloc method has one other important task, which is to clear out the memory allocated for the object’s properties by setting them to zero. This avoids the usual problem of memory containing garbage from whatever was stored before, but is not enough to initialize an object completely.

You need to combine a call to alloc with a call to init, another NSObject method:

- (id)init;

The init method is used by a class to make sure its properties have suitable initial values at creation, and is covered in more detail in the next chapter.

Note that init also returns an id.

If one method returns an object pointer, it’s possible to nest the call to that method as the receiver in a call to another method, thereby combining multiple message calls in one statement. The correct way to allocate and initialize an object is to nest the alloc call inside the call to init, like this:

    NSObject *newObject = [[NSObject alloc] init];

This example sets the newObject variable to point to a newly created NSObject instance.

The innermost call is carried out first, so the NSObject class is sent the alloc method, which returns a newly allocated NSObject instance. This returned object is then used as the receiver of the init message, which itself returns the object back to be assigned to the newObject pointer, as shown in Figure 2-5.

Figure 2-5  Nesting the alloc and init message

Initializer Methods Can Take Arguments

Some objects need to be initialized with required values. An NSNumber object, for example, must be created with the numeric value it needs to represent.

The NSNumber class defines several initializers, including:

- (id)initWithBool:(BOOL)value;
- (id)initWithFloat:(float)value;
- (id)initWithInt:(int)value;
- (id)initWithLong:(long)value;

Initialization methods with arguments are called in just the same way as plain init methods—an NSNumber object is allocated and initialized like this:

    NSNumber *magicNumber = [[NSNumber alloc] initWithInt:42];

Class Factory Methods Are an Alternative to Allocation and Initialization

As mentioned in the previous chapter, a class can also define factory methods. Factory methods offer an alternative to the traditional alloc] init]process, without the need to nest two methods.

The NSNumber class defines several class factory methods to match its initializers, including:

+ (NSNumber *)numberWithBool:(BOOL)value;
+ (NSNumber *)numberWithFloat:(float)value;
+ (NSNumber *)numberWithInt:(int)value;
+ (NSNumber *)numberWithLong:(long)value;

A factory method is used like this:

    NSNumber *magicNumber = [NSNumber numberWithInt:42];

This is effectively the same as the previous example using alloc] initWithInt:]. Class factory methods usually just call straight through to alloc and the relevant init method, and are provided for convenience.

Use new to Create an Object If No Arguments Are Needed for Initialization

It’s also possible to create an instance of a class using the new class method. This method is provided by NSObject and doesn’t need to be overridden in your own subclasses.

It’s effectively the same as calling alloc and init with no arguments:

    XYZObject *object = [XYZObject new];
    // is effectively the same as:
    XYZObject *object = [[XYZObject alloc] init];

Literals Offer a Concise Object-Creation Syntax

Some classes allow you to use a more concise, literal syntax to create instances.

You can create an NSString instance, for example, using a special literal notation, like this:

    NSString *someString = @"Hello, World!";

This is effectively the same as allocating and initializing an NSString or using one of its class factory methods:

    NSString *someString = [NSString stringWithCString:"Hello, World!"
                                              encoding:NSUTF8StringEncoding];

The NSNumber class also allows a variety of literals:

    NSNumber *myBOOL = @YES;
    NSNumber *myFloat = @3.14f;
    NSNumber *myInt = @42;
    NSNumber *myLong = @42L;

Again, each of these examples is effectively the same as using the relevant initializer or a class factory method.

You can also create an NSNumber using a boxed expression, like this:

    NSNumber *myInt = @(84 / 2);

In this case, the expression is evaluated, and an NSNumber instance created with the result.

Objective-C also supports literals to create immutable NSArray and NSDictionary objects;

 

Factory Methods alternative Vs init-alloc, new

Objects Are Created Dynamically

 

Memory is allocated dynamically for an Objective-C object. The first step in creating an object is to make sure enough memory is allocated not only for the properties defined by an object’s class, but also the properties defined on each of the superclasses in its inheritance chain.

The NSObject root class provides a class method, alloc, which handles this process for you:

+ (id)alloc;

Notice that the return type of this method is id. This is a special keyword used in Objective-C to mean “some kind of object.” It is a pointer to an object, like (NSObject *), but is special in that it doesn’t use an asterisk.

The alloc method has one other important task, which is to clear out the memory allocated for the object’s properties by setting them to zero. This avoids the usual problem of memory containing garbage from whatever was stored before, but is not enough to initialize an object completely.

You need to combine a call to alloc with a call to init, another NSObject method:

- (id)init;

The init method is used by a class to make sure its properties have suitable initial values at creation, and is covered in more detail in the next chapter.

Note that init also returns an id.

If one method returns an object pointer, it’s possible to nest the call to that method as the receiver in a call to another method, thereby combining multiple message calls in one statement. The correct way to allocate and initialize an object is to nest the alloc call inside the call to init, like this:

    NSObject *newObject = [[NSObject alloc] init];

This example sets the newObject variable to point to a newly created NSObject instance.

The innermost call is carried out first, so the NSObject class is sent the alloc method, which returns a newly allocated NSObject instance. This returned object is then used as the receiver of the init message, which itself returns the object back to be assigned to the newObject pointer, as shown in Figure 2-5.

Figure 2-5  Nesting the alloc and init message

Initializer Methods Can Take Arguments

Some objects need to be initialized with required values. An NSNumber object, for example, must be created with the numeric value it needs to represent.

The NSNumber class defines several initializers, including:

- (id)initWithBool:(BOOL)value;
- (id)initWithFloat:(float)value;
- (id)initWithInt:(int)value;
- (id)initWithLong:(long)value;

Initialization methods with arguments are called in just the same way as plain init methods—an NSNumber object is allocated and initialized like this:

    NSNumber *magicNumber = [[NSNumber alloc] initWithInt:42];

Class Factory Methods Are an Alternative to Allocation and Initialization

As mentioned in the previous chapter, a class can also define factory methods. Factory methods offer an alternative to the traditional alloc] init]process, without the need to nest two methods.

The NSNumber class defines several class factory methods to match its initializers, including:

+ (NSNumber *)numberWithBool:(BOOL)value;
+ (NSNumber *)numberWithFloat:(float)value;
+ (NSNumber *)numberWithInt:(int)value;
+ (NSNumber *)numberWithLong:(long)value;

A factory method is used like this:

    NSNumber *magicNumber = [NSNumber numberWithInt:42];

This is effectively the same as the previous example using alloc] initWithInt:]. Class factory methods usually just call straight through to alloc and the relevant init method, and are provided for convenience.

Use new to Create an Object If No Arguments Are Needed for Initialization

It’s also possible to create an instance of a class using the new class method. This method is provided by NSObject and doesn’t need to be overridden in your own subclasses.

It’s effectively the same as calling alloc and init with no arguments:

    XYZObject *object = [XYZObject new];
    // is effectively the same as:
    XYZObject *object = [[XYZObject alloc] init];

Literals Offer a Concise Object-Creation Syntax

Some classes allow you to use a more concise, literal syntax to create instances.

You can create an NSString instance, for example, using a special literal notation, like this:

    NSString *someString = @"Hello, World!";

This is effectively the same as allocating and initializing an NSString or using one of its class factory methods:

    NSString *someString = [NSString stringWithCString:"Hello, World!"
                                              encoding:NSUTF8StringEncoding];

The NSNumber class also allows a variety of literals:

    NSNumber *myBOOL = @YES;
    NSNumber *myFloat = @3.14f;
    NSNumber *myInt = @42;
    NSNumber *myLong = @42L;

Again, each of these examples is effectively the same as using the relevant initializer or a class factory method.

You can also create an NSNumber using a boxed expression, like this:

    NSNumber *myInt = @(84 / 2);

In this case, the expression is evaluated, and an NSNumber instance created with the result.

Objective-C also supports literals to create immutable NSArray and NSDictionary objects;

 

‘this’ pointer in C++

The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. ‘this’ pointer is a constant pointer that holds the memory address of the current object. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name).
For a class X, the type of this pointer is ‘X* const’. Also, if a member function of X is declared as const, then the type of this pointer is ‘const X *const’.

Following are the situations where ‘this’ pointer is used:

1) When local variable’s name is same as member’s name

#include
using namespace std;
 
/* local variable is same as a member's name */
class Test
{
private:
   int x;
public:
   void setX (int x)
   {
       // The 'this' pointer is used to retrieve the object's x
       // hidden by the local variable 'x'
       this->x = x;
   }
   void print() { cout << "x = " << x << endl; }
};
 
int main()
{
   Test obj;
   int x = 20;
   obj.setX(x);
   obj.print();
   return 0;
}

Output:

x = 20

Easy reading from Keyboard in Java

We can use Scanner class

Import first:

import java.util.Scanner;

Then we go this way for integers.

Scanner keyboard = new Scanner(System.in);
System.out.println("enter an integer");
int myint = keyboard.nextInt();

If we rather a string line:

String text= scan.nextLine();

Easy piece!

Note: If you are using nextInt() with nextLine() it may probably could have some trouble cause nextInt() does not read the last newline character of input and so nextLine().

Static

Static

Los métodos static no requieren una instancia de la clase, ni pueden acceder a los datos de la clase/objeto de forma implícita.

Un método static se distingue en algunos lenguajes de programación con la palabra clave static colocada en algún lugar en la firma del método.

Los metodos estaticos se cargan en memoria en tiempo de compilación y no a medida que se ejecutan las líneas de código del programa. Van precedidos del modificador static. Para invocar a un método estático no se necesita crear un objeto de la clase en la que se define:

  • Si se invoca desde la clase en la que se encuentra definido, basta con escribir su nombre.
  • Si se le invoca desde una clase distinta, debe anteponerse a su nombre, el de la clase en la que se encuentra seguido del operador punto (.) .metodoEstatico

Suelen emplearse para realizar operaciones comunes a todos los objetos de la clase.

Dado que los métodos estáticos tienen sentido a nivel de clase y no a nivel de objeto (instancia) los métodos estáticos no pueden acceder a datos miembros que no sean estáticos.

C++

Class MyClass {
public:
static float areaCirc (radio){
  //do some math here
  return area;
 }
};

Java

public class Mechanics {

    // add an instance variable for the object ID    
    private int cadence;
    private int gear;
    private int speed;

    //static method
    public static double speedURM (int dist, float time){
     // do some math here
    return urmSpeed;
}
}

Static methods

Static

 

Static methods neither require an instance of the class nor can they implicitly access the data (or this, self, Me, etc.) of such an instance. A static method is distinguished in some programming languages with the static keyword placed somewhere in the method’s signature.

In statically typed languages such as Java, static methods are called “static” because they are resolved statically (i.e. at compile time) based on the class they are called on and not dynamically as in the case with instance methods which are resolved polymorphically based on the runtime type of the object. Therefore, static methods cannot be overridden.

C++

Class MyClass {
public:
static float areaCirc (radio){
  //do some math here
  return area;
 }
};

Java

public class Mechanics {

    // add an instance variable for the object ID    
    private int cadence;
    private int gear;
    private int speed;

    //static method
    public static double speedURM (int dist, float time){
     // do some math here
    return urmSpeed;
}
}