Saturday, September 5, 2009

Operator Overloading

It is a wonderful feature of C++ through which we can provide different meaning to the operators such as +,-,=,== etc. Operators have different implementation according to requirement.

As you know that operator can be used in mathematical expressions:


int i = j + 18; float x = y*1.5;

Now it would be great if we could use such kind of operations with Objects. For example, If should be able to join or concatenate two Strings by using + operator. Is it possible? Yes you can! That's what Operator Overloading for.


String first_name = "Amitabh";
String last_name = "Bachchan";

Now if we want to concatenate both String into one. C++ should allow to do it. like :

String full_name = first_name+last_name;

Its absolutely fine. It can be done successfully.

But, What about user-defined classes? Can this concept is applicable to them also?

Let us take two user-defined date objects;

Class Time {
int hours;
int minutes;
int seconds;
}
. . . .
. . . .
Create objects of class Time :-
{
. . . .
Time time1, time2;
Time time3 = time1 + time2; //(Its 100% valid.)
time3++; // (this too...)
. . . .
. . . .
}
So, we can say that objective of Operator overloading is to provide experience of primitive data type with user defined datatype. Like this :

Primitive Data type User Defined Data type
int num1,num2;Time time1,time2;
int num3=num1+num2; Time time3=time1+time2;
num3++;time3++;



Some Points to REMEMBER : -

  • New operators can not be created. Functionality of built-in operators can be modified.
  • Not all the operators can be overloaded.There are few which can not be overloaded.


In C++, about 40 predefined operators can be overloaded. The operator which can not be overloaded are as follows :

::, . , .*, sizeof , ?:

We can not overload preprocessing symbols like # and ###.

To be continued.....

Sunday, November 30, 2008

Function Overloading 2

How to call Overloaded Functions

printMe(108);
printMe(3.14F);
printMe(420.12009);
printMe(‘k’);

Note : suffix F or f has to be used with float without F or f it will be treated as double

Function Overloading and Ambiguity

If compiler is not able to choose between two or more overloaded function , it leads to ambiguity. Ambiguous statements are errors and programs containing ambiguity will not compile.
Main cause of ambiguity is C++’s automatic type conversions.
C++ automatically attempts to convert the arguments used to call a function into the type of arguments expected by the function.

For example:
Suppose if function declration is
int showMe(double d);

and if we call it like

showMe(‘x’); // not an error , conversion occurred

So above statement will not show any error because C++ automatically converts the character ‘x’ into its double equivalent.

Now consider this program.




#include

float exposeMe(float f);
double exposeMe(double d);

main()
{
cout<<”Secret no : “<<exposeMe(42.4); // not ambiguous, calls exposeMe( double) : 1
cout<<”\nAnother Secret number : “<< exposeMe(100); // : 2
return 0;

}

float exposeMe(float f)
{
return f;

}

double exposeMe(double d)
{
return d;
}

Here, exposeMe() is overloaded it can accept either float or double type data. In 1 exposeMe(double) is called, because all floating point constants in C++ are automatically of type double if suffix f or F is not there. Hence this call is not ambiguous. However function 2 exposeMe(100) is called , it leads to ambiguity because compiler has no way to know whether it should be converted to a float or to a double. This causes an error message to be displayed , and the program will not compile.

Another example of ambiguity



#include

float exposeMe(unsigned char c);
double exposeMe(char c);

main()
{
cout<<”Reveled Character is : “<<exposeMe(‘x’);
cout<<”\nAnother Reveled Character is : “<< exposeMe(999); // : 2
return 0;

}

float exposeMe(unsigned char c)
{
return c - 1;

}

double exposeMe(char c)
{
return c + 1;
}

In C++, unsigned char and char are not inherently ambiguous. However, when exposeMe(99) is called the compiler has no way to know which function to call. That is, whether 99 should be converted into a char or an unsigned char?



To be continued….

Function Overloading

‘Overloading’ means a thing is having one name but distinct meanings. C++ supports two types of overloading
1. Function Overloading
2. Operator Overloading

Function overloading means one function name can have different meanings. And it can perform distinct tasks. But now the question is, how it can be done ?
It is done very intelligently, just providing different argument lists which is also known as function signature. The overloaded function is selected on the basis of following criteria –
Number of arguments
Type of arguments
Order of arguments

Important : - return type of function doesn’t take participate in overloading.

This information is available to compiler at compile-time itself , hence called early binding or static binding or static linking. It is also known as Compile-time polymorphism.


For example :
A. float sum ( int a, int b)
B. float sum (float a, float b)
C. float sum (float a, float b, float c)

That is , in A sum() is taking two int arguments , in B sum is taking two float arguments while in C sum() is taking three float arguments.

Declaration and Definition

void printMe(int a)
void printMe(float f)
void printMe(double d)
void printMe(char c)

After declaration of overloading functions, we have to define them in following manner.

void printMe(int a)
{
cout<<”I am “<<a<<endl;

}

void printMe(double d)
{
Cout<<”I am “<<d<<endl;
}

void printMe(char c)
{
Cout<<”I am “<<c<<endl;
}

Now you can understand how easy to work with overloading functions.

Wednesday, October 22, 2008

Console I/O Streams

There are three types of Console I/O Stream-

cout - Standard Output Stream
cin - Standard Input Stream
cerr - Standard Error Output Stream


cout :

It is used to display data on console.
Example :
cout<<"Sachin is a greatest Cricket Player"
cout<<234;
In general form :
cout< here expression can be any valid C++ expression

cin :

It is used to capture data from keyword.
Example :
int age;
cin>>age;
The general form :
cin>>variable;

cerr :

It is used to display errors on console.

C++ Keywords

Keywords are predefined reserved words (identifiers).They have special meanings. They cannot be used as identifiers in your program. The following keywords are reserved for C++.

* asm
* auto
* break
* case
* catch
* char
* class
* const
* continue
* default
* delete
* do
* double
* else
* enum
* explicit
* extern
* float
* for
* friend
* goto
* if
* inline
* int
* long
* mutable
* namespace
* new
* operator
* private
* protected
* public
* register
* return
* short
* signed
* sizeof
* static
* struct
* switch
* template
* this
* throw
* try
* typedef
* union
* unsigned
* using
* virtual
* void
* volatile
* while

Friday, October 17, 2008

My First Program

Now we will see how to write a program in C++. The idea of this program is to introduce you to the overall structure of a C++ program.

//My first program

#include<iostream.h>
int main()
{
//Print text message on console

cout<<"Hello Universe.. Give me Red ";

return 0;
}

Now after writing program in a text file(Source file) , save text file by name first.c

Note:

C++ source files conventionally use one of the suffixes .C, .cc, .cpp, .CPP, .c++, .cp, or .cxx;

if you are using GNU Compiler, you can give following command to compile first.c

g++ first.c

To run
a.out

Output will be:
Hello Universe.. Give me Red


Example 2:

#include<iostream.h>
int main()
{
//Print multiple text messages on console

cout<<"Hello Universe.. Give me Red "<<endl;
cout<<"Congrats! Sachin ...";

return 0;
}

Thursday, October 16, 2008

Constructors & Destructors in C++

Constructor
Definition :
Constructor is a special member function with the same name as its class.

Example:
class Person
{

public:
Person(); // constructor for class Person
};

Use:
Constructors are used to create, and can initialize, objects of their class type.

Call:
When an object of a class is created, constructor for that class is called.

If there is no constructor defined, DEFAULT constructor is invoked.
But default constructor doesn't initialize.

Some facts about Constructors :
  • Constructors are special member functions with the same name as the class.
  • Constructors can not return any value (nothing even void) .
  • Constructors are intended to initialize the members of the class when an instance of that class is created.
  • Constructors are not called directly.
  • Constructors can not be virtual.
  • Constructors can not be static.
  • Constructors can not be const, volatile, or const volatile.
  • Constructors aren't automatically inherited between base and derived classes.
  • There can be any number of constructors in a same class. They must have different parameters to distinguish them. (=> Constructors can be overloaded )
Destructors
Definition :

Destructors in C++ also have the same name, but they are preceded by a '~' operator.

Example :
class Person {
public:
// Constructor for class Person
Person();
// Destructor for class Person
~Person();
};

Use :

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed.

Call:

The destructors are called when the object of a class goes out of scope or is explicitly deleted.

Some facts about Destructors:
  • If the constructor/destructor is declared as private, then the class cannot be instantiated. (why? Think about it.)
  • It is not necessary to declare a constructor or a destructor inside a class. If not declared, the compiler will automatically create a default one for each.
  • A destructor takes no arguments and has no return type.
  • Its address cannot be taken.
  • Destructors cannot be declared const, volatile, const volatile or static.
  • A destructor can be declared virtual or pure virtual.

Friday, September 19, 2008

Inheritance in C++

Inheritance

It is a mechanism to reuse and extend existing classes.

Creating and deriving a class from existing class is also known as inheritance in C++.

New Created class is called
Derived Class and extended class (old class) is called Base class.

Derived class can have all the features of base class and we can add new features to derived class.

Adding new features in base class to make derived class is called extension of base class.

In general we can formulate it-

Base Class + New features = Derived Class

Example :
We can create a base class named fruit and define derived classes as , mango, apple, banana Each of these derived classes has all the features of the base class (fruit) with extra attributes or features specific to these derived classes. Mango would have its own defined features, apple would have its own defined features, banana would have its own defined features, etc.

C++ inheritance is similar to a parent-child relationship. According to inheritance concept, When a class is inherited all the functions and data member are inherited. In C++, every thing from the base class can not be inherited. Yes! we are talking about some exceptional cases. Just have a look-

We can't inherit->
  • The constructor and destructor of a base class
  • The assignment operator
  • The friend functions and friend classes of the base class
(Don't worry .. Very soon we will learn about friends..
Yes friends are also there in C++. They will become your fast friend in certain cases.)

Saturday, May 12, 2007

What is Object?



Object is like a variable
as we create with built-in datatypes. Object is an instance of class.
Object has state,behavior and identity.

state - value of data member at any point of time
behaviour - how object performing a task, it comes from definition of member functions.
identity - name of object.

How to create Object?

Syntax:
class-name object-name;
or
class-name object-name1,object-name2,....;

Suppose we have to create object(s) of class Circle :

Circle c; //One object created
or
Circle c1,c2; //Two objects created

How to call a member function?

Syntax :
object-name.member-function-name();

for example we want to set radius of object c , we have to call a member function SetRadius(int) :
->
c.SetRadius(12);
in same way
int area = c.GetArea();

and so on....

Class Members :
Data Member
Member Function
Members must be declared/defined within class definition.
A member can not be declared twice in the class definition.

Now let's assemble all the pieces together to make it meaningful..

//class definition
class A
{
//data member
int i;
int j;

//member function
int getI() //definition of member function
{
return i;
}
void setI(int a) //definition of member function
{
i = a;
}
};
int main()
{

A aObj; //Creation of object
aObj.setI(20); //calling member function
cout<&ltaObj.getI(); //calling member function
}

Please visit us again .Updation is ongoing process here...Thanks

Friday, May 11, 2007

Class & Objects


Class:
It is a basic block of Object Oriented Software.
Class is like a data type as struct in C. A datatype contains data and operations applicable to that data. We can take example of int data type, it contains data as well as operations like a+b , a-b , a*b etc.

In other words, class is a blueprint for objects. class decides what object can have and what task it can perform.

Now we will see, how class concept can be implemented through C++ -

General Form of Class

class
{
data member;

member functions;

};
// ; is must here

Example :

class Circle
{
int radius;

int GetRadius();
void SetRadius(int);
int CalculateArea(int);
};
:

In above example , we have seen how a class look like .
As we know by default, all members of class have private access-specifier. So in above class Circle, all the members will be private,means they can not be accessed from outside the class.Before discussing further, first we have a idea regarding Access Specifier :-

Access-Specifier : also known as visibility labels.
There are three types of Access specifiers

private : private members can be accessed only within the class itself.
public : public members can be accessed from outside the class also.In this case, member is fully exposed to outside-world.
protected : can be access from derived class only.(We will discuss this in detail during inheritance topic)

Now again we take above example. none of the member can be accessed from outside of the class, now to make some member accessible from outside we make one little but very important modification -


class Circle
{
int radius;

public:
int GetRadius();
void SetRadius(int);
int CalculateArea(int);
};
:

Now, to use this definition of class , Let's understand What is Object?

Saturday, May 5, 2007

C++ Structure vs C++ Class

C++ programming language provides structure and class to create problem-oriented datatypes.Instance of these datatypes are known as objects.

C++ Structure and C++ class are exactly same except default access specifier of their members i.e. in C++ Structure all members are public by default while in Class all are private.

For example in following code , the class C is equivalent to structure S

class C
{
//default access specifier is private
int num;

public:
void setNum(int n)
{
Num = n;
}
}

struct S
{
//default access specifier is public
void setNum(int n)
{
Num = n;
}

private:
int num;
}

Hence we can see here that the difference in both is only access specifier, but as security is concern, this is a big drawback of structure.Because by default all the members are exposed to outside world. That is the one main reason, why programmers are hesitant to use structure.In turn, class encourages encapsulation/data-hiding by default.So my recommendation is use class, forget structure.

Thursday, May 3, 2007

C Structure vs C++ Structure

C Structure contains only data items while C++ structure contains data as well as function.

In C to create structure variable you have to use 'struct' keyword for example
struct Person p;

But in C++ 0nly Structure name is used just like built-in datatype. for example
Person p;

Example :

C Structure :
struct Person
{
int pid;
char name[25];
....
}
Declaration of a variable
struct Person p;

C++ Structure :

struct Person
{
int pid;
char name[25];
....
void enterDetails()
{
...
}
..
}

Declaration of a variable:
Person p;

Wednesday, May 2, 2007

Basic Features

Stream : It is a flow of data to and fro.
Standard Input Stream
Used to read data form Standard Input device i.e. keyboard ,it can take input from a file stored at hard disk and from other input devices also.
'cin' represents the Standard Input Stream.
Standard Output Stream
Used to send output to Standard Output Device i.e. Monitor, it can send output to file on hard-disk,printer etc.
'cout' represents the Standard Output Stream.
Standard Error Stream
Another output stream used by programs to output error messages.
'cerr' represents the Standard Error Stream.

The iostream is an object-oriented library that contains input and output streams.

C++ provide two ways to work with streams :
low-level
high-level
Very soon we will get detailed description of this topic...

C++ Comments
Single line comment
// single line statement here
Multiline Comment
/*
Some lines here
*/

References

C++ references are to create alternative name or alias name for the already defined variable.
for example :
int i = 18;
int &ref = i;
here ref is reference to integer variable i. it can be used in place of i.
->& is not address operator here, it is reference operator.<- REMEMBER :

* No memory is allocated for reference variables as they are alias name for simple variables.
* Reference variables should be initialized.

Main Use :
* as a formal argument to a function.
Example :
--------------------------------------
#include
using namespace std;
int Square(int &Val);
int main()
{
int Number=10;
Square(Number);
cout<<"Number is "<<>Pointer Reference:
It is Alias name to the pointer.

Example:
int ival = 100;
int *ptr = &ival;
int * &refptr = ptr;

Scope Resolution Operator :
In C a local variable has precedence over global variable with the same name.
In C++, global variable can be accessed through Scope Resolution Operator :: ,with local variable.
Example:

int i = 4;
int main()
{
int i = 9;
cout<< ::i<< endl; //Prints global variable i 4
cout<< i; //Prints local variable i 9
}
}

Monday, April 30, 2007

Features Of C++

Following are the various features of C++ :
Streams for I/O
Comments
Function Prototypes
Default Function Arguments
Variables
Scope Resolution Operator
The Const qualifier
Enumeration
Inline Function
References
Overloaded functions
Class
Object
Access Specifiers

and many more.....

C vs C++

What C++ is having C not :

References
boolean type
Inline substitution
Default function arrays
Free Store Management Operators i.e. new and delete
Function Overloading
Operator Overloading
RTTI (Run Time Type Information)
Namespaces
Eclipses
default arguments
I/O i.e. cin & cout

What is Object Oriented Programming(OOP) ?

As its name indicates , it is a technique which is organised around object.Hence object is CYNOSURE here.Here main focus point is data. Functions are secondary. In very simple terms, functions are data oriented , means in what way data is going to be used in program that is described in function. so data and functions are tied together to make "Object".

Features of OOPs:

Abstraction
Encapsulation
Inheritance
Polymorphism

Abstraction:
Abstraction is the process of hiding the details and exposing only the essential features of a object according to the context or problem domain.

IEEE Definition :
"A view of a problem that extracts the essential information
relevant to a particular purpose and ignores the remainder of
the information."

-- [IEEE, 1983]


Encapsulation:
Encapsulation is the ability to bundle related data and functionality within a single, autonomous entity called a class.

Inheritance:
Inheritance is a mechanism to create new classes through already existing classes.

Polymorphism:
Poly means "many" morphism means "forms" hence verbal meaning is many forms. It is a way in which one name can provide different functionalities.
-> the ability to provide the same interface to objects with differing implementations.

What is C++ ?


Welcome to C++ Learning Sessions..

C++ is very entertaining and one of the most used programming language. I hope you will enjoy learning this beautiful programming language.
ALL THE BEST.


C++ Fact File


C++ is a Object Oriented Programming Language, developed by Bjarne Stroustrup in 1983 at Bell lab.

It is a powerful general purpose language which contains almost all the features of C including low level features like memory management,pointers etc.

One major advantage over C is object oriented features of C++. From small-scale to large-scale application can be created in C++.

It also supports other programming approaches like Procedural,Object-based programming, Generic programming, and Functional programming.

Originally it was named as "C with Classes".

C++ is also considered as Superset of C.

C++ is having a special concept called "operator overloading". This concept is not present in the earlier OOP languages and it makes the creation of libraries much cleaner and easy.