Search This Blog

23 September, 2011

Android Interview Question and answers


Introduction Android:
Android is an operating system for mobile devices that includes middleware and key applications, and uses a modified version of the Linux kernel. It was initially developed by Android Inc..It allows developers to write managed code in the Java language, controlling the device via Google-developed Java libraries…..
The Android SDK includes a comprehensive set of development tools . These include a debugger, libraries, a handset emulator (based on QEMU), documentation, sample code, and tutorials. Currently supported development platforms include x86-architecture computers running Linux (any modern desktop Linux distribution), Mac OS X 10.4.8 or later, Windows XP or Vista.
Android does not use established Java standards, i.e. Java SE and ME. This prevents compatibility among Java applications written for those platforms and those for the Android platform. Android only reuses the Java language syntax, but does not provide the full-class libraries and APIs bundled with Java SE or ME
What is android?
Android is a stack of software for mobile devices which has Operating System, middleware and some key applications. The application executes within its own process and its own instance of Dalvik Virtual Machine. Many Virtual Machines run efficiently by a DVM device. DVM executes Java language?s byte code which later transforms into .dex format files.
What are the advantages of Android?
The following are the advantages of Android:
* The customer will be benefited from wide range of mobile applications to choose, since the monopoly of wireless carriers like AT&T and Orange will be broken by Google Android.
* Features like weather details, live RSS feeds, opening screen, icon on the opening screen can be customized
* Innovative products like the location-aware services, location of a nearby convenience store etc., are some of the additive facilities in Android.
Components can be reused and replaced by the application framework.
*Optimized DVM for mobile devices
*SQLite enables to store the data in a structured manner.
*Supports GSM telephone and Bluetooth, WiFi, 3G and EDGE technologies
*The development is a combination of a device emulator, debugging tools, memory profiling and plug-in for Eclipse IDE.
Features of Android
 Application framework enabling reuse and replacement of components
 Dalvik virtual machine optimized for mobile devices
 Integrated browser based on the open source WebKit engine
 Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional)
 SQLite for structured data storage
 Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)
 GSM Telephony (hardware dependent)
 Bluetooth, EDGE, 3G, and WiFi (hardware dependent)
 Camera, GPS, compass, and accelerometer (hardware dependent)
 Rich development environment including a device emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE.
Explain about the exceptions of Android?
The following are the exceptions that are supported by Android
* InflateException : When an error conditions are occurred, this exception is thrown
* Surface.OutOfResourceException: When a surface is not created or resized, this exception is thrown
* SurfaceHolder.BadSurfaceTypeException: This exception is thrown from the lockCanvas() method, when invoked on a Surface whose is SURFACE_TYPE_PUSH_BUFFERS
* WindowManager.BadTokenException: This exception is thrown at the time of trying to add view an invalid WindowManager.LayoutParamstoken.
Describe the APK format.
The APK file is compressed the AndroidManifest.xml file, application code (.dex files), resource files, and other files. A project is compiled into a single .apk file.
What is .apk extension? 
The extension for an Android package file, which typically contains all of the files related to a single Android application. The file itself is a compressed collection of an AndroidManifest.xml file, application code (.dex files), resource files, and other files. A project is compiled into a single .apk file.
What is .dex extension 
Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created by automatically translating compiled applications written in the Java programming language
What is an adb ?
Android Debug Bridge, a command-line debugging application shipped with the SDK. It provides tools to browse the device, copy tools on the device, and forward ports for debugging.
What is an Application ?
A collection of one or more activities, services, listeners, and intent receivers. An application has a single manifest, and is compiled into a single .apk file on the device.
What is a Content Provider ?
A class built on ContentProvider that handles content query strings of a specific format to return data in a specific format. See Reading and writing data to a content provider for information on using content providers.
What is a Dalvik ?
The name of Android’s virtual machine. The Dalvik VM is an interpreter-only virtual machine that executes files in the Dalvik Executable (.dex) format, a format that is optimized for efficient storage and memory-mappable execution. The virtual machine is register-based, and it can run classes compiled by a Java language compiler that have been transformed into its native format using the included “dx” tool. The VM runs on top of Posix-compliant operating systems, which it relies on for underlying functionality (such as threading and low level memory management). The Dalvik core class library is intended to provide a familiar development base for those used to programming with Java Standard Edition, but it is geared specifically to the needs of a small mobile device.
What is an DDMS 
Dalvik Debug Monitor Service, a GUI debugging application shipped with the SDK. It provides screen capture, log dump, and process examination capabilities.
What is Drawable? 
A compiled visual resource that can be used as a background, title, or other part of the screen. It is compiled into an android.graphics.drawable subclass.
What is an Intent?
A class (Intent) that contains several fields describing what a caller would like to do. The caller sends this intent to Android’s intent resolver, which looks through the intent filters of all applications to find the activity most suited to handle this intent. Intent fields include the desired action, a category, a data string, the MIME type of the data, a handling class, and other restrictions.
What is an Intent Filter ?
Activities and intent receivers include one or more filters in their manifest to describe what kinds of intents or messages they can handle or want to receive. An intent filter lists a set of requirements, such as data type, action requested, and URI format, that the Intent or message must fulfill. For Activities, Android searches for the Activity with the most closely matching valid match between the Intent and the activity filter. For messages, Android will forward a message to all receivers with matching intent filters.
What is an Intent Receiver? 
An application class that listens for messages broadcast by calling Context.broadcastIntent
What is a Layout resource?
An XML file that describes the layout of an Activity screen.
What is a Manifest ?
An XML file associated with each Application that describes the various activies, intent filters, services, and other items that it exposes.
What is a Resource 
A user-supplied XML, bitmap, or other file, entered into an application build process, which can later be loaded from code. Android can accept resources of many types; see Resources for a full description. Application-defined resources should be stored in the res/ subfolders.
What is a Service ?
A class that runs in the background to perform various persistent actions, such as playing music or monitoring network activity.
What is a Theme ?
A set of properties (text size, background color, and so on) bundled together to define various default display settings. Android provides a few standard themes, listed in R.style (starting with “Theme_”).
What is an URIs? 
Android uses URI strings both for requesting data (e.g., a list of contacts) and for requesting actions (e.g., opening a Web page in a browser). Both are valid URI strings, but have different values. All requests for data must start with the string “content://”. Action strings are valid URIs that can be handled appropriately by applications on the device; for example, a URI starting with “http://” will be handled by the browser.
Can I write code for Android using C/C++?
Yes, but need to use NDK
Android applications are written using the Java programming language. Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language.
Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included “dx” tool.
Android only supports applications written using the Java programming language at this time.
What is an action?
A description of something that an Intent sender desires.
What is activity?
A single screen in an application, with supporting Java code.
What is intent?
A class (Intent) describes what a caller desires to do. The caller sends this intent to Android’s intent resolver, which finds the most suitable activity for the intent. E.g. opening a PDF file is an intent, and the Adobe Reader is the suitable activity for this intent.
How is nine-patch image different from a regular bitmap?
It is a resizable bitmap resource that can be used for backgrounds or other images on the device. The NinePatch class permits drawing a bitmap in nine sections. The four corners are unscaled; the four edges are scaled in one axis, and the middle is scaled in both axes.
What languages does Android support for application development?
Android applications are written using the Java programming language.
What is a resource?
A user-supplied XML, bitmap, or other file, injected into the application build process, which can later be loaded from code.
How will you record a phone call in Android? How to get a handle on Audio Stream for a call in Android?
Permissions.PROCESS_OUTGOING_CALLS: Allows an application to monitor, modify, or abort outgoing calls.
What’s the difference between file, class and activity in android? 
File – It is a block of arbitrary information, or resource for storing information. It can be of any type.
Class – Its a compiled form of .Java file . Android finally used this .class files to produce an executable apk
Activity – An activity is the equivalent of a Frame/Window in GUI toolkits. It is not a file or a file type it is just a class that can be extended in Android for loading UI elements on view.
What is a Sticky Intent?
sendStickyBroadcast() performs a sendBroadcast (Intent) that is “sticky,” i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver (BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent).
One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED. When you call registerReceiver() for that action — even with a null BroadcastReceiver — you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.
Does Android support the Bluetooth serial port profile?
Yes.
Can an application be started on powerup?
Yes.
How to Remove Desktop icons and Widgets
A. Press and Hold the icon or widget. The phone will vibrate and on the bottom of the phone you will see anoption to remove. While still holding the icon or widget drag it to the remove button. Once remove turns red drop the item and it is gone
Describe a real time scenario where android can be used?
Imagine a situation that you are in a country where no one understands the language you speak and you can not read or write. However, you have mobile phone with you.
With a mobile phone with android, the Google translator translates the data of one language into another language by using XMPP to transmit data. You can type the message in English and select the language which is understood by the citizens of the country in order to reach the message to the citizens.
How to select more than one option from list in android xml file? 
Give an example.
Specify android id, layout height and width as depicted in the following example.
What languages does Android support for application development?
Android applications are written using the Java programming language.
Describe Android Application Architecture.
Android Application Architecture has the following components:
• Services – like Network Operation
• Intent – To perform inter-communication between activities or services
• Resource Externalization – such as strings and graphics
• Notification signaling users – light, sound, icon, notification, dialog etc.
• Content Providers – They share data between applications
Common Tricky questions
 Remember that the GUI layer doesn’t request data directly from the web; data is always loaded from a local database.
 The service layer periodically updates the local database.
 What is the risk in blocking the Main thread when performing a lengthy operation such as web access or heavy computation? Application_Not_Responding exception will be thrown which will crash and restart the application.
 Why is List View not recommended to have active components? Clicking on the active text box will pop up the software keyboard but this will resize the list, removing focus from the clicked element.

13 September, 2011

iPhones Are For Old People, says HTC Chief



The iPhone 4 and the iPhone 3GS are the two top-selling phones in America. But don’t let that fool you into thinking they’re cool, says Martin Fichter, acting president of HTC America.
Speaking at the Mobile Future Forward conference in Seattle, Fichter — pictured above with bicycle — related a story about taking his daughter to Reed College in Portland, where he took an informal survey of her dormitory buddies. “None of them has an iPhone,” Fichter said, “because they told me: ‘My dad has an iPhone.’ There’s an interesting thing that’s going on in the market. The iPhone becomes a little less cool than it was. They were carrying HTCs. They were carrying Samsungs. They were even carrying some Chinese manufacturer’s devices.”
Added Fichter: “Macbook Airs are cool. iPhones are not that cool anymore. We here are using iPhones, but our kids don’t find them that cool anymore.”
HTC has been making some aggressive moves in the market of late. Currently, the manufacturer uses Android and Windows Phone 7 for its operating systems; earlier Monday, its CEO suggested in an interview that he was looking around for other mobile OS options, so that the company isn’t so reliant on software from Google or Microsoft; this despite the pro-Android stance that HTC took in the wake of the Google-Motorola deal. HTC has a smartphone market share of 9% and growing fast. At some Verizon stores, according to one poll, the HTC Thunderbolt has been outselling the iPhone 4.
Now comes Fichter, launching a broadside against one of the iPhone’s strongest defenses: the elusive sense of “cool.” It’s a risky strategy, especially given the anticipation swirling around the impending iPhone 5 launch. Presenting your daughter’s college dorm as representative of a wider trend, especially when the whole world is waiting for Apple’s next phone, seems a sure-fire route to ridicule.
On the other hand, Fichter has a point: iPhone owners tend to be older and more affluent, largely because their device is more expensive than the average Android equivalent. According to a recent infographic from recommendation engine Hunch, Android owners tend to have only a high school diploma and to be aged between 18 and 34 — the cool years, as far as most marketers are concerned.
Can HTC outmaneuver Apple by attempting to marginalize the iPhone? Or will the iPhone 5 launch blow that idea out of the water? Let us know what you think in the comments.
----------------------------------------------------------------------------------

Google announces next Android OS, Jelly Bean


Google announces next Android OS, Jelly Bean






Close on the heels of GoogleExecutive Chairman Eric Schmidt announcing the arrival of the upcoming version of AndroidOS termed Ice Cream Sandwich in October or November, speculations have started on the next version of Android. 

According to a report citing trusted sources in 'This is My Next', Jelly Bean is the working name for next incarnation of Android. 

The name follows Google's tradition of calling its Android operating systems after sweets in alphabetical order. Earlier versions of Android follow a typical order -- Cupcake 1.5, Donut 1.6, Eclair 2.1, Froyo 2.2, Gingerbread 2.3,Honeycomb 3.0 and the upcoming Ice Cream Sandwich. 

The report quotes industry source saying, that the "game-changing stuff" that had originally been scheduled for Ice Cream Sandwich will be being pushed to Jelly Bean. Jelly Bean could be dubbed Android 4.5 or Android 5.0, depending on the amount of features packed, says the report.

Ice Cream Sandwich is expected to be a universal operating system that will work on phones, tablets, TVs, and even phones that transform into laptops. Among other things, the OS is likely to bring an updated app launcher, holographic user interface, interactive and new homescreen widgets and a multi-tasking panel. 

----------------------------------------------------------------------------------

11 September, 2011

C++ Operator Overloading Guidelines


C++ Operator Overloading Guidelines

One of the nice features of C++ is that you can give special meanings to operators, when they are used with user-defined classes. This is called operator overloading. You can implement C++ operator overloads by providing special member-functions on your classes that follow a particular naming convention. For example, to overload the + operator for your class, you would provide a member-function named operator+ on your class.
The following set of operators is commonly overloaded for user-defined classes:
  • = (assignment operator)
  • + - * (binary arithmetic operators)
  • += -= *= (compound assignment operators)
  • == != (comparison operators)

Here are some guidelines for implementing these operators. These guidelines are very important to follow, so definitely get in the habit early.

Assignment Operator =

The assignment operator has a signature like this:
  class MyClass {
  public:
    ...
    MyClass & operator=(const MyClass &rhs);
    ...
  }

  MyClass a, b;
  ...
  b = a;   // Same as b.operator=(a);

Notice that the = operator takes a const-reference to the right hand side of the assignment. The reason for this should be obvious, since we don't want to change that value; we only want to change what's on the left hand side.
Also, you will notice that a reference is returned by the assignment operator. This is to allow operator chaining. You typically see it with primitive types, like this:
  int a, b, c, d, e;

  a = b = c = d = e = 42;
This is interpreted by the compiler as:
  a = (b = (c = (d = (e = 42))));
In other words, assignment is right-associative. The last assignment operation is evaluated first, and is propagated leftward through the series of assignments. Specifically:
  • e = 42 assigns 42 to e, then returns e as the result
  • The value of e is then assigned to d, and then d is returned as the result
  • The value of d is then assigned to c, and then c is returned as the result
  • etc.

Now, in order to support operator chaining, the assignment operator must return some value. The value that should be returned is a reference to the left-hand side of the assignment.
Notice that the returned reference is not declared const. This can be a bit confusing, because it allows you to write crazy stuff like this:
  MyClass a, b, c;
  ...
  (a = b) = c;  // What??
At first glance, you might want to prevent situations like this, by having operator= return a const reference. However, statements like this will work with primitive types. And, even worse, some tools actually rely on this behavior. Therefore, it is important to return a non-const reference from your operator=. The rule of thumb is, "If it's good enough for ints, it's good enough for user-defined data-types."
So, for the hypothetical MyClass assignment operator, you would do something like this:
  // Take a const-reference to the right-hand side of the assignment.
  // Return a non-const reference to the left-hand side.
  MyClass& MyClass::operator=(const MyClass &rhs) {
    ...  // Do the assignment operation!

    return *this;  // Return a reference to myself.
  }
Remember, this is a pointer to the object that the member function is being called on. Since a = b is treated as a.operator=(b), you can see why it makes sense to return the object that the function is called on; object a is the left-hand side.
But, the member function needs to return a reference to the object, not a pointer to the object. So, it returns *this, which returns what this points at (i.e. the object), not the pointer itself. (In C++, instances are turned into references, and vice versa, pretty much automatically, so even though *this is an instance, C++ implicitly converts it into a reference to the instance.)
Now, one more very important point about the assignment operator:
YOU MUST CHECK FOR SELF-ASSIGNMENT!
This is especially important when your class does its own memory allocation. Here is why: The typical sequence of operations within an assignment operator is usually something like this:
  MyClass& MyClass::operator=(const MyClass &rhs) {
    // 1.  Deallocate any memory that MyClass is using internally
    // 2.  Allocate some memory to hold the contents of rhs
    // 3.  Copy the values from rhs into this instance
    // 4.  Return *this
  }
Now, what happens when you do something like this:
  MyClass mc;
  ...
  mc = mc;     // BLAMMO.
You can hopefully see that this would wreak havoc on your program. Because mc is on the left-hand side and on the right-hand side, the first thing that happens is that mc releases any memory it holds internally. But, this is where the values were going to be copied from, since mc is also on the right-hand side! So, you can see that this completely messes up the rest of the assignment operator's internals.
The easy way to avoid this is to CHECK FOR SELF-ASSIGNMENT. There are many ways to answer the question, "Are these two instances the same?" But, for our purposes, just compare the two objects' addresses. If they are the same, then don't do assignment. If they are different, then do the assignment.
So, the correct and safe version of the MyClass assignment operator would be this:
  MyClass& MyClass::operator=(const MyClass &rhs) {
    // Check for self-assignment!
    if (this == &rhs)      // Same object?
      return *this;        // Yes, so skip assignment, and just return *this.

    ... // Deallocate, allocate new space, copy values...

    return *this;
  }
Or, you can simplify this a bit by doing:
  MyClass& MyClass::operator=(const MyClass &rhs) {

    // Only do assignment if RHS is a different object from this.
    if (this != &rhs) {
      ... // Deallocate, allocate new space, copy values...
    }

    return *this;
  }
Remember that in the comparison, this is a pointer to the object being called, and &rhs is a pointer to the object being passed in as the argument. So, you can see that we avoid the dangers of self-assignment with this check.
In summary, the guidelines for the assignment operator are:
  1. Take a const-reference for the argument (the right-hand side of the assignment).
  2. Return a reference to the left-hand side, to support safe and reasonable operator chaining. (Do this by returning *this.)
  3. Check for self-assignment, by comparing the pointers (this to &rhs).

Compound Assignment Operators += -= *=

I discuss these before the arithmetic operators for a very specific reason, but we will get to that in a moment. The important point is that these are destructive operators, because they update or replace the values on the left-hand side of the assignment. So, you write:
  MyClass a, b;
  ...
  a += b;    // Same as a.operator+=(b)
In this case, the values within a are modified by the += operator.
How those values are modified isn't very important - obviously, what MyClass represents will dictate what these operators mean.
The member function signature for such an operator should be like this:
  MyClass & MyClass::operator+=(const MyClass &rhs) {
    ...
  }
We have already covered the reason why rhs is a const-reference. And, the implementation of such an operation should also be straightforward.
But, you will notice that the operator returns a MyClass-reference, and a non-const one at that. This is so you can do things like this:
  MyClass mc;
  ...
  (mc += 5) += 3;

Don't ask me why somebody would want to do this, but just like the normal assignment operator, this is allowed by the primitive data types. Our user-defined datatypes should match the same general characteristics of the primitive data types when it comes to operators, to make sure that everything works as expected.
This is very straightforward to do. Just write your compound assignment operator implementation, and return *this at the end, just like for the regular assignment operator. So, you would end up with something like this:
  MyClass & MyClass::operator+=(const MyClass &rhs) {
    ...   // Do the compound assignment work.

    return *this;
  }

As one last note, in general you should beware of self-assignment with compound assignment operators as well. Fortunately, none of the C++ track's labs require you to worry about this, but you should always give it some thought when you are working on your own classes.

Binary Arithmetic Operators + - *

The binary arithmetic operators are interesting because they don't modify either operand - they actually return a new value from the two arguments. You might think this is going to be an annoying bit of extra work, but here is the secret:
Define your binary arithmetic operators using your compound assignment operators.
There, I just saved you a bunch of time on your homeworks.
So, you have implemented your += operator, and now you want to implement the + operator. The function signature should be like this:
  // Add this instance's value to other, and return a new instance
  // with the result.
  const MyClass MyClass::operator+(const MyClass &other) const {
    MyClass result = *this;     // Make a copy of myself.  Same as MyClass result(*this);
    result += other;            // Use += to add other to the copy.
    return result;              // All done!
  }
Simple!
Actually, this explicitly spells out all of the steps, and if you want, you can combine them all into a single statement, like so:
  // Add this instance's value to other, and return a new instance
  // with the result.
  const MyClass MyClass::operator+(const MyClass &other) const {
    return MyClass(*this) += other;
  }
This creates an unnamed instance of MyClass, which is a copy of *this. Then, the += operator is called on the temporary value, and then returns it.
If that last statement doesn't make sense to you yet, then stick with the other way, which spells out all of the steps. But, if you understand exactly what is going on, then you can use that approach.
You will notice that the + operator returns a const instance, not a const reference. This is so that people can't write strange statements like this:
  MyClass a, b, c;
  ...
  (a + b) = c;   // Wuh...?
This statement would basically do nothing, but if the + operator returns a non-const value, it will compile! So, we want to return a const instance, so that such madness will not even be allowed to compile.
To summarize, the guidelines for the binary arithmetic operators are:
  1. Implement the compound assignment operators from scratch, and then define the binary arithmetic operators in terms of the corresponding compound assignment operators.
  2. Return a const instance, to prevent worthless and confusing assignment operations that shouldn't be allowed.

Comparison Operators == and !=

The comparison operators are very simple. Define == first, using a function signature like this:
  bool MyClass::operator==(const MyClass &other) const {
    ...  // Compare the values, and return a bool result.
  }
The internals are very obvious and straightforward, and the bool return-value is also very obvious.
The important point here is that the != operator can also be defined in terms of the == operator, and you should do this to save effort. You can do something like this:
  bool MyClass::operator!=(const MyClass &other) const {
    return !(*this == other);
  }
That way you get to reuse the hard work you did on implementing your == operator. Also, your code is far less likely to exhibit inconsistencies between == and !=, since one is implemented in terms of the other.


-0--0-0-0-0-0-0-0-0-0-0-0--0-0-0--0-0--0--0-0-0-0--

Operator Overloading in C++


Operator Overloading in C++

by Andrei Milea

In C++ the overloading principle applies not only to functions, but to operators too. That is, of operators can be extended to work not just with built-in types but also classes. A programmer can provide his or her own operator to a class by overloading the built-in operator to perform some specific computation when the operator is used on objects of that class. Is operator overloading really useful in real world implementations? It certainlly can be, making it very easy to write code that feels natural (we'll see some examples soon). On the other hand, operator overloading, like any advanced C++ feature, makes the language more complicated. In addition, operators tend to have very specific meaning, and most programmers don't expect operators to do a lot of work, so overloading operators can be abused to make code unreadable. But we won't do that.


An Example of Operator Overloading
Complex a(1.2,1.3);     //this class is used to represent complex numbers
Complex b(2.1,3);       //notice the construction taking 2 parameters for the real and imaginary part
Complex c = a+b;        //for this to work the addition operator must be overloaded
The addition without having overloaded operator + could look like this:
Complex c = a.Add(b);
This piece of code is not as readable as the first example though--we're dealing with numbers, so doing addition should be natural. (In contrast to cases when programmers abuse this technique, when the concept represented by the class is not related to the operator--ike using + and - to add and remove elements from a data structure. In this cases operator overloading is a bad idea, creating confusion.)

In order to allow operations like Complex c = a+b, in above code we overload the "+" operator. The overloading syntax is quite simple, similar to function overloading, the keyword operator must be followed by the operator we want to overload:
class Complex
{
public:
        Complex(double re,double im)
                :real(re),imag(im)
                {};
        Complex operator+(const Complex& other);
        Complex operator=(const Complex& other);
private:
        double real;
        double imag;
};
Complex Complex::operator+(const Complex&  other)
{
    double result_real = real + other.real;
    double result_imaginary = imag + other.imag;
    return Complex( result_real, result_imaginary );
}
The assignment operator can be overloaded similarly. Notice that we did not have to call any accessor functions in order to get the real and imaginary parts from the parameter other since the overloaded operator is a member of the class and has full access to all private data. Alternatively, we could have defined the addition operator globally and called a member to do the actual work. In that case, we'd also have to make the method a friend of the class, or use an accessor method to get at the private data:
friend Complex operator+(Complex); 

Complex operator+(const Complex  &num1, const Complex &num2)
{
    double result_real = num1.real + num2.real;
    double result_imaginary = num1.imag + num2.imag;
    return Complex( result_real, result_imaginary );
}
Why would you do this? when the operator is a class member, the first object in the expression must be of that particular type. It's as if you were writing:
Complex a( 1, 2 );
Complex a( 2, 2 );
Complex c = a.operator=( b );
when it's a global function, the implicit or user-defined conversion can allow the operator to act even if the first operand is not exactly of the same type:
Complex c = 2+b;        //if the integer 2  can be converted by the Complex class, this expression is valid
By the way, the number of operands to a function is fixed; that is, a binary operator takes two operands, a unary only one, and you can't change it. The same is true for the precedence of operators too; for example the multiplication operator is called before addition. There are some operators that need the first operand to be assignable, such as : operator=, operator(), operator[] and operator->, so their use is restricted just as member functions(non-static), they can't be overloaded globally. The operator=, operator& and operator, (sequencing) have already defined meanings by default for all objects, but their meanings can be changed by overloading or erased by making them private.

Another intuitive meaning of the "+" operator from the STL string class which is overloaded to do concatenation:
string prefix("de");
string word("composed");
string composed = prefix+word;
Using "+" to concatenate is also allowed in Java, but note that this is not extensible to other classes, and it's not a user defined behavior. Almost all operators can be overloaded in C++:
+       -       *       /       %       ^       &       |
        ~       !       ,       =       <       >       <=      >=
        ++      --      <<      >>      ==      !=      &&      ||
        +=      -=      /=      %=      ^=      & =     |=      *=
        <<=     >>=     [ ]     ( )     ->      ->*     new     delete
The only operators that can't be overloaded are the operators for scope resolution (::), member selection (.), and member selection through a pointer to a function(.*). Overloading assumes you specify a behavior for an operator that acts on a user defined type and it can't be used just with general pointers. The standard behavior of operators for built-in (primitive) types cannot be changed by overloading, that is, you can't overload operator+(int,int).

The logic(boolean) operators have by the default a short-circuiting way of acting in expressions with multiple boolean operations. This means that the expression:
if(a && b && c) 
will not evaluate all three operations and will stop after a false one is found. This behavior does not apply to operators that are overloaded by the programmer.

Even the simplest C++ application, like a "hello world" program, is using overloaded operators. This is due to the use of this technique almost everywhere in the standard library (STL). Actually the most basic operations in C++ are done with overloaded operators, the IO(input/output) operators are overloaded versions of shift operators(<<, >>). Their use comes naturally to many beginning programmers, but their implementation is not straightforward. However a general format for overloading the input/output operators must be known by any C++ developer. We will apply this general form to manage the input/output for our Complex class:
friend ostream &operator<<(ostream &out, Complex c)     //output
{
        out<<"real part: "<<real<<"\n";
        out<<"imag part: "<<imag<<"\n";
        return out;
}
friend istream &operator>>(istream &in, Complex &c)     //input
{
        cout<<"enter real part:\n";
        in>>c.real;
        cout<<"enter imag part: \n";
        in>>c.imag;
        return in;
}
Notice the use of the friend keyword in order to access the private members in the above implementations. The main distinction between them is that the operator>> may encounter unexpected errors for incorrect input, which will make it fail sometimes because we haven't handled the errors correctly. A important trick that can be seen in this general way of overloading IO is the returning reference for istream/ostream which is needed in order to use them in a recursive manner:
Complex a(2,3);
Complex b(5.3,6);
cout<<a<<b;

Meetme@