Tuesday, April 28, 2009

Overloading Unary Operator using - Operator

A minus operator, when used as a unary, takes just one operator. We know that this operator used to subtract two values. Consider the program we can subtract two values separately using ‘-’ operator

Example

header files

class minus
{
int a,b,c;
public:
void get();
{
a=10;
b=-20;
z=30;
}
void operator-()
{
a=-a;
b=-b;
c=-c;
}

void display()
{
cout<<"A=" << a <<"\n";
cout<<"B=" << b <<"\n";
cout<<"C=" << c <<"\n";
}
};

void main()
{
clrscr();
minus obj;
obj.get();
obj.display();
-obj;
obj.display();
getch();
}

Output will be

A=-10
B=20
Z=-30

Overloading Unary Operator Using + Operator

A plus operator, when used as a unary, takes just one operator. We know that this operator used to add two values. Consider the program we can add hrs and minutes separately using ‘+’ operator.

Example:

header files

class time
{
int hrs, min;
public:
void get(int a,int b)
{
hrs=a;
min=b;
}
time operator +(time ob);
void disp();
void display();
};
time time::operator +(time ob)
{
time t;
t.hrs=hrs+ob.hrs;
t.min=min+ob.min;
return(t);
}
void time::disp()
{
cout<<"\n" <<"Hours=" << hrs <<" " <<"Minutes=" << min << endl;
}
void display()
{
int n1, m;
m=min/60%;
n1=m/60;
hrs=hrs+n1;
cout<<"\n" << hrs <<"hrs" << m <<"mins" << endl;
}
void main()
{
clrscr();
time obj1, obj2, obj3,;
obj1.get(5,0);
obj2.et(7,45);
obj3=obj1+obj2;
obj1.disp();
obj2.disp();
obj3.display();
getch();
}

Output will be

12 hrs 45 mins

Monday, April 27, 2009

INHERITANCE

Introduction:
Inheritance is a process of deriving new classes from existing classes. The derived classes contain all attributes and functions of existing classes and its own attributes and functions. The existing classes are called base classes and the inherited classes are called derived classes. For eg.:


Here Academic is a derived class of Students which is derived from the base class College. So it contains all the attributes and functions of Students and College plus its own attributes and functions.
Salary is a derived class of Staffs which is derived from the base class College. So it contains all the attributes and functions of Staffs and College plus its own attributes and functions
Wages is a derived class of Workers which is derived from the base class College. So it contains all the attributes and functions of Workers and College plus its own attributes and functions

Inheritance is the process of creating new classes from the existing classes. The new classes are called derived classes. The existing classes are called base classes.


Type of Inheritance and Syntax

Type of Inheritance

Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance


Syntax:

Class derivedclassname : mode baseclassname
{
New member variable declaration
- - - - -
New member function declaration (or) definition
}

Base and Derived Classes


Base and Derived Classes

Single Inheritance


Single Inheritance
Deriving a new derived class from single base class is called single inheritance

Class B is derived from single base class A, here Class A is called base class and Class B is called derived class. Using Derived class object, we can access the members of both derived and bases class. But using Base class object we can not access members of derived class.

Example:
header files
class student
{
int rno;
char name[50];
char address[30];
public:
void get();
void display();
};
void student::get()
{
cout<<”Enter the Student Roll Number:”;
cin>> rno;
cout<<”Enter the student Name :”;
cin>> name;
cout<<”Enter the Student Address:”;
cin>> address;
}
void student::display()
{
cout<<”Roll No.: “<<>
cout<<”Name : “<<>
cout<<”Address :”<<>
}
class mark:public student
{
int mark1, mark2, mark3, mark4, mark5;
float avg;
public:
void getmark();
void displaymark();
};
void mark::getmark()
{
cout<<”Enter the five subject Marks one by one”<<”\n”;
cin>> mark1>> mark2>> mark3>> mark4>> mark5;
total=mark1+ mark2+ mark3+ mark4+ mark;
avg=total/5;
}
void mark::displaymarks()
{
cout<< mark1<< endl;
cout<< mark1<< endl;
cout<< mark2<< endl;
cout<< mark3<< endl;
cout<< mark4<< endl;
cout<< mark5<< endl;
cout<<“Total =“<< total<< endl;
cout<<“Average =“<
}
void main()
{
clrscr();
mark obj1;
obj1.get();
obj1.getmark();
obj1.diaplay();
obj1.displaymark();
getch();
}
Output will be
Enter the Student Roll Number: 101
Enter the student Name: Lak
Enter the Student Address: Chennai
Enter the five subject Marks one by one
80
75
80
90
100

80
75
80
90
100
Total = 425
Average = 85

Multiple Inheritance



Multiple Inheritance
Deriving a new derived class from more then one base class is called multiple inheritance

Class C is derived from two base classes A and B, here class A and Class B is called base class and class C is called derived class. Using derived class object, we can access the members of both derived and base classes. But using Base class object we can not access members of derived class.

Example:
header files
class student
{
int rno;
char name[50];
char address[30];
public:
void get();
void display();
};
void student::get()
{
cout<<”Enter the Student Roll Number:”;
cin>> rno;
cout<<”Enter the student Name :”;
cin>> name;
cout<<”Enter the Student Address:”;
cin>> address;
}
void student::display()
{
cout<<”Roll No.: “<<>
cout<<”Name : “<<>
cout<<"Address :”<<>
}
class mark
{
int mark1, mark2, mark3, mark4, mark5;
float avg;
public:
void getmark();
void displaymark();
};
void mark::getmark()
{
cout<<”Enter the five subject Marks one by one”<<”\n”; cin>>mark1>>mark2>>mark3>>mark4>>mark5;
total=mark1+ mark2+ mark3+ mark4+ mark;
avg=total/5;
}
void mark::displaymarks()
{
cout<<>
cout<<>
cout<<>
cout<<>
cout<<>
cout<<>
cout<<“Total =“<<>
cout<<“Average =“<<>
}
class result:public student, public mark
{
public:
void check();
};
void result::check()
{
if(avg>=90)
{
cout<”Distinction”;
}
else if(avg<=80 && avg>=60)
{
cout<<”I Class”;
}
else if(avg<60>=40)
{
cout<<”II Class”;
}
else cout<<”Fail”;
}
void main()
{
clrscr();
result obj1;
obj1.get();
obj1.getmark();
obj1.diaplay();
obj1.displaymark();
obj1.check();
getch();
}
Output will be
Enter the Student Roll Number: 101
Enter the student Name: Lak
Enter the Student Address: Chennai
Enter the five subject Marks one by one
80
75
80
90
100
Total = 425
Average = 85
I Class

Multilevel Inheritance


Multilevel Inheritance
A new class is derived from another derived class is called multilevel inheritance


Class C is derived from class B, and Class B is derived from class A, here Class B is called derived as well as base class for class C it is base class, for class A it is derived class. Class C is called derived class. Using derived class object, we ca access the members of both base derived and two base classes. But using Base class object we can’t access members of derived class.

Example:
Header files
class student
{
int rno;
char name[50];
char address[30];
public:
void get();
void display();
};
void student::get()
{
cout<<”Enter the Student Roll Number:”;
cin>>rno;
cout<<”Enter the student Name :”;
cin>>name;
cout<<”Enter the Student Address:”;
cin>>address;
}
void student::display()
{
cout<<”Roll No.: “<cout<<”Name : “<cout<
}
class mark:public student
{
int mark1, mark2, mark3, mark4, mark5;
float avg;
public:
void getmark();
void displaymark();
};
void mark::getmark()
{
cout<<”Enter the five subject Marks one by one”<<”\n”;
cin>>mark1>>mark2>>mark3>>mark4>>mark5;
total=mark1+ mark2+ mark3+ mark4+ mark;
avg=total/5;
}
void mark::displaymarks()
{
cout< cout< cout< cout< cout< cout< cout<<“Total =“< cout<<“Average =“<}
class result:public mark
{
public:
void check();
};
void result::check()
{
if(avg>=90)
{
cout<”Distinction”;
}
else if(avg<=80 && avg>=60)
{
cout<<”I Class”;
}
else if(avg<60>=40)
{
cout<<”II Class”;
}
else
cout<<”Fail”;
}
void main()
{
clrscr();
result obj1;
obj1.get();
obj1.getmark();
obj1.diaplay();
obj1.displaymark();
obj1.check();
getch();
}

Output will be

Enter the Student Roll Number: 101
Enter the student Name: Lak
Enter the Student Address: Chennai
Enter the five subject Marks one by one
80
75
80
90
100
80
75
80
90
100
Total = 425
Average = 85
I Class

Hierarchical Inheritance


Hierarchical Inheritance
Deriving more then one derived class using single base is called hierarchical Inheritance.


Class B and Class C is derived from Class A. here Class B and Class C is called derived class and Class A is called base class. Using base class object we can’t access derived class members. Using derived class object we can access base class object.


Example:
Header files
class student
{
int rno;
char name[50];
char address[30];
public:
void get();
void display();
};
void student::get()
{
cout<<”Enter the Student Roll Number:”; cin>> rno;
cout<<”Enter the student Name :”; cin>> name;
cout<<”Enter the Student Address:”; cin>> address;
}
void student::display()
{
cout<<”Roll No.: “<< class="">>mark1>>mark2>>mark3>>mark4>>mark5;
total=mark1+ mark2+ mark3+ mark4+ mark;
avg=total/5;
}
void mark::displaymarks()
{
cout<=90)
{
cout<”Distinction”; } else if(avg<=80 && avg>=60)
{
cout<<”I Class”; } else if(avg<60>=40)
{
cout<<”II Class”; } else cout<<”Fail”; } void main() { clrscr(); result obj1; obj1.get(); obj1.getmark(); obj1.diaplay(); obj1.displaymark(); obj1.check(); getch();
}
Output will be
Enter the Student Roll Number: 101
Enter the student Name: Lak
Enter the Student Address: Chennai
Enter the five subject Marks one by one
80
75
80
90
100
80
75
80
90
100
Total = 425
Average = 85
I Class

Hybrid Inheritance


Hybrid Inheritance
Combination of hierarchical and multiple inheritance is called hybrid inheritance.

In this lass D is derived from class B and Class C, Using class D object we can access all the members (A,B,C). But when we accessing Class A members we have two ways in this case we have an ambiguity, i.e. in which way we are getting the properties of class A, so here we implementing virtual keyword to avoid the ambiguity.

Example:
#include <>
#include <>
class student
{
int rno;
char name[50];
char address[30];
public:
void get();
void display();
};
void student::get()
{
cout<<”Enter the Student Roll Number:”; cin>> rno;
cout<<”Enter the student Name :”; cin>> name;
cout<<”Enter the Student Address:”; cin>> address;
}
void student::display()
{
cout<<”Roll No.: “<<>class mark:virtual public student
{
int mark1, mark2, mark3, mark4, mark5;
float avg;
public:
void getmark();
void displaymark();
};
void mark::getmark()
{
cout<<”Enter the five subject Marks one by one”<<”\n”; cin>>mark1>>mark2>>mark3>>mark4>>mark5;
total=mark1+ mark2+ mark3+ mark4+ mark;
avg=total/5;
}
void mark::displaymarks()
{
cout<< total ="“<<" average ="“<<">class sports : public virtual student
{
Int points;
Public:
Void getsp();
Void displaysp();
};
Void sports::getsp()
{
Cout<<”Enter the Sports Points”; Cin>> points;
}
Void sports::displaysp()
{
Cout<<>class result: public mark, public sports
{
public:
void check();
};
void result::check()
{
if(avg > =90)
{
cout<”Distinction”; } else if(avg< =80 && avg> =60)
{
cout<<”I Class”; } else if(avg<> =40)
{
cout<<”II Class”; } else cout<<”Fail”; } void main() { clrscr(); result obj1; obj1.get(); obj1.getmark(); obj1.diaplay(); obj1.displaymark(); obj1.check(); obj1.displaysp(); getch(); } Output will be Enter the Student Roll Number: 101 Enter the student Name: Lak Enter the Student Address: Chennai Enter the five subject Marks one by one 80 75 80 90 100 Enter the Sports Points: 60 80 75 80 90 100 Total = 425 Average = 85 I Class 60

Friday, April 24, 2009

FILES

Introduction to Files


A file is a collection of related information, that is permanently stored on the disk and allows us to access and alter that information, whenever necessary.

A program typically involves either or both of the following kinds of data communication:
1. Data transfer between console unit and the program
2. Data transfer between the program and a disk file.


In I/O system of C++ handles file operations which are very much similar to the console input and output operations. It uses the streams as an interface between the programs and the files.

The stream that supplies data to the program is known as input stream and the one that receives data from the program is known as output stream. In other words, the input stream extracts data from the file and the output stream inserts data to the file.

Class for file stream operations

Class for file stream operations

The I/O system of C++ contains a set of classes that define the file handling methods. These include
ifstream
ofstream
fstream.

The above classes are derived from fstreambase and from the corresponding iostream.h.
Details of file stream classes are:
filebuf
fstreambase
ifstream
ofstream
fstream

filebuf
Its purpose is to set the file buffers to read and write. Contains openprot constant used in the open() of file stream classes. Also contains close() and open() as members.

fstreambase
Provides operations common to the file streams. Serves as a base for fstream, if stream and ofstream classes. Contains open() and close() function.

ifstream
Porvides input operations. Contains open() with default input mode. Inherits the functions
get()
getline()
read()
seekg() and
tellg() functions from istream.

ofstream
Provides output operations. Contains open() with default input mode. Inherits the functions
pet()
write()
seekp() and
tellp() function from ostream.

fstream
Provide support for simultaneous input and output operations. Contains open() with default input mode. Inherits all the functions from istream and ostream classes through iostream.

Opening and Closing a file


We can perform the following basic operations of files.
Naming a file
Opening a file
Reading data from a file
Writing data to a file
Closing a file

The filename is a string of characters that make up a valid file name for the operating system. It may contain two parts, a primary name and an optional period with extension
Example:

sample.doc

Opening a file using constructor
Opening files using open()

Opening a file using constructor

Opening a file using constructor
This involves two steps
1. Create file stream subject to manage the stream using the appropriate class. That is the class ofstream is used to create the output stream and the class ifstream to create the input stream.
2. Initialize the file object with the desired filename.

Syntax:
Ofstream object(file_name);

Example:
Ofstream obj(“sample.doc”)

This creates obj1 as an ofstream that manages the output stream.
#include stream.h
#include string.h

Void main()
{
char str[]=”ssi computer center”;
ofstream outfile(“sample.doc”);
for(int j=0;j<>Syntax:
Ifstream object (file_name);

Example:

Ifstream obj(“sample.doc”)

This creates obj1 as an ifstream that manages the input stream.

#include fstream.h
void main()
{
char ch;
ifstream in(“sample.txt”);
while(!in.eof())
{
in.get(ch);
cout<< ch; } }

#include fstream.h
void main()
{
const int MAX=80;
char buffer[MAX];
ifstream infile(“sample.txt”);
while(!infile.eof())
{
infile.getline(buffer, MAX);
cout<< buffer;
}
}

Opening files using open()

Opening files using open()
The function open() can be used to open multiple files that use the same stream object.
Syntax:
File_stream object streamobject;
Stream_object. Open(“file_name”);


Example:


Ofstream obj1;
Obj1. open(“employee”);

#include<>
#include<>
#include<>
main()
{
char string[120];
clrscr();
cout<<”Enter an string”;
cin>> string;
int len=strlen(string);
cout<< len<<”\n”;
fstream file;
file.open(“samp.txt”,ios::in ios::out);
for(int i=0;i< len;i++)
{
file.put(string[i]);
}
file.seekg(0);
char ch[90];
for(i=0;i< len;i++)
{
file.get(ch[i]);
cout<< ch[i];
}
file.close();
getch();
}

Closing a file

Closing a file

All the file must be closed after the file operations. The file can be closed using the following syntax.

Syntax:

object.close();
ex.obj.close();

End of file

Detecting of the end of file condition is necessary for preventing any further attempt to read data from the file. This can done using the following statement
while(great)

An ifstream object, such as great, returns a value of 0 if any error occurs in the file operations including the end of file condition. Thus, the while loop terminates when great returns a value of zero on reaching the end of file condition

File Modes

File Modes
We can use two arguments in the open() function, first argument is filename and the second argument is mode. The general form of the function open() with two arguments is
stream-object.open(“file_name”,mode);
here
File name
is sequence of string
Mode specifies the purpose for which the file is opened.

File Modes parameters
ios::app : Append to end of file
ios::ate: go to end of file on opening
ios::binary : Binary file
ios::in: Open file for reading only
ios:: nocreate: open fails if the file does not exists
ios::out: open fails if the file already exists
ios::out open file for writing only
ios::trunk: Delete contents of the file if it exists

Example:

#include<>
#include<>
void main()
{
char name[25],des[50];
int empcode;
clrscr();
ofstream f;
f.open(vvp.txt",ios::app);
cout<<"Enter Employee Name"; cin>> name;
f<<>> des;
f<<>> empcode;
f<<>> name;
fo>> des;
fo>> empcode;
cout>> name >> endl;
cout>> des >> endl;
cout>> empcode >> endl;
fo.close();
getch();
}

Monday, April 20, 2009

TEMPLATE

Introduction

We can define templates for both classes and functions. A template can be used to create a family of classes or functions. For example, a class template for an array class would enable us to create arrays of various data types such as linearly and float array. Similarly, we can define a template for a function, say mul(). That would help us create various versions of mul() for multiplying int, float and double type values.
A template can be considered as a king of macro. When an object of a specific type is defined for actual use, the template definition for that class is substituted with the required data type. Since a template is defined with a parameter that would be replaced by the specified data type at the time of actual use of the class or function, the templates are sometimes called parameterized classes or function.
Click here

Class Template

Consider a vector class defined as follows:
Now suppose we want to define a vector that can store angry of float values. We van do this by simply replacing the appropriate int declaration with float in the vector class. This means that we have to redefine the entire class all over again.
Assume that we want to define a vector class with the data type as a parameter and then use this class to create a vector of any data type instead of defining a new class every time. The template mechanism enables us to achieve this goal.
As mentioned earlier, templates allow us to define generic classes. It is a simple process to create a generic class suing a template with an anonymous type. The general format of a class template is:

Template <>
Class clase_name
{
// Class member specification
// With anonymous type T
// Wherever appropriate


};

The template definition of vector class shown below illustrates the syntax of a template:
Note that the class template definition is very similar to an ordinary class definition except the prefix template <> and the use of type T. This prefix tells the compiler that we are going to declare a template and use as a type name in the declaration. Thus, vector has become a parameterized class with the type T as its parameter. T may be substituted by any data type including the user-defined types now, we can curare vectors for holding different data types.

Example:

Vector <> v1 (10); // element int vector
Vector <> v3(25); 25 element float vector
Note that the type T may represent a class name as well.

Example:
Vector <> v3(5); // vector if 5 complex numbers

A class created from a class template is called a template class. The syntax for defining an object of a template classis:
Class_name <> object_name (arg list);
This process of creating a specific class form a class template is called instantiation. The compiler will perform the error analysis only when an instantiation takes place. It is, therefore, advisable to create and debug an ordinary class before converting it into a template.

Friday, April 17, 2009

Function Templates

Function Templates
Like class templates, we can also define function templates that could be used to create a family of functions with different argument types. The general format of a function template is:
Syntax:

Template <>
returntype functionname( argument of type T)
{

Body of function with type T wherever appropriate

}
The function template syntax is similar to that of the class template except that we are defining functions instead of classes. We must use the template parameter T as and when necessary in the function body and in its argument list.
The following example declares a swap() function template that will swap two values of a given type of data.
Example:
template <>
void swap (T&a, T&b)
{
T temp = a;
a = b;
b= temp
}

This essentially declares a set of overloaded functions, one for each type of data. We can invoke the swap() function like any ordinary function. For example, we can apply the swap() function as follows:

void f(int m, int n, float a, float b)
{
swap(m,n); // swap two integer values
swap(a,b); // swap two float values
}
This will generate a swap() function from the function template for each set of argument types. Another function often used is sort() for sorting arrays of various types such as int and double. The following example shows a function template for bubble sort:

Member function Templates

When we created a class template for vector, all the member functions were defined as inline which was not necessary. We could have defined them outside the class as well. But remember that the member functions of the template classes themselves are parameterized by the type argument (to their template classes) and therefore these functions must be defined by the function templates. It takes the following general form:

Template <>
Returntype classname <> function_name(arg list)
{
Body of the function
}


Template Arguments

A template can have multiple arguments. That is, in addition to the type argument t, we can also use other arguments such as strings, function names, constant expressions and built-in types. Consider the following example:

Template <>
class array
{
T n[size]; // automatic array initialization
};

This template supplies the size of the array as an argument. This implies that the size of the array is known to the compiler at the compile time itself. The arguments must be specified whenever a template class.

Example:

array<> n1; // array of 10 integers
array<> n2; // array of 15 floats
array<> n3; // string of size 30

The size is given as an argument to the template class. Compare this with the creation of the template class vector where the size is given as an argument to the object.

Example:

#include<>
#include<>
Void swap(int x, int y)
{
Int t;
T=x;

X=y;
Y=t;
Cout<< x << y;
}
Void main()

{
Clrscr();
Swap(15,20);
Swap(33.05,85.66);
Swap(“hello”, “world”);
}


EXCEPTION HANDLING

Exception handling is the latest feature adder to ANSI C++, Exceptions refer to unusual conditions in a program. They could errors that cause the program to fail or certain conditions that lead to errors. When a program encounters an exceptional condition, it is important that it is dealt with.
Exceptions are of two kinds, namely, synchronous exceptions. Errors such as “out-of-range index” and “over-flow” belong to the synchronous type exceptions. The errors that are caused by events beyond the control of the program (such as keyboard interrupts) are called asynchronous exceptions. The proposed exception handling mechanism in C++ is designed to handle only synchronous exceptions.
The purpose of the exception handling mechanism is to provide means to detect and report an “exceptional circumstance” so that appropriate action can be taken. The mechanism suggests a separate error handling code that performs the following tasks:

1. Find the problem (Hit the exception).
2. Inform that an error has occurred (Throw the exception).
3. Receive the error information ( Catch the exception).
4. Take corrective actions (Handle the exception).


The error handling code basically consists of two segments, one to detect errors and to throw exceptions and the other to catch the exceptions and to take appropriate actions.

Wednesday, April 15, 2009

Syntax of Exception Handling code




C++ uses three new keywords namely, throw, try, and catch to handle exceptions. When a function returns using the exception handling mechanism, it is referred to as throwing an exception.
The Keyword throw implements this “return” activity. The keyword try prefaces a block of statements which may generate exceptions. A catch block defined by the keyword catch ‘catches’ the exceptions ‘thrown’ by throw and handles them appropriately.
The “try” block code normally invokes a function that detects an exception. The function which is in the “throw” block returns (“throw”) the control to the “catch” block. The catch block may have more than one catch statements, each corresponding to a particular type of exception. For example, if the throw blocks is likely to throw two exceptions, the catch block will have two catch statements, one for each type of exception. Each catch statements is called an exception handler.
The function that throws the exceptions indicates the specific type of exception which in turn decides the catch statement to be executed. It is somewhat similar to a switch statement.
Example for Exception Handling
#include <>
#include <>
void xcep(int n)
{
try
{
if(n!=0) throw n;
else throw “Zero”;
}
catch (int I)
{
cout<<”caught an int” <<>
}
catch(char *st)
{ cout<<”caught a string” <<>
}
}
main() { xcep(1);
xcep(2);
xcep(0);
//return 0;
}



Sunday, April 12, 2009

DATA TYPES IN C++

Identifiers

Identifiers
Identifiers refer to the name of variables, functions, arrays, classes, etc. created by the programmer. They have the fundamental requirement of any languages. Each language has its own rules for naming these identifiers.

The following rules are common to both C & C++.

· Only alphabetic characters, digits and underscores are permitted.
· The name can’t start with a digit.
· Uppercase and lowercase letters are different.
· A declared keyword cannot be used as a variable name.

A major difference between C & C++ is the limit on the length of the name. C++ plays no limit on its length.

KEYWORDS IN C++

Keywords
In C++ we can use all the keywords of C language (32 keywords).
C language key words are listed below
auto
break
case
char
const
continue
default
do
double
enum
else
extern
float
for
goto
if
int
long
return
register
signed
short
static
sizeof
struct
witch
typedef
union
unsigned
void
volatile
while

Apart from that we have some new keywords in C++. They are explicitly reserved identifiers and cannot be used as names for the program variables or other user-defined program elements/ the C++ keywords are listed below.
class
friend
catch
operator
private
protected
virtual
inline
public
template
this
throw
try

Token of C++

Token of C++
The small individual units in a program are known as token. C++ has the following tokens:
Ø Keywords
Ø Identifiers
Ø Constants
Ø Strings
Ø Operator
A C++ program is written using these tokens, white spaces, and the syntax of the languages. Most of the C++ tokens are basically similar to the C token with the exception of some additions and minor modifications.

Cascading of I/O Operators

Cascading of I/O Operators
We have used the extraction operator << repeatedly in the two statements for printing results. The statement
cout<<”Total Value is =”< First sends the string “Total Value is=” to cout and then sends the value of sum. Finally, it sends the new line character so that the next output will be in the new line. The multiple use of << in one statement is called cascading. When cascading an output operator, we should ensure necessary blank spaces between different items. Using the cascading technique, the last two statements can be combine as follows.
Cout<<”Total Value is=”<This is one statement but provides two lines of output.
Total Value is = 15
Average = 7.5

If you want one line of output, the statement will be;
Cout<<”Total Value is=”<Output will be

Total Value is = 15 Average = 7.5
We can also cascade input operator >> as shown below
cin>>n1>>n2>>;
The values are assigned from left to right. That is, if we key in two values, say, 15 and 24 then 15 will be assigned to n1 and 24 will be assigned to n2.

INPUT OUTPUT STREAMS IN C++

Input Operator
Input using insertion operator
The operator >> is known as extraction or get from operator. It extracts (or takes) the value from the keyboard and assigns it to the variable on its right. It is used to read the value from the user. This corresponds to the familiar scanf() operation.
Syntax:

cin>>variable_name;

Example:

int a;
cin>>a;
Using the above example we can read an integer value from the input device.

Output Operator

The operator << is known as insertion. It is used to write the output to the display device.

Syntax:

cout<
Example:

int a;
cout<
Using the above example we can print an integer value to the output device. It just like printf() statement is C.

Structure of C++ Porgram



Structure of C++ Program

A typical C++ program would contain four sections as shown in fig. These sections may be placed in separate code files and then compiled independently or jointly.
It is common practice to organize a program into three separate files. The class declarations are placed in a header file and the definitions of member functions go into another file. Finally, the main program that uses the class is placed in a third file which “includes” the previous two files as well any other files required.

Syntax for structures of C++ Program

// Comment Statements
header files
cass declaration
{
dta member;
member function();
};
void main()
{
cass name object name;
oject name. member function();
getch();
}

Thursday, April 9, 2009

INTRODUCTION TO C++

INTRODUCTION OF C++

C++ is an Object Oriented Programming language. C++ was developed by Bjarne Stroustrup at AT & T Bell Laboratories Murray Hill, New Jersey, USA, in the early eighties (1982). Using C language we can solve simple problems to solve complex problem he decided to develop a new language that will support real world problems. So he took Object and Class from Simlua 67 (Simlua 67 is first object oriented language) and entire C language syntax. Merging these two concepts (C++ is an extension of C with a major addition of the class construct feature of simula67) he developed a new language. It is initially called a c with classes later it was renamed as C++. So C++ is a superset of C. Therefore. Almost all C programs are also C++ programs. The object oriented features in C++ allow programmers to build large programs with clarity, extensibility and ease of maintenance.

Sample C++ Program

// comment Statement

#include

#include

main()

{

cout<<"God";

}

Output will be

God


Main()
The C++ program is a collection of functions. Every C++ program must have a main()
Comment Statemen

Two type of comments are there
1. Single line comments
2. Multi line comments
C++ introduces a new comment symbol // (Double slash).
Single line comments
Double slash comment is basically a single line comment. Start with double slash symbol and terminate at the end of the line. A comment may start anywhere in the line and whatever follows till the end of the line is ignored. Note that there is no closing symbol.

Single line comments can be written as follows:
//cout<<”Good Morning”; //cout<<”Good Afternoon”; //cout<<”Good Evening”; //cout<<”Good Night”;

Multi Line comments

The comment symbols /*, */ are still valid and are more suitable for multi line comments. Multi line comments can be written as follows:

/* cout<<”Good Morning”; cout<<”Good Afternoon”; cout<<”Good Evening”; cout<<”Good Night”; */

Example

For example, the double slash comment cannot be used in the following case:

for (j=0; j

OOPS CONCEPTS

Objects:

Object is a real entity or any touchable event, Objects are the basic run-time entities in an object-oriented system. In c++, instances of a class is called an Object.


Object is the basic unit of object-oriented programming. Objects are identified by its unique name. An object represents a particular instance of a class. There can be more than one instance of an object. Each instance of an object can hold its own relevant data. An Object is a collection of data members and associated member functions also known as methods.
Classes:
Group of objects forms a class.
Classes are data types based on which objects are created. Objects with similar properties and methods are grouped together to form a Class. Thus a Class represent a set of individual objects. Characteristics of an object are represented in a class as Properties. The actions that can be performed by objects becomes functions of the class and is referred to as Methods.

For example consider we have a Class of Cars under which Santro Xing, Alto and WaganR represents individual Objects. In this context each Car Object will have its own, Model, Year of Manufacture, Colour, Top Speed, Engine Power etc., which form Properties of the Car class and the associated actions i.e., object functions like Start, Move, Stop form the Methods of Car Class.
No memory is allocated when a class is created. Memory is allocated only when an object is created, i.e., when an instance of a class is created.

Inheritance:
Inheritance is the process of forming a new class from an existing class or base class. The base class is also known as parent class or super class, The new class that is formed is called derived class. Derived class is also known as a child class or sub class. Inheritance helps in reducing the overall code size of the program, which is an important concept in object-oriented programming.
Data Abstraction:
Data Abstraction increases the power of programming language by creating user defined data types. Data Abstraction also represents the needed information in the program without presenting the details.

Data Encapsulation:
Data Encapsulation combines data and functions into a single unit called Class. When using Data Encapsulation, data is not accessed directly; it is only accessible through the functions present inside the class. Data Encapsulation enables the important concept of data hiding possible.

Polymorphism:
Polymorphism allows routines to use variables of different types at different times. An operator or function can be given different meanings or functions. Polymorphism refers to a single function or multi-functioning operator performing in different ways.

Overloading:
Overloading is one type of Polymorphism. It allows an object to have different meanings, depending on its context. When an exiting operator or function begins to operate on new datatype, or class, it is understood to be overloaded.

Reusability:
This term refers to the ability for multiple programmers to use the same written and debugged existing class of data. This is a time saving device and adds code efficiency to the language. Additionally, the programmer can incorporate new features to the existing class, further developing the application and allowing users to achieve increased performance. This time saving feature optimizes code, helps in gaining secured applications and facilitates easier maintenance on the application.

Wednesday, April 8, 2009

Basic Concept of OOPS


"Object-oriented " remains a term which is interpreted differently people. It is hterefore necessary to understtand some of the concepts used extensively in object-oriented programming. We shall discuss in this section the following general concepts:

1. Objects
2. Classes
3. data abstraction
4. Data Encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic binding
8. Message Passing

In order to understand the basic concepts in C++, the programmer must have a command of the basic terminology in object-oriented programming. Below is a brief outline of the concepts of Object-oriented programming languages: