Saturday, October 15, 2011

C++ Tutorial: Some Lab assignments on data conversions

Questions: Write a program that can convert the Distance (meter, centimeter) to meters measurement in float and vice versa. Make a class distance with two data members, meter and centimeter. You can add function members as per your requirement.
using std::cout;
using std::cin;
using std::endl;

class distance
float meter;
float centimeter;
distance(float met) //for basic to userdefined data conversion
meter = static_cast<int>(met);
centimeter = static_cast<int>((met-meter)*100);
void getdata()
cout<<"Enter the value of Meter: ";
cout<<"Enter the value of Centimter: ";
operator float() //for user defined to basic data conversion
float met;
met = meter+centimeter/100;
return met;
void display(void)
cout<<"Meter: "<<meter<<"\n"<<" Centimeter: "<<centimeter;

int main()
distance d; //uset defined
float m; //basic
int temp;

cout<<"1. Conversion from (meters, centimeters) to meters "<<endl;
cout<<"2. Conversion from meters to (meters, centimeters) "<<endl;
cout<<"Enter the choice: ";
case 1:
m = d;
cout<<"The Distance in meter is: "<<m;
case 2:
cout<<"Enter the value in Meter: ";
d = m;
cout<<"Enter either 1 or 2"<<endl;
cout<<"You Entered " <<temp;

return 0;

Friday, October 14, 2011

C++ Tutorial: Some Lab assignments on Operator Overloading

Question:Write a class to store x, y, and z coordinates of a point in three-dimensional space. Using operator overloading, write friend functions to add, and subtract the vectors.

using namespace std;

class dimension
float xco, yco, zco;
void getco_ordinate();
friend dimension operator +(dimension, dimension);
friend dimension operator -(dimension, dimension);
void display(){cout<<"("<< xco<<" , "<<yco<< " , "<<zco<<")";}

void dimension::getco_ordinate()

cout<<"Enter the x-coordinate: ";
cout<<"Enter the y-coordinate: ";
cout<<"Enter the z-coordinate: ";

dimension operator +(dimension d1,  dimension d2 )
dimension temp;
temp.xco = d1.xco + d2.xco;
temp.yco = d1.yco + d2.yco;
temp.zco = d1.zco + d2.zco;
return temp; //nameless object

dimension operator -(dimension d1, dimension d2)
dimension temp;
temp.xco = d1.xco - d2.xco;
temp.yco = d1.yco - d2.yco;
temp.zco = d1.zco - d2.zco;
return temp;

int main()
dimension d1, d2, d3, d4;
cout<<" + or - ";
d3 = d1 + d2;
d4 = d1 - d2;
cout<<" = ";
cout<<" or ";
return 0;


Minor project: Cyber Management System using C

cyber_thumb[2] C.yber is a program which interconnects different computers which allows users to communicate over the computer network and provide security from unauthorized users by login system in client server.The project aims at managing the cyber cafe with multiple clients and give the clients access of services that the cyber is providing when it log in. The clients can log in as members or guests and use the services that the cyber is providing. The client can request services of cafe like tea, coffee or any others.
The above program uses file handling as database. The various features of C like Multithreading, Socket (Networking) are used. It is very useful for the student or beginner in the programming field. It also helps in building the other type of management software or projects like library management, student record, and many more.
Block Diagram:
basic operation_thumb[6]


C++ Tutorial : This pointer and static members

This Pointer
The keyword this represents a pointer to the object whose member function is being executed. It is a pointer to the object itself.
One of its uses can be to check if a parameter passed to a member function is the object itself. For example,
// this
#include <iostream>
using namespace std;

class CDummy {
int isitme (CDummy& param);

int CDummy::isitme (CDummy& param)
if (&param == this) return true;
else return false;

int main () {
CDummy a;
CDummy* b = &a;
if ( b->isitme(a) )
cout << "yes, &a is b";
return 0;

Thursday, October 13, 2011

C++ Tutorial: Operator Overloading

C++ incorporates the option to use standard operators to perform operations with classes in addition to with fundamental types. For example:
int a, b, c;
a = b + c;
This is obviously valid code in C++, since the different variables of the addition are all fundamental types. Nevertheless, it is not so obvious that we could perform an operation similar to the following one:
struct {
string product;
float price;
} a, b, c;
a = b + c; 
In fact, this will cause a compilation error, since we have not defined the behavior our class should have with addition operations. However, thanks to the C++ feature to overload operators, we can design classes able to perform operations using standard operators. All operators except the following six operators are overloadable:
  1. Scope resolution operator(::)
  2. Dot operator (.)
  3. Sizeof operator (sizeof())
  4. Type cast operator (typeid())
  5. Conditional operator (?:)
  6. Pointer to member operator (.*)
To overload an operator in order to use it with classes we declare operator functions, which are regular functions whose names are the operator keyword followed by the operator sign that we want to overload. The format is: type operator sign (parameters) { /*...*/ } Here you have an example that overloads the addition operator (+). We are going to create a class to store two dimensional vectors and then we are going to add two of them: a(3,1) and b(1,2). The addition of two  two dimensional vectors is an operation as simple as adding the two x coordinates to obtain the resulting x coordinate and adding the two y coordinates to obtain the resulting y. In this case the result will be (3+1,1+2) = (4,3).
// vectors: overloading operators example
#include <iostream>
using namespace std;

class CVector {
int x,y;
CVector () {};
CVector (int,int);
CVector operator + (CVector);

CVector::CVector (int a, int b) {
x = a;
y = b;

CVector CVector::operator+ (CVector param) {
CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return (temp);

int main () {
CVector a (3,1);
CVector b (1,2);
CVector c;
c = a + b;
cout << c.x << "," << c.y;
return 0;
It may be a little confusing to see so many times the CVector identifier. But, consider that some of them refer to the class name (type) CVector and some others are functions with that name (constructors must have the same name as the class). Do not confuse them:
CVector (int, int);            // function name CVector (constructor)
CVector operator+ (CVector);   // function returns a CVector 
The function operator+ of class CVector is the one that is in charge of overloading the addition operator (+). This function can be called either implicitly using the operator, or explicitly using the function name:
c = a + b;
c = a.operator+ (b);
Both expressions are equivalent. Notice also that we have included the empty constructor (without parameters) and we have defined it with an empty block:
CVector () { };
This is necessary, since we have explicitly declared another constructor:
CVector (int, int);
And when we explicitly declare any constructor, with any number of parameters, the default constructor with no parameters that the compiler can declare automatically is not declared, so we need to declare it ourselves in order to be able to construct objects of this type without parameters. Otherwise, the declaration:
CVector c;
included in main() would not have been valid. Anyway, I have to warn you that an empty block is a bad implementation for a constructor, since it does not fulfill the minimum functionality that is generally expected from a constructor, which is the initialization of all the member variables in its class. In our case this constructor leaves the variables x and y undefined. Therefore, a more advisable definition would have been something similar to this:
CVector () { x=0; y=0; };
which in order to simplify and show only the point of the code I have not included in the example. As well as a class includes a default constructor and a copy constructor even if they are not declared, it also includes a default definition for the assignment operator (=) with the class itself as parameter. The behavior which is defined by default is to copy the whole content of the data members of the object passed as argument (the one at the right side of the sign) to the one at the left side
CVector d (2,3);
CVector e;
e = d;           // copy assignment operator 
The copy assignment operator function is the only operator member function implemented by default. Of course, you can redefine it to any other functionality that you want, like for example, copy only certain class members or perform additional initialization procedures. The overload of operators does not force its operation to bear a relation to the mathematical or usual meaning of the operator, although it is recommended. For example, the code may not be very intuitive if you use operator + to subtract two classes or operator== to fill with zeros a class, although it is perfectly possible to do so. Although the prototype of a function operator+ can seem obvious since it takes what is at the right side of the operator as the parameter for the operator member function of the object at its left side, other operators may not be so obvious. Here you have a table with a summary on how the different operator functions have to be declared (replace @ by the operator in each case):
Points to be remembered while overloading operators
  1. All operators are not overloadable. Any attempt to make these operators overloadable will case compiler error.
  2. The ‘+’ operator cannot be made as ‘-‘ due to overloading.
  3. Overloading only extends the meaning of operator and their use but does not change their identity. For example, ‘+’ operator can be extended to add two complex numbers.
  4. Although C++ programmers can write program that use ‘+’ operator to subtract two complex numbers but it is very bad programming practice. Programmer should be aware of this.
  5. Overloading can be used very efficiently in data conversion between user defined and basic or between user defined themselves.

Wednesday, October 12, 2011

C++ Tutorial: Some Lab assignments on Objects and Classes

Question: Write a simple program that convert the temperature in degree Celsius to degree Fahrenheit  and vice versa using the basic concept of class and object. Make separate class for Centigrade and Fahrenheit which will have the private member to hold the temperature value and make conversion functions in each class for conversion from one to other. For example you will have function toFahrenheit() in class Celsius that converts to Fahrenheit scale and returns the value.
#include <iostream>
using namespace std;

class Celcius{
float c;
void readCelcius(){
cout<<"Enter temperature in Celcius: ";
float toFarenheit(){

class Farenheit{
float f;
void readFarenheit(){
cout<<"Enter temperature in Farenhiet: ";
float toCelcius(){

int main(){
Celcius c1;
Farenheit f1;
cout<<c1.toFarenheit()<<" F"<<endl;
cout<<f1.toCelcius()<<" C";
return 0;

Tuesday, October 11, 2011

C++ Tutorial : Constructors and Destructors

Objects generally need to initialize variables or assign dynamic memory during their process of creation to become operative and to avoid returning unexpected values during their execution. For example, what would happen if in the previous example we called the member function area() before having called function set_values()? Probably we would have gotten an undetermined result since the members x and y would have never been assigned a value.
In order to avoid that, a class can include a special function called constructor, which is automatically called whenever a new object of this class is created. This constructor function must have the same name as the class, and cannot have any return type; not even void.
We are going to implement CRectangle including a constructor:
  1: // example: class constructor
  2: #include <iostream>
  3: using namespace std;
  5: class CRectangle {
  6:     int width, height;
  7:   public:
  8:     CRectangle (int,int);
  9:     int area () {return (width*height);}
 10: };
 12: CRectangle::CRectangle (int a, int b) {
 13:   width = a;
 14:   height = b;
 15: }
 17: int main () {
 18:   CRectangle rect (3,4);
 19:   CRectangle rectb (5,6);
 20:   cout << "rect area: " << rect.area() << endl;
 21:   cout << "rectb area: " << rectb.area() << endl;
 22:   return 0;
 23: }

As you can see, the result of this example is identical to the previous one. But now we have removed the member function set_values(), and have included instead a constructor that performs a similar action: it initializes the values of width and height with the parameters that are passed to it.
Notice how these arguments are passed to the constructor at the moment at which the objects of this class are created:

CRectangle rect (3,4);
CRectangle rectb (5,6);

Constructors cannot be called explicitly as if they were regular member functions. They are only executed when a new object of that class is created.
You can also see how neither the constructor prototype declaration (within the class) nor the latter constructor definition include a return value; not even void.
The destructor fulfills the opposite functionality. It is automatically called when an object is destroyed, either because its scope of existence has finished (for example, if it was defined as a local object within a function and the function ends) or because it is an object dynamically assigned and it is released using the operator delete.
The destructor must have the same name as the class, but preceded with a tilde sign (~) and it must also return no value.
The use of destructors is especially suitable when an object assigns dynamic memory during its lifetime and at the moment of being destroyed we want to release the memory that the object was allocated.
  1: // example on constructors and destructors
  2: #include <iostream>
  3: using namespace std;
  5: class CRectangle {
  6:     int *width, *height;
  7:   public:
  8:     CRectangle (int,int);
  9:     ~CRectangle ();
 10:     int area () {return (*width * *height);}
 11: };
 13: CRectangle::CRectangle (int a, int b) {
 14:   width = new int;
 15:   height = new int;
 16:   *width = a;
 17:   *height = b;
 18: }
 20: CRectangle::~CRectangle () {
 21:   delete width;
 22:   delete height;
 23: }
 25: int main () {
 26:   CRectangle rect (3,4), rectb (5,6);
 27:   cout << "rect area: " << rect.area() << endl;
 28:   cout << "rectb area: " << rectb.area() << endl;
 29:   return 0;
 30: }

C++ Tutorial : Objects and Classes in C++

A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions.
An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable.
Classes are generally declared using the keyword class, with the following format:
class class_name {
} object_names;

Where class_name is a valid identifier for the class, object_names is an optional list of names for objects of this class. The body of the declaration can contain members, that can be either data or function declarations, and optionally access specifiers.
All is very similar to the declaration on data structures, except that we can now include also functions and members, but also this new thing called access specifier. An access specifier is one of the following three keywords: private, public or protected. These specifiers modify the access rights that the members following them acquire:
  • private members of a class are accessible only from within other members of the same class or from their friends(to be discussed later).

  • protected members are accessible from members of their same class and from their friends, but also from members of their derived classes.

  • Finally, public members are accessible from anywhere where the object is visible.
By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before one other class specifier automatically has private access. For example:
class CRectangle {
int x, y;
void set_values (int,int);
int area (void);
} rect;
Declares a class (i.e., a type) called CRectangle and an object (i.e., a variable) of this class called rect. This class contains four members: two data members of type int (member x and member y) with private access (because private is the default access level) and two member functions with public access: set_values() and area(), of which for now we have only included their declaration, not their definition. Notice the difference between the class name and the object name: In the previous example, CRectangle was the class name (i.e., the type), whereas rect was an object of typeCRectangle. It is the same relationship int and a have in the following declaration:
int a;
where int is the type name (the class) and a is the variable name (the object). After the previous declarations of CRectangle and rect, we can refer within the body of the program to any of the public members of the object rect as if they were normal functions or normal variables, just by putting the object's name followed by a dot (.) and then the name of the member. All very similar to what we did with plain data structures before. For example:
rect.set_values (3,4); myarea = rect.area();
The only members of rect that we cannot access from the body of our program outside the class are x and y, since they have private access and they can only be referred from within other members of that same class. Here is the complete example of class CRectangle:
1: // classes example
2: #include <iostream>
3: using namespace std;
5: class CRectangle {
6:     int x, y;
7:   public:
8:     void set_values (int,int);
9:     int area () {return (x*y);}
10: };
12: void CRectangle::set_values (int a, int b) {
13:   x = a;
14:   y = b;
15: }
17: int main () {
18:   CRectangle rect;
19:   rect.set_values (3,4);
20:   cout << "area: " << rect.area();
21:   return 0;
22: }
The most important new thing in this code is the operator of scope (::, two colons) included in the definition of set_values(). It is used to define a member of a class from outside the class definition itself. You may notice that the definition of the member function area() has been included directly within the definition of the CRectangle class given its extreme simplicity, whereasset_values() has only its prototype declared within the class, but its definition is outside it. In this outside definition, we must use the operator of scope (::) to specify that we are defining a function that is a member of the class CRectangle and not a regular global function. The scope operator (::) specifies the class to which the member being declared belongs, granting exactly the same scope properties as if this function definition was directly included within the class definition. For example, in the function set_values() of the previous code, we have been able to use the variables x and y, which are private members of classCRectangle, which means they are only accessible from other members of their class. The only difference between defining a class member function completely within its class or to include only the prototype and later its definition, is that in the first case the function will automatically be considered an inline member function by the compiler, while in the second it will be a normal (not-inline) class member function, which in fact supposes no difference in behavior. Members x and y have private access (remember that if nothing else is said, all members of a class defined with keyword class have private access). By declaring them private we deny access to them from anywhere outside the class. This makes sense, since we have already defined a member function to set values for those members within the object: the member function set_values(). Therefore, the rest of the program does not need to have direct access to them. Perhaps in a so simple example as this, it is difficult to see any utility in protecting those two variables, but in greater projects it may be very important that values cannot be modified in an unexpected way (unexpected from the point of view of the object). One of the greater advantages of a class is that, as any other type, we can declare several objects of it. For example, following with the previous example of class CRectangle, we could have declared the object rectb in addition to the object rect:
1: // example: one class, two objects
2: #include <iostream>
3: using namespace std;
5: class CRectangle {
6:     int x, y;
7:   public:
8:     void set_values (int,int);
9:     int area () {return (x*y);}
10: };
12: void CRectangle::set_values (int a, int b) {
13:   x = a;
14:   y = b;
15: }
17: int main () {
18:   CRectangle rect, rectb;
19:   rect.set_values (3,4);
20:   rectb.set_values (5,6);
21:   cout << "rect area: " << rect.area() << endl;
22:   cout << "rectb area: " << rectb.area() << endl;
23:   return 0;
24: }
25: rect area: 12
In this concrete case, the class (type of the objects) to which we are talking about is CRectangle, of which there are two instances or objects: rect and rectb. Each one of them has its own member variables and member functions. Notice that the call to rect.area() does not give the same result as the call to rectb.area(). This is because each object of class CRectangle has its own variables x and y, as they, in some way, have also their own function members set_value() and area() that each uses its object's own variables to operate. That is the basic concept of object-oriented programming: Data and functions are both members of the object. We no longer use sets of global variables that we pass from one function to another as parameters, but instead we handle objects that have their own data and functions embedded as members. Notice that we have not had to give any parameters in any of the calls to rect.area or rectb.area. Those member functions directly used the data members of their respective objects rect and rectb.

C++ Tutorial: Namespace in C++

A program includes many identifiers defined in different scopes. Sometimes a variable of one scope will "overlap" (i.e., collide) with a variable of the same name in a different scope, possibly creating a naming conflict. Such overlapping can occur at many levels. Identifier overlapping occurs frequently in third-party libraries that happen to use the same names for global identifiers (such as functions). This can cause compiler errors.
The C++ standard attempts to solve this problem with namespaces. Each namespace defines a scope in which identifiers and variables are placed. To use a namespace member, either the member's name must be qualified with the namespace name and the binary scope resolution operator (::), as in
or a using declaration or using directive must appear before the name is used in the program. Typically, such using statements are placed at the beginning of the file in which members of the namespace are used. For example, placing the following using directive at the beginning of a source-code file
using namespace MyNameSpace

A using declaration (e.g., using std::cout;) brings one name into the scope where the declaration appears. A using directive (e.g., using namespace std;) brings all the names from the specified namespace into the scope where the directive appears.

Not all namespaces are guaranteed to be unique. Two third-party vendors might inadvertently use the same identifiers for their namespace names.  The following code segment illustrates the  user of Namespace.
1  // programming-techniques tutorial on Namespace
2  // Demonstrating namespaces.
3  #include <iostream>
4  using namespace std; // use std namespace
6  int integer1 = 98; // global variable
8  // create namespace Example                           
9  namespace Example                                     
10  {                                                     
11     // declare two constants and one variable          
12     const double PI = 3.14159;                         
13     const double E = 2.71828;                          
14     int integer1 = 8;                                  
16     void printValues(); // prototype                   
18     // nested namespace                                
19     namespace Inner                                    
20     {                                                  
21        // define enumeration                           
22        enum Years { FISCAL1 = 1990, FISCAL2, FISCAL3 };
23     } // end Inner namespace                           
24  } // end Example namespace                            
26  // create unnamed namespace                           
27  namespace                                             
28  {                                                     
29     double doubleInUnnamed = 88.22; // declare variable
30  } // end unnamed namespace                            
32  int main()
33  {
34     // output value doubleInUnnamed of unnamed namespace
35     cout << "doubleInUnnamed = " << doubleInUnnamed;
37     // output global variable
38     cout << "\n(global) integer1 = " << integer1;
40     // output values of Example namespace
41     cout << "\nPI = " << Example::PI << "\nE = " << Example::E
42        << "\ninteger1 = " << Example::integer1 << "\nFISCAL3 = "
43        << Example::Inner::FISCAL3 << endl;
45     Example::printValues(); // invoke printValues function
46     return 0;
47  } // end main
49  // display variable and constant values
50  void Example::printValues()
51  {
52     cout << "\nIn printValues:\ninteger1 = " << integer1 << "\nPI = "
53        << PI << "\nE = " << E << "\ndoubleInUnnamed = "
54        << doubleInUnnamed << "\n(global) integer1 = " << ::integer1
55        << "\nFISCAL3 = " << Inner::FISCAL3 << endl;
56  } // end printValues

Using the std Namespace

Line 4 informs the compiler that namespace std is being used. The contents of header file <iostream> are all defined as part of namespace std. [Note: Most C++ programmers consider it poor practice to write a using directive such as line 4 because the entire contents of the namespace are included, thus increasing the likelihood of a naming conflict.]
The using namespace directive specifies that the members of a namespace will be used frequently throughout a program. This allows the programmer to access all the members of the namespace and to write more concise statements such as
cout << "double1 = " << double1;

rather than
std::cout << "double1 = " << double1;

Without line 4, either every cout and endl in above code would have to be qualified with std::, or individual using declarations must be included for cout and endl as in:
using std::cout;
using std::endl;

The using namespace directive can be used for predefined namespaces (e.g., std) or programmer-defined namespaces.

Defining Namespace

Lines 9, 4 use the keyword namespace to define namespace Example. The body of a namespace is delimited by braces ({}). Namespace Example's members consist of two constants (PI and E at lines 1213), an int (integer1 at line 14), a function (printValues at line 16) and a nested namespace (Inner at lines 1923). Notice that member integer1 has the same name as global variable integer1 (line 6). Variables that have the same name must have different scopesotherwise compilation errors occur. A namespace can contain constants, data, classes, nested namespaces, functions, etc. Definitions of namespaces must occupy the global scope or be nested within other namespaces.
Lines 27, 30 create an unnamed namespace containing the member doubleInUnnamed. The unnamed namespace has an implicit using directive, so its members appear to occupy the global namespace, are accessible directly and do not have to be qualified with a namespace name. Global variables are also part of the global namespace and are accessible in all scopes following the declaration in the file.
Accessing Namespace Members with Qualified Names
Line 35 outputs the value of variable doubleInUnnamed, which is directly accessible as part of the unnamed namespace. Line 38 outputs the value of global variable integer1. For both of these variables, the compiler first attempts to locate a local declaration of the variables in main. Since there are no local declarations, the compiler assumes those variables are in the global namespace.
Lines 41, 43 output the values of PI, E, integer1 and FISCAL3 from namespace Example. Notice that each must be qualified with Example:: because the program does not provide any using directive or declarations indicating that it will use members of namespace Example. In addition, member integer1 must be qualified, because a global variable has the same name. Otherwise, the global variable's value is output. Notice that FISCAL3 is a member of nested namespace Inner, so it must be qualified with Example::Inner::.
Function printValues (defined at lines 5056) is a member of Example, so it can access other members of the Example namespace directly without using a namespace qualifier. The output statement in lines 5255 outputs integer1, PI, E, doubleInUnnamed, global variable integer1 and FISCAL3. Notice that PI and E are not qualified with Example. Variable doubleInUnnamed is still accessible, because it is in the unnamed namespace and the variable name does not conflict with any other members of namespace Example. The global version of integer1 must be qualified with the unary scope resolution operator (::), because its name conflicts with a member of namespace Example. Also, FISCAL3 must be qualified with Inner::. When accessing members of a nested namespace, the members must be qualified with the namespace name (unless the member is being used inside the nested namespace).