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.)