Showing posts with label Introduction. Show all posts
Showing posts with label Introduction. Show all posts

Generating XHTML MP (WAP 2.0) Pages From PHP

alt="XHTML Mp Webpage Generation Using PHP"
title="XHTML MP (WAP 2.0) Webpage on a Cellphone"
src="http://one.arvind.googlepages.com/xhtml_mp_wap_site.jpg">Maybe
you guys know that I've been working on a service called
MyWapBlog.com which lets peoples create/manage mobile blogs using their
mobile phones. In the course of the development I've learnt great deal
about mobile websites and their dynamic generation, and I'm sharing a
bit of it here in this post.


How do you generate dynamic (X)HTML Pages using PHP? Simple:



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"  dir="ltr">
<head>
<title>Sometitle</title>
</head>
<body>
<h1>Hello</h1>
<p> style="color: rgb(0, 0, 187);"><?php 
style="color: rgb(0, 119, 0);">echo  style="color: rgb(0, 0, 187);">date style="color: rgb(0, 119, 0);">( style="color: rgb(221, 0, 0);">'h:i A, j-M-y' style="color: rgb(0, 119, 0);">);  style="color: rgb(0, 0, 187);">?></p>
</body>
</html>

And if you look at XHTML MP pages, their source look like the
following:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
...
...

So you see these pages have a different document type and some
other differences. So will the following code work and generate a valid
WAP 2.0 page?:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sometitle</title>
</head>
<body>
<h1>Hello</h1>
<p> style="color: rgb(0, 0, 187);"><?php 
style="color: rgb(0, 119, 0);">echo  style="color: rgb(0, 0, 187);">date style="color: rgb(0, 119, 0);">( style="color: rgb(221, 0, 0);">'h:i A, j-M-y' style="color: rgb(0, 119, 0);">);  style="color: rgb(0, 0, 187);">?></p>
</body>
</html>

The answer is “NO”? Why? Because XHTML MP pages needs to be
served with a different Content-Type than what is generated by .PHP
files. Normally when you runa s PHP script and it outputs something,
the content is served with Content-Type: text/html


What is
Content-Type?


It is a header (information about a particular resource)
returned to browser when it requests something from a server. When you
request an image, the server return the image with the header
image/png, image/jpeg etc. letting the browser know how the returned
content is to be interpreted.


PHP scripts can return contents of any type (using
the header() function), from text to
images and PDFs to ZIPs. And therfore
if we want to generate  XHTML MP pages, it can even do that
without doubt.


So what we need to do is, just change the above code a bit
adding a new line at the top so that the whole code look like the
following:



style="color: rgb(0, 0, 187);"><?php header
style="color: rgb(0, 119, 0);">( style="color: rgb(221, 0, 0);">"Content-type: application/vnd.wap.xhtml+xml; charset=UTF-8" style="color: rgb(0, 119, 0);">); style="color: rgb(0, 0, 187);">?>
style="color: rgb(0, 0, 0);"><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sometitle</title>
</head>
<body>
<h1>Hello</h1>
<p> style="color: rgb(0, 0, 187);"><?php  style="color: rgb(0, 119, 0);">echo  style="color: rgb(0, 0, 187);">date style="color: rgb(0, 119, 0);">( style="color: rgb(221, 0, 0);">'h:i A, j-M-y' style="color: rgb(0, 119, 0);">);  style="color: rgb(0, 0, 187);">?></p>
</body>
</html>

This will tell the browser that the content we are going to
serve is of the type XHTML MP. We always use the charset UTF-8 for
these pages, which is also told to the requesting browser.


Now the big question is, why we didn't do this for normal HTML
pages. Why didn't we have to tell the browser that content is of the
type “text/html” when it was so? Because PHP does it for us! Yes
whenever we output anything from PHP scripts, the PHP interpreter
outputs the default header (text/html) automatically. Just as the
PHP  interpreter finds anything in the script that needs to be
output, it first generates a header, the outputted content follows. For
example in the first script, the very first line (very first character
“<”) needs to be output to the browser. So before that, the PHP
interpreter sends a content type header (default – text/html).


Therefore, when we had to output our content with a different
header we had to make sure that it is done before PHP does it
automatically. Two headers  cannot be valid.


This is it for this post, do check back soon for more new
posts. Till then, good bye!

Writing and Running PHP Scripts

We’ve been talking about PHP for 2 days now; we even wrote a simple PHP
script and understood its working. Now comes a big question, “How do we
write and run PHP scripts?”. Do we need some special software to write
PHP code? How do we run these scripts?


Let’s know the answers!


Writing PHP scripts


You don’t need anything special; really, plain old Notepad would do just
fine. PHP is an interpreted language hence code remains as it is (not compiled)
thus any plain text editor is fine. Although syntax highlighted text editors
would be better.


If you are using a word processor instead, be sure to save the files as plain
text files and not in the proprietary formats.


Notepad, as I said may be used but I don’t recommend using it, instead
use code editors like Programmers
Notepad
, Notepad++(really
great, supports numerous third-party plug-ins)that have syntax highlighting
feature. That would make you easily understand the code and write it in a better
way with proper indenting etc.


Though, I personally use Macromedia Dreamweaver which has decent syntax highlighting
and IntelliSense type, on the fly, function reference, you are free to use any
editor you like and feel comfortable with.


I’ve read some positive reviews about PHP
Designer
(Paid Software although there is a free lite version) but I
reserve my comments because I’ve yet to use it.


As you can see, PHP is just like JavaScript in this case. Both are interpreted
language and both don’t need any special software to write the codes in.


Running PHP scripts


In this case, PHP is way different that JavaScript. JavaScript is client sided
hence interpreted by the browser; PHP on the other hand is server-sided which
means a server is NEEDED to interpret its scripts. Be it somebody else’s
server (Web hosts) or your own PC server (that you can install yourself).


There are 3 things that you can do to be able to run PHP scripts:




  1. Buy web space, most web hosts even the cheapest ones give PHP support




  2. Find a free web host that has PHP support. You can find plenty of them
    at http://www.free-webhosts.com/




  3. Install your own web server on your own PC. This way your computer would
    act both as a server and a client. This according to most is the best way
    to learn PHP.




In the coming posts, I’ll give you a detailed set-by-step guide for installing
your own web server along with PHP.


So till then good bye guys and thanks for reading!


Related Articles:


Introduction to PHP Part III

Please read the post Introduction
to PHP, How to Insert Dynamic Content on WebPages
, if you haven’t
already.


Below is the code snippet from the previous post.



<html>
<body>
Date: <?php echo date("H:i A, jS F Y"); ?>
</body>
</html>



I’d like to state the following regarding the above code:




  1. PHP code starts with a <?php and ends with a ?> tag. Though PHP supports
    some other tags (depending on the configuration) which signify the same
    but these are the most widely used and are guaranteed to work on most servers.




  2. You can have any number of <?php …?> blocks in a file.




  3. In PHP too, like C++ comments are written using // (single line) and /*…*/
    (multi-line) symbols. Besides these one more symbol i.e. ‘#’
    symbol can also be used for single line comments.




  4. [Update: Added this point] Each statement of PHP ends with a semicolon
    ";" just like in C++. [/Update]




  5. No need to bother about the arguments passed to the date() function now,
    it is just a format string which tells the date function which format to
    return the date in. eg. “H:i A, jS F Y” tells the date function
    to return date and time as “06:00 AM, 18th April 2008”. Echo
    command just echoes (prints) it to the screen.




  6. Files containing PHP codes must have a “.php” extension (default)
    even if it contains HTML too.




  7. Any file having an extension “.php” is parsed by PHP. As someone
    requests a PHP page, the server hands it over to PHP parser. PHP parses
    the file returning HTML codes as it is, but when it finds a <?php…?>
    block, it interprets the code between the tags and returns the result back.
    So we get something like this upon parsing the PHP code at the top of this
    post:



    <html>
    <body>
    Date: 06:00 AM, 18th April 2008
    </body>
    </html>


    In this case, line 1 and 2 were returned as is without any interpretation
    whereas the PHP code between <?php…?> were interpreted and results
    were returned. Again line 4 and 5 were returned the same.




Related Articles:


Introduction to PHP, How to Insert Dynamic Content on WebPages


In the last article Introduction
To PHP, The Web Programming Language
, we talked about what
PHP is and what it is used for. There we talked about the Dynamic insertion
of date & time on web pages. Well, in this post we’re going to ACTUALLY
create page that displays current date & time.


We’ll also briefly talk about how PHP pages are handled by the server
and the browser (client).


Let’s get started!


Suppose we have the following:



<html>
<body>
Date: 06:00 AM, 18th April 2008
</body>
</html>


Above is a simple HTML code (some tags are intentionally left-out)


No matter when and how many times you run it, you’d see the same output
(date and time), since it is a static HTML page.


Now have a look at the following



<html>
<body>
Date: <?php echo date("H:i A, jS F Y"); ?>
</body>
</html>


This is a HTML document having embedded PHP code.


As I said PHP can make documents dynamic. So you’ll get different outputs
(date and time) depending on the condition (the date and time you run it) programmed.
The date function returns the current date and time.


If you request this page today you’ll see

06:00 AM, 18th April 2008

in your browser.


You’d see 12:00 AM, 26th May 2008, should you request it on
26th May 2008 at 12:00 AM, on the other hand the static page would always show
the same date and time statically coded into it.


Since, as I said PHP codes are interpreted server-side so if you look at the
source code of the requested page (from browser) in both the cases (static and
dynamic pages) you’d see



<html>
<body>
Date: 06:00 AM, 18th April 2008
</body>
</html>


in case of the static page, and



<html>
<body>
Date: 06:00 AM, 18th April 2008
</body>
</html>


in the case of the dynamic page requested on the same date and time as coded
into the static page.


As you can notice, the end result is a static HTML document in both cases.
The difference being that a part (date and time) of the PHP page was created
dynamically at run time.


Now it’s pretty obvious that Internet Browser don’t/don’t
need to understand PHP, its server’s job. PHP on the other hand need to
output data that a browser does understand (HTML, Image, files etc.). In this
case it’s plain text which can be considered HTML.


Related Articles:


Introduction To PHP, The Web Programming Language

PHP is a recursive acronym for PHP Hypertext Preprocessor, though it originally
stood for Personal Home Page. It is designed specifically for the web, hence
a web programming language.


PHP is a server-side scripting language which can be either embedded into HTML
documents or used alone. Since PHP is a interpreted language, when someone requests
a page containing PHP, the code is interpreted on the server and the output
(often HTML) is returned to the client web browser.


As you might have guessed, PHP can help you generate different outputs depending
on the conditions and generate different pages depending on conditions programmed,
hence able to create what wee call “Dynamic Pages”.


For example, suppose we want to put the current date and time on our web page,
HTML alone won’t do any good. So a nice option would be to use PHP (in
fact, any sever-sided programming language would be fine. It could also be done
with JavaScript but due to it being client-sided date/time is not sure to be
accurate)


In the next article we’ll see how PHP code works and how it is embedded
in HTML documents, till then Good Bye guys!

Right/Left Bit Shift Operators

This is the continuation of the article Operation
on Bits and Bitwise Operators
.
If you haven’t read that, it is
strongly recommended that you do, before proceeding with this article.


Bit shifting, as the name signifies, does shifting of bits in byte(s). There
are basically two ways, in which bits (of a byte) can be shifted, either to
the right, or to the left. Thus we have two types of bit shifting operator.


If you think logically, its pretty clear that for bit shifting in a byte, we
need to have two data. We need the byte(s) to shift bits on and the number of
bits to be shifted. Guess what, the two operators need these to data as operands!


Right Bit Shifting Operator (>>)



Syntax: res = var >> num;


This would shift all bits in the variable var, num places
to the right which would get stored to the variable res. So
for example if var has the following bit structure:


var = 00110101 (decimal 53)


And we do the following operation:


res = var >> 2;


We would get res as:


res = 00001101 (decimal 13)


As you can see, shifting of the bits to right disposes the bits
(2) from the right and introduces 0s (2) to the left.


Left Bit Shift Operator (<<)



It is similar to the right shift operator except that the direction of shifting
is opposite. The following is I think enough to explain this:


var = 00110101 (decimal 53)


And we do the following operation:


res = var << 2;


We would get res as:


res = 11010100 (decimal 212)


Just the opposite here, here bits get disposed from the left and new 0s are
introduced to the right.


Related Articles:


Operation on Bits and Bitwise Operators

OK guys, this is my first post in the New Year 2008, I thought of posting it
earlier but at last I didn’t. It’s already been so long since I
posted so let’s keep everything aside and talk just about what we have
for today. ;-)


I was sitting the other day thinking about what to write for a post here. Suddenly
I realized that we have discussed operations
on matrices
, arrays,
and what not but we haven’t had the chance to talk anything about the
most fundamental thing a computer understands. Yeah, Operation on Bits.


Bits can have only two values either ON (1) or OFF (0). In this article, we’ll
be discussing about the different operations which can be performed on bits.
One thing to note here is, we don’t perform these operation on single
bits but rather on a group of bits (byte(s)). So even though Bitwise operators
operate on bits its almost always a part of a group (byte, which makes up each
data type), it means we can do bitwise operations on any data type.


BTW, the operators that perform operation on bits are called Bitwise Operator
and such operations are known as Bitwise Operations


The six bitwise operators are listed below:




























&


AND


|


OR


^


XOR


>>


Right shift


<<


Left shift


~


One’s complement


For this post we’ll only be discussing &(AND) and | (OR) operators
leaving the rest for future posts ;-)


Bitwise AND (&) Operator: First thing, it’s nothing to do with the
Logical (&&) operator, both are different.


Now, if you know something about Logic Gates then you might already know about
this. For the rest of us, it does an AND mask on bits.


So, suppose if we have two separate bytes having binary values as 00100000
and 00100001 then doing AND operation would give us the following result.











First Byte:

Second Byte:

00100000

00100001

Result:

00100000

The truth table for this would be:













First Bit
Second Bit
& (AND)

1


1


0


0


1


0


1


0



1


0


0


0



As the Logic AND Gate does, it takes two bits (from the two separate bytes)
and if both of them are ON (1) then only it gives ON (1) in all other cases
it gives OFF (0). So starting from the right there is 0&1->0, 0&0->0,…,
1&1->1 and so on.


Bitwise OR (|) Operator: Here again, both OR (||) and Bitwise OR (|) are different.


The following example is sufficient for you all to understand its operation.











First Byte:

Second Byte:

00100000

00100001

Result:

00100001

Truth table













First Bit
Second Bit
& (OR)

1


1


0


0

1


0


1


0

1


1


1


0


There won’t be any example program here because to fully understand these
operators we need to express data as bits (binary form) and see how the operations
change them. Since decimal to binary conversion programs require some bitwise
operations that we’ve yet to discuss so I think it’ll be pointless
to have such programs now!


P.S. An integer in 32-Bit (Windows) environment is 4 bytes long. Short int
is half of that

8 bits make up one byte.


Related Articles:


Introduction to Operator Overloading in C++ II

From the previous article Introduction
to Operator Overloading in C++
, we know that we can overload operators
by defining member functions having special names. The general form, as you
know, for overloading operators is:


ret-type operator#(arg-list);

Although, you’re free to use any return type as ret-type but commonly
it’ll be the name of the class itself; in this article we’ll be
closely examining why is it so and what would happen if we use other return
types.


You may not expect further theories in this article as all the further discussion
is in the program as comments.


I request you to read the program thoroughly so you may understand what we’re
discussing.



// Example program to illustrate
// operator overloading with diff rent
// return-types used in the overload
// function

#include <iostream.h>

// class
class myclass
{
int a;

public:
// default constructor
myclass(){}

// constructor
myclass(int x){a=x;}

// overloaded operator
// with return type 'myclass'
myclass operator +(myclass);

void show(){cout<<a<<endl;}
};

myclass myclass::operator +(myclass ob)
{
myclass t;

t.a=a + ob.a;

return t;
}

// other class
class myclass2
{
int a;

public:
// default constructor
myclass2(){}

// constructor
myclass2(int x){a=x;}

// here, return type is
// 'int'
int operator +(myclass2);

void show(){cout<<a<<endl;}
};

int myclass2::operator +(myclass2 ob)
{
int t;

t=a + ob.a;

return t;
}

void main()
{
myclass ob1(10);
myclass ob2(20);

myclass2 ob3(100);
myclass2 ob4(200);

int a;

// this is legal because
// the class to which ob1 and ob2
// belong, upon '+' operation return
// data of type 'myclass'
ob1=ob1+ob2;

// here the result of the '+'
// operation return data of type
// 'int' which is assigned to the
// variable 'a' (of data type int)
a=ob3+ob4;

ob1.show();
cout<<a;
}


Related Articles:


Introduction to Operator Overloading in C++


a1 = a2 + a3;



The above operation is valid, as you know if a1, a2 and a3 are instances of
in-built Data
Types
. But what if those are, say objects of a Class;
is the operation valid?


Yes, it is, if you overload the ‘+’ Operator
in the class, to which a1, a2 and a3 belong.


Operator overloading is used to give special meaning to the commonly used operators
(such as +, -, * etc.) with respect to a class. By overloading operators, we
can control or define how an operator should operate on data with respect to
a class.


Operators are overloaded in c++ by creating operator functions either as a
member or a s a Friend Function of a class. Since creating member operator functions
are easier, we’ll be using that method in this article.


As I said operator functions are declared using the following general form:


  ret-type operator#(arg-list);

and then defining it as a normal member function.


Here, ret-type is commonly the name of the class itself as the operations would
commonly return data (object) of that class type.


# is replaced by any valid operator such as +, -, *, /, ++, -- etc.


Now that you have understood the theory, let’s have a look at an example
program:



// Example program to illustrate
// operator overloading
#include <iostream.h>

class myclass
{
int sub1, sub2;

public:
// default constructor
myclass(){}

// main constructor
myclass(int x, int y){sub1=x;sub2=y;}

// notice the declaration
myclass operator +(myclass);

void show(){cout<<sub1<<endl<<sub2;}
};

// returns data of type myclass
myclass myclass::operator +(myclass ob)
{
myclass temp;

// add the data of the object
// that generated the call
// with the data of the object
// passed to it and store in temp
temp.sub1=sub1 + ob.sub1;
temp.sub2=sub2 + ob.sub2;

return temp;
}

void main()
{
myclass ob1(10,90);
myclass ob2(90,10);

// this is valid
ob1=ob1+ob2;

ob1.show();
}


At this stage many of you might be wondering why the operator function is taking
only one argument when it’s operating on two objects (i.e. it’s
a binary operator).


To understand this, first have a look at this line of code:


  ob1 = ob1 + ob2; 


Now assume that ‘operator+’ function is just a regular function
which is called as below when the respective operator (‘+’ in this
case) is encountered with respect to the objects of its class.


  ob1 = ob1.operator+(ob2);

Something like this happens internally when an overloaded operator is encountered.
As you can understand from this, when an operator is encountered, the objects
to the left generates a call to the operator function to which ob3 is passed,
the function does the operation as defined and returns the result as an object
which is then assigned to ob1.


Now I think it’s clear why a overloaded binary operator is taking only
one argument.


Related Articles:


Introduction to Inheritance in C++

Inheritance in C++ is one of the major aspects of Object Oriented Programming
(OOP). It is the process by which one object can inherit or acquire the features
of another object.


In C++ class and structure can use inheritance. It means we can make one class
(known as derived class) to acquire or inherit the features of another class
(known as base class).


Base class has general features common to all the derived classes and derived
class (apart from having all the features of the base class) adds specific features.
This enables us to form a hierarchy of classes.


Ex. if we define a class ‘computer’ then it could serve as the
base class for defining other classes such as ‘laptops’, ‘desktops’
etc.. This is because as you know that laptops have all the features of computers
and so have desktops (and so should their classes) but they have their specific
features too. So, rather than defining all the features of such classes from
scratch, we make them inherit general features from other classes.


General Form of Inheritance:



class
derived-class:access-specifier base-class
{
...
...
...
};


Here access-specifier can be any one of the three private, public and protected.
These will not be discussed here.


For this article we’ll be using public for all the classes we define.
This means, all the public members of the base class will be public to the derived
class too.


Now let’s take the example of ‘computer’ class a bit further
by actually defining it.



class computer
{
int speed;
int main_memory;
int harddisk_memory;

public:
void set_speed(int);
void set_mmemory(int);
void set_hmemory(int);
int get_speed();
int get_mmemory();
int get_hmemory();
};



As you can see, the features (properties and functions) defined in the class
computer is common to laptops, desktops etc. so we make their classes inherit
the base class ‘computer’.



class laptop:public computer
{
int battery_time;
float weight;

public:
void set_battime(int);
void set_weight(float);
int get_battime();
float get_weight();
};



This way the class laptop has all the features of the base class ‘computer’
and at the same time has its specific features (battery_time, weight) which
are specific to the ‘laptop’ class.


If we didn’t use inheritance we would have to define the laptop class
something like this:



class laptop
{
int speed;
int main_memory;
int harddisk_memory;

int battery_time;
float weight;

public:
void set_speed(int);
void set_mmemory(int);
void set_hmemory(int);
int get_speed();
int get_mmemory();
int get_hmemory();

void set_battime(int);
void set_weight(float);
int get_battime();
float get_weight();
};



And then again we would have to do the same thing for desktops and any other
class that would need to inherit from the base class ‘computer’.


Thanks to inheritance, we don’t need to do all this!


I think now you’ve got the essence of what inheritance is, so taking
the example of the ‘computer’ class a bit more further, we implement
it into an example program listed below:



// Introduction to Inheritance in C++
// ------------------------
// An example program to
// demonstrate inheritance in C++
#include<iostream.h>

// base class for inheritance
class computer
{
float speed;
int main_memory;
int harddisk_memory;

public:
void set_speed(float);
void set_mmemory(int);
void set_hmemory(int);
float get_speed();
int get_mmemory();
int get_hmemory();
};

// -- MEMBER FUNCTIONS --
void computer::set_speed(float sp)
{
speed=sp;
}

void computer::set_mmemory(int m)
{
main_memory=m;
}

void computer::set_hmemory(int h)
{
harddisk_memory=h;
}

int computer::get_hmemory()
{
return harddisk_memory;
}

int computer::get_mmemory()
{
return main_memory;
}

float computer::get_speed()
{
return speed;
}
// -- ENDS --

// inherited class
class laptop:public computer
{
int battery_time;
float weight;

public:
void set_battime(int);
void set_weight(float);
int get_battime();
float get_weight();
};

// -- MEMBER FUNCTIONS --
void laptop::set_battime(int b)
{
battery_time=b;
}

void laptop::set_weight(float w)
{
weight=w;
}

int laptop::get_battime()
{
return battery_time;
}

float laptop::get_weight()
{
return weight;
}
// -- ENDS --

void main(void)
{
computer c;
laptop l;

c.set_mmemory(512);
c.set_hmemory(1024);
c.set_speed(3.60);

// set common features
l.set_mmemory(256);
l.set_hmemory(512);
l.set_speed(1.8);

// set specific features
l.set_battime(7);
l.set_weight(2.6);

// show details of base class object
cout<<"Info. of computer class\n\n";
cout<<"Speed:"<<c.get_speed()<<"\n";
cout<<"Main Memory:"<<c.get_mmemory()<<"\n";
cout<<"Hard Disk Memory:"<<c.get_hmemory()<<"\n";

//show details of derived class object
cout<<"\n\nInfo. of laptop class\n\n";
cout<<"Speed:"<<l.get_speed()<<"\n";
cout<<"Main Memory:"<<l.get_mmemory()<<"\n";
cout<<"Hard Disk Memory:"<<l.get_hmemory()<<"\n";
cout<<"Weight:"<<l.get_weight()<<"\n";
cout<<"Battery Time:"<<l.get_battime()<<"\n";
}

Introduction to Linked Lists Part II

In the previous article Introduction
to Linked Lists
, we introduced the basic concept of linked list. To
make the program (an the article) as simple as possible, we discussed only the
addition and display of nodes in the linked list although necessary we didn't’t
discussed the deletion of node in that article.


In this article we will be discussing about the deletion of nodes from linked
lists.


Deletion of node (elements) from a linked list


The node to be deleted can be represented by many ways but here we will be
representing it by its info. So if we have the following linked list


Linked lists - Deletion of nodes




And we want to delete node1 then we will express it by its info part (i.e. 10).


The main theory behind deletion of nodes is pretty simple. We need to make
the link pointer of the node before the target node (to be deleted) to point
at the node after the target node. Suppose if we wish to delete node having
info as 10 from the above linked list then it will be accomplished as below:


Linked list - Deletion of nodes


Now since node1 is orphan and has no meaning, it can be deleted
to free-up memory as represented below:


Linked lists - node deleted to free-up memory


The following example program illustrates all this. Keep reading
the comments to understand what is happening where!


  // -- Linked Lists --
// ------------------
// Example program in C++
// to illustrate the most simple
// linked list
// NOTE: this program can do three
// operation [adding, deleting,
// and displaying] of data in a
// linked list
#include<iostream.h>

// node class, this will
// represent the nodes or elements
// of the linked list
class node
{
public:
int info;
node *link;
};

// declare global objects
node *start=NULL;

// function prototypes
void add(int inf);
void display(void);
void del(int);

void main(void)
{
int ch;

// input elements
while(ch!=0)
{
cout<<"enter element to be added:";
cout<<"\nenter 0 to stop...\n";
cin>>ch;

if(ch!=0) add(ch);
cout<<"\n\n";
}

ch=-1;

while(ch!=0)
{
cout<<"enter element to be deleted:";
cout<<"\nenter 0 to stop...\n";
cin>>ch;

if(ch!=0) del(ch);
cout<<"\n\n";
}

cout<<"elements are...\n";
display();

// below is a bit confusing
// part.
// here all the nodes that
// we have allocated are
// being freed up
node temp;
while(start!=NULL)
{
// store the next node
// to the one being deleted
temp=*start;
// delete the node
delete start;

// retrieve the next node
// to be deleted
start=temp.link;
}
}

void add(int inf)
{
node *temp1;
node *temp2;

// if the element to be added
// is the first element
if(start==NULL)
{
// allocate a new node
temp1=new node;
temp1->info=inf;
temp1->link=NULL;

// make start point at it
start=temp1;
}
// if not
else
{
temp1=start;

// find out the last element
while(temp1->link!=NULL)
temp1=temp1->link;

// allocate new node
temp2=new node;
temp2->info=inf;
temp2->link=NULL;

// make the last element
// of the list to point
// at the newly created node
temp1->link=temp2;
}
}

void display(void)
{
node *temp;
temp=start;

// traverse or process
// through each element
// and keep printing
// the information
while(temp!=NULL)
{
cout<<temp->info<<endl;
temp=temp->link;
}
}

// this function takes an
// argument which is the info
// of the node to be delted
void del(int num)
{
node *old;
node *target;

target=start;

while(target!=NULL)
{
// if node to be
// delted is found
if(target->info==num)
{
// if node to be deleted
// is the first node
// in the list
if(target==start)
start=target->link;

// if not
else
// then make the node
// prev. to the node
// to be deleted to
// point at the node
// which is after it
old->link=target->link;

// free-up the memory
delete(target);
return;
}
else
{
// traverse through
// each node
old=target;
target=target->link;
}
}
}

Related Articles:


Introduction to Linked Lists

We have been using arrays to store similar data linearly. While arrays are
simple to understand and easy to implement in common situations, they do suffer
from some drawbacks which are listed below:




  • Arrays have fixed dimensions, even if we dynamically allocate the dimension
    it remains constant throughout. So there is a limit to the number of elements
    it can store.




  • Operations such as insertion and deletion are pretty much difficult to
    implement and increases the overhead because these operations require elements
    in the array to be physically shifted.




Linked lists overcome these drawbacks and are commonly used to store linear
data.


Actually elements of linked lists (called as nodes) store two information,
data and the link (pointer) pointing to the next elements (node).


The elements (nodes) are linked sequentially with the help of link pointers.
So we can say that linked lists are collection of nodes which have data and
are linked sequentially so that all the nodes or elements are grouped together.


In programming sense, linked lists are classes whose general form is:


  class node
{
public:
data-type info;
node *link;
};

Here info stores the actual data while link stores the memory
address of the next node, which forms the link between the nodes.


Graphical Representation of a Node of a Linked List

FIG.: Graphical representation of a node


Following figure illustrates the growing of linked lists, the node which has
its link as NULL is the last element in the linked list.


Growing of linked list

FIG.: Linked lists grows like this


Let us now discuss a bit about how a linked list grows:




  1. We have a pointer that stores the memory address of the first element
    in the linked list, represented as the start pointer (of type node). It
    is NULL to begin with as we don’t have any element in the list.




  2. As an element is added, the start pointer is made to point at it and since
    for now the first element is the last element therefore its link is made
    to be NULL




  3. After the addition of each element the link pointer of the previously last
    element is made to point at new last element. This step continues…




In this way the number of nodes in a linked list can grow or shrink over time
as far as memory permits.


Below is the example program that illustrates linked lists. This program is
made as simple as possible and therefore it only performs the basic action (addition
of element) in the linked list.


  // -- Linked Lists --
// ------------------
// Example program in C++
// to illustrate the most simple
// linked list
// NOTE: It is designed so that it
// could only add nodes to the
// list and display them.
#include<iostream.h>

// node class, this will
// represent the nodes or elements
// of the linked list
class node
{
public:
int info;
node *link;
};

// declare global objects
node *start=NULL;

// function prototypes
void add(int inf);
void display(void);

void main(void)
{
int ch;

// input elements
while(ch!=0)
{
cout<<"enter element to be added:";
cout<<"\nenter 0 to stop...\n";
cin>>ch;

if(ch!=0) add(ch);
cout<<"\n\n";
}

cout<<"elements are...\n";
display();

// below is a bit confusing
// part.
// here all the nodes that
// we have allocated are
// being freed up
node temp;
while(start!=NULL)
{
// store the next node
// to the one being deleted
temp=*start;

// delete the node
delete start;

// retrieve the next node
// to be deleted
start=temp.link;
}
}

void add(int inf)
{
node *temp1;
node *temp2;

// if the element to be added
// is the first element
if(start==NULL)
{
// allocate a new node
temp1=new node;
temp1->info=inf;
temp1->link=NULL;

// make start point at it
start=temp1;
}
// if not
else
{
temp1=start;

// find out the last element
while(temp1->link!=NULL)
temp1=temp1->link;

// allocate new node
temp2=new node;
temp2->info=inf;
temp2->link=NULL;

// make the last element
// of the list to point
// at the newly created node
temp1->link=temp2;
}
}

void display(void)
{
node *temp;
temp=start;

// traverse or process
// through each element
// and keep printing
// the information
while(temp!=NULL)
{
cout<<temp->info<<endl;
temp=temp->link;
}
}

Good-Bye!


Related Articles:


Computer Programming: An Article for Beginners

-Article of the Month


You might have read many so-called “the art of computer programming an” and
many “how to …” on computer programming, but this one is different. It doesn't’t
deals with the technical details of programming rather it deals with what is
more important to beginners. This article would help beginners who are having
a tough time with programming to get to the right track.


It is also for newcomers who want to start programming and want to choose the
right programming language. It is not just another guide to learn computer programming;
it helps you to minimize your confusions while learning computer programming.


It is not an article which talks about the history or something like that,
it is a practical guide. This article is written keeping in mind what the beginner’s
confusions are and how to minimize them.


Careers in Computer Programming


As a professional having a degree from any reputed institution you have a good
chance of making a career in computer programming. But as a person having no
formal degree can also earn money by freelancing or by developing and selling
your own software.


There are many sites where peoples place their programming requirements, if
you come across one which you can do in their budget then you can do the programming
to earn money online sitting at home. This is known as freelancing, which has
grown up as a good career in computer programming.


You can also develop software yourself and sell them online to earn money;
there are many ways by which you can do this. It is so amazing, think of developing
your very own software, games and even selling them. But before you sell you
have to develop the software! Yes it is tough and at times it feels ridiculous
but believe me, as you become more and more used to it, you’ll feel very comfortable
using it.


I have a habit questioning myself-“How did they do that?” whenever I come across
any unique software. That helps me a lot. There are a lot of examples of small
developers who have made their career in computer programming by developing
software which they are selling to earn money. One of the common things among
them is that their software was worth selling.


Computer Programming Languages


Communicating with a computer involves speaking the language the computer understands,
which immediately rules out English as the language of communication with computer.
However, there is a close analogy between learning any language (like English,
French etc.) and learning computer programming language.


The classical method of learning any language is to first learn the alphabets
or characters used in the language, then learn to combine these alphabets to
form sentences and sentences are combined to form paragraphs. Learning programming
languages is similar and much easier.


Therefore, instead of straight-away learning how to write programs, we must
first know how alphabets, numbers and special symbols are used in the programming
language, then how using these, instructions are constructed.


A group of instruction would be combined later on to form a program. There
are many programming languages in the world. Many of them are used for specific
purposes. While there are many programming languages, here is a list of programming
languages that can be used for everyday programming:-




  • C++




  • C




  • C#




  • Pascal




  • Fortran




  • Basic




  • PHP




All the programming languages can be divided into two categories:


Problem oriented languages or High-level languages: These
languages have been designed to give a better programming efficiency, i.e. faster
program development. Examples of languages falling in this category are FORTRAN,
BASIC etc.


Machine oriented languages or Low-level programming languages:
These languages have been designed to give a better machine efficiency, i.e.
faster program execution. Examples of programming languages falling in this
category are Assembly Language and Machine Language.


Few languages such as C++ stands in between these two categories. That’s why
it is often called a Middle level language, since it was designed to have both:
a relatively good programming efficiency (as compared to Machine oriented languages)
and relatively good machine efficiency (as compared to Problem oriented languages).


For a newcomer BASIC is well-suited, there are also some windows compilers
available, but for serious programming, C++ is the STANDARD.


C++ is one of the most widely-used programming languages. It is often considered
to be the industry-standard language for game development, but is also very
often used to write other types of computer software applications.


There are many C++ compilers including free compilers available. For a person
who doesn't’t knows what programming is all about, should always first play
with LOGO for sometime before jumping on to some other ‘serious’ programming
language.


When you experiment with LOGO you get the understanding of how a computer interacts
with the commands entered by the user, what parameters are and all the other
minor details that are common to most of the programming languages. This helps
in gaining knowledge as well as confidence which further helps in learning other
‘serious’ programming languages.


With LOGO you might not be able to do many things but it would definitely increase
your understanding and would sharpen your logic.


Here is the list of steps that you should take or avoid while
learning computer programming


Do's




  • When you’ll first start programming may be things will not make much sense
    to you but stick with it and do more learning. Take the help of books and
    tutorials.




  • There are many books on mind twisting problems, try to solve tem by your
    own, that makes you sharp.




  • Always write down the program in paper(preferably in a note-book) before
    feeding it to the computer because it doesn't’t makes sense to me to write
    the program before the Pc, all the thinking should be done and written beforehand.
    This increases your productivity. Writing algorithms before programming
    will help.




  • Only reading the codes of the program written by someone else will not
    help. You have to solve problems by your own to make a good grip over computer
    programming.




  • Think carefully when debugging because it’s only you, who could make mistake.
    Remember never to blame the computer.




  • The easiest thing to do is to give-up thinking that ‘every thing in this
    world is not for everyone’. Keep in mind that nothing seems to be simple
    in the starting, what you have to do is to stick with it and practice more,
    read more and understand more.




  • In the beginning peoples usually make the mistake of downloading complicated
    source codes from the internet to see how they work, and obviously understand
    nothing. Always see simple codes in the starting, it is better to have a
    book and proceed with the source codes chapter-wise.




Don'ts




  • Never ever mind buying books, they are the biggest source of knowledge;
    you have the opportunity to learn the art of computer programming from the
    top experts from all over the world. And for 10$ or 20$ or maybe 30$ it
    is worth it if you gain something.




  • In the starting don’t give much stress to complicated problems; it’ll only
    make you more confused, always proceed chapter-wise.




  • Don’t forget to ask in forums etc about your problems and confusions, there
    are many forums which will give you prompt replies.




  • Don’t overdo it, always take rest.




  • Peoples have a bad habit of running a program too many times before it
    successfully runs, don’t run the program every time you make minor changes,
    do all the debugging or at least many of them then only run it.




  • Don’t loose heart when you can’t do complicated problems leave it, try
    some other less difficult programs then come back to it. Remember, practice
    is everything.




Action Steps to learn computer programming




  1. If you know the basic concepts of programming then you may skip this step
    .Download LOGO (from http://www.softronix.com/), also search for LOGO tutorials
    and download some tutorials. Read and understand them. Experiment with LOGO
    until you feel comfortable with the basic concepts of programming. Some
    books will come handy, tutorials are recommended. The help included with
    MSW LOGO is also very good.This might take anywhere from a few weeks to
    a few months for you to feel comfortable with the concepts.




  2. The next step should be to choose a ‘serious’ programming language in which
    real world applications can be developed. You can experiment with BASIC
    for some time to get a grip over it and then use Visual Basic to develop
    real world applications.But according to me the best choice of programming
    language is C++. As said earlier most of the application software (including
    games) are developed using C++ language.




  3. After you master any programming language (that means you are able to understand
    programs written in that programming language). Now you should have a book
    on projects in that language in which source codes of various small applications
    are given. Try to see and understand how the programmers solve problems
    faced by you and what techniques they use. This helps very much in learning
    the art of computer programming. It’s the technique and art that makes you
    or anybody else a good programmer. This step is very much essential for
    you to develop real world applications. Only learning computer programming
    language won’t help you do anything serious. You have to learn the techniques
    of programming, because knowing any language and using it to develop something
    worthwhile is totally different thing.You can also download source code
    of any open-source applications from the internet. But remember that source
    codes from the internet are often with good documentation.



  4. Peoples learn computer programming to develop application software, therefore
    this step is also very important although it doesn't’t help you learn computer
    programming, rather it helps you to implement your knowledge. Remember that
    the previous step is an ongoing process, there is no limit to learning , you
    should always keep your mind open to the new techniques which you come across.
    After understanding some of the techniques you would start feeling confident.
    Now what you need is just an idea that you you to materialize. Keep thinking
    wherever you can show your knowledge until you have an idea of the type of
    application you would like to develop. When you have an idea, put all your
    knowledge, all your effort and all that you have learnt so far.And remember
    never to give-up, sometimes it feels just too complicated but ‘real programmers’
    never give-up.


This is it for now!


Hope you like this long article!


Good-Bye!

Introduction to C++ Preprocessor Directives

As the name suggest, C++ Preprocessor is an integrated program in C++ that
preprocesses every program we write before compilation.


Preprocessor commands or directives are special functions that are executed
or processed before the compilation of the program.


Although we can write program without the knowledge of preprocessor directives
but why underutilize features when we have them?


Every preprocessor directive starts with a # symbol. While
we can have them anywhere in the program but they are almost always used at
the starting of the program before any function is defined.


Knowingly or unknowingly, we have been using one preprocessor directive. It
is the #include directive, which is most commonly used to include
header files in the program.


While there are many types of preprocessor directives, here we will only be
discussing about Macro Expansion directives and that also in the simplest sense!


Macro Expansion Directives


Have a look at the code below:


  #define MAX 10
cout<<MAX;

Here, MAX is known as ‘Macro Template’ and 10,
Macro Expansion’.


Upon preprocessing every instance of the word MAX is replaced with 10 and only
then is the program executed.


It is just like search and replace, in which every word defined as macro template
(in this case MAX) is replaced by the corresponding macro expansion (in this
case 10).


It is the common way of defining constants that doesn’t needs to be change
throughout.


A few points to note:




  • Please note that it is necessary not to end directives with semicolon (;).




  • While it is not necessary to use ALL-CAPS for macro template but it has
    become the standard.




Below is a simple example program that illustrates macro expansion directives:


  // example program in c++ to show
// the use of macro directives
#include<iostream.h>
// below is the macro, which can be
// changed to change the behaviour
// of the whole program
// DON'T END WITH ';'
#define MAX 3

void main(void)
{
int arr[MAX];
int i;

cout<<"enter elements of the array:";
for(i=0;i<MAX;i++)
cin>>arr[i];

cout<<"elements are:";
for(i=0;i<MAX;i++)
cout<<"\n"<<i<<":"<<arr[i];
}

Good-Bye!


Related Articles:


Introduction to Dynamic Memory Allocation in C++

Suppose you are making a C++ program to store a particular number (specified
by the user at runtime) of phone numbers. What will you do? You cannot declare
array of 10 or 20 elements because you don’t know how many numbers the
user will enter. He may want to enter 1, 10 or even 100 phone numbers.


So what will you do?


Actually, you can do two things to achieve this, that are listed below:




  1. You can create a very large int(eger) array (say, of 500 elements) , in
    this case whether the user wants to store 1 or 500 phone numbers, the memory
    used will always be the same (large!).




  2. You can make use of C++’s dynamic memory allocation to allocate only
    the needed amount of memory.




The first choice is a very bad way of programming, nevertheless it works fine,
you should never employ such an inefficient method of programming.


So, you are left with only one choice to use the Dynamic Memory Allocation
of C++ programming language, that I will be discussing in this article.


As is clear from the above example, dynamic memory allocation is needed when
you don’t know the program’s memory needs beforehand.


Allocating Memory


Dynamic memory is allocated by the new keyword. Memory for
one variable is allocated as below:


ptr=new DataType (initializer);

Here,




  • ptr is a valid pointer of type DataType.




  • DataType is any valid c++ data type.




  • Initializer (optional) if given, the newly allocated variable is initialized
    to that value.




Ex.


  //Example Program in C++
#include<iostream.h>

void main(void)
{
int *ptr;
ptr=new int(10);


cout<<*ptr;

delete ptr;
}

This is will allocate memory for an int(eger) having initial value 10, pointed
by the ptr pointer.


Memory space for arrays is allocated as shown below:


ptr=new DataType [x];

Here,




  • ptr and DataType have the same meaning as above.




  • x is the number of elements and C is a constant.




Ex.


  //Example Program in C++
#include<iostream.h>

void main(void)
{
int *ptr, size;

cin>>size;
ptr=new int[size];

//arrays are freed-up like this
delete []ptr;
}

Freeing-Up Allocated Memory


Unlike static variables, c++ will not free-up the memory allocated through
dynamic allocation. Its your duty to free them up. delete keyword
is used to free-up the allocated memory.


delete ptr;

Arrays are deleted in a slightly different manner as shown below:


delete []ptr;

It’s easy to forget to free the allocated memory because C++ compiler
won’t inform you that you are doing this. It’s your job and should
always be done.


Now let me show you an example of dynamic memory allocation in action:


  //Example Program in C++
#include<iostream.h>

void main(void)
{
int *ptr, size;

cout<<"How many PH. Numbers do you wish to enter:";
cin>>size;
ptr=new int[size];//allocate memory

//input ph. numbers
for (int i=0;i<size;i++)
{
cout<<"Enter PH. NO."<<i+1<<" :";
cin>>ptr[i];
}

//output ph. numbers
cout<<"\n\n\n PH. NOs. are\n";
for (i=0;i<size;i++)
cout<<"\nPH. NO."<<i+1<<" :"<<ptr[i];

cout<<endl;

delete []ptr;//free-up memory
}

Good-Bye!


Related Articles:


Introduction to Constructor and Destructor functions of a Class

Constructor and Destructor functions are Member Functions of a class having
some special property.


Constructor function gets invoked when an object of a class is constructed
(declared) and destructor function gets invoked when the object is destructed
(goes out of scope).


Use of Constructor and Destructor function of a class




  • Constructor function is used to initialize member variables to pre-defined
    values as soon as an object of a class is declared.




  • Constructor function having parameters is used to initialize the data members
    to the values passed values, upon declaration.




  • Generally, the destructor function is needed only when constructor has
    allocated dynamic memory.





Defining Constructor and Destructor functions


The example below illustrates how constructor and destructor functions are
defined:


  class myclass
{
private:
int number;

public:
myclass()//constructor
{
number=10;
}

~myclass()//destructor
{
//nothing needed
}
};

A few points to note:




  • Both of the functions have the same name as that of the class, destructor
    function having (~) before its name.




  • Both constructor and destructor functions should not be preceded by any
    data type (not even void).




  • These functions do not (and cannot) return any values.




  • We can have only the constructor function in a class without destructor
    function or vice-versa.




  • Constructor function can take arguments but destructors cannot.




  • Constructor function can be overloaded as usual functions.




Example 1: Using constructor function to initialize data members
to pre-defined values


  //Example Program in C++
#include<iostream.h>

class myclass
{
private:
int a;
int b;

public:
myclass()
{
//here constructor function is used to
//initialize data members to pre-def
//values
a=10;
b=10;
}

int add(void)
{
return a+b;
}
};

void main(void)
{
myclass a;

cout<<a.add();
}

Example 2: Using constructor function to initialize data members
to values passed as arguments


  //Example Program in C++
#include<iostream.h>

class myclass
{
private:
int a;
int b;

public:
myclass(int i, int j)
{
a=i;
b=j;
}

int add(void)
{
return a+b;
}
};

void main(void)
{
//notice how the object of the class
//has been declared
//it can be thought as
// myclass a;
// a=myclass(10,20)
myclass a(10,20);

cout<<a.add();
}

Notice that there is no destructor function in both the examples, just because
we don’t need them.


I will discuss destructor functions in detail in the coming articles.


So, keep checking!


Related Articles:


Introduction to Function Overloading in C++

Let us start this with a question!


All of you know that we cannot have two variables of the same name, but can
we have two Functions having the same name.


The answer is YES, we can have two functions of the same name by a method known
as function overloading and the functions having the same name are known as
overloaded functions.


So, what’s the use of Function Overloading


Function overloading is one of the most powerful features of C++ programming
language. It forms the basis of polymorphism (compile-time polymorphism).


Most of the time you’ll be overloading the constructor function of a
class.


How function overloading is achieved


One thing that might be coming to your mind is, how will the compiler know
when to call which function, if there are more than one function of the same
name.


The answer is, you have to declare functions in such a way that they differ
either in terms of the number of parameters or in terms of the type of parameters
they take.


What that means is, nothing special needs to be done, you just need to declare
two or more functions having the same name but either having different number
of parameters or having parameters of different types.


Example 1: Overloading Functions that differ in terms of NUMBER
OF PARAMETERS


  //Example Program in C++
#include<iostream.h>

//FUNTION PROTOTYPES
int func(int i);
int func(int i, int j);

void main(void)
{
cout<<func(10);//func(int i)is called

cout<<func(10,10);//func(int i, int j) is called
}

int func(int i)
{
return i;
}

int func(int i, int j)
{
return i+j;
}

Example 2: Overloading Functions that differ in terms of TYPE
OF PARAMETERS


  //Example Program in C++
#include<iostream.h>

//FUNTION PROTOTYPES
int func(int i);
double func(double i);

void main(void)
{
cout<<func(10);//func(int i)is called

cout<<func(10.201);//func(double i) is called
}

int func(int i)
{
return i;
}

double func(double i)
{
return i;
}

One more Question, is the program below, valid?


  //Example Program in C++
#include<iostream.h>

//FUNTION PROTOTYPES
int func(int i);
double func(int i);

void main(void)
{
cout<<func(10);

cout<<func(10.201);
}

int func(int i)
{
return i;
}

double func(int i)
{
return i;
}

No, because you can’t overload functions if they differ only in terms
of the data type they return.


I Hope this article throws some light on function overloading!


Good-Bye for now


Thanks for reading…


Do check back for updates!


Related Articles:


Introduction to Classes in C++

Classes are the building blocks of Object Oriented Programming in C++ language.
Class gives us the ability to simplify certain types of programs by creating
objects that forms the basis of Object Oriented programming.


Just like identifiers of built-in data types (ex. int, char etc.) are known
as variables similarly identifiers (instances) of class are known as Objects.


Classes in C++ have two parts, data and functions; these are known as data
members and member function respectively. Member functions are usually the means
of accessing and modifying data members.


Anything inside the class can be either private to the class or public to the
program. Classes may have both type of members (private and public) at the same
time.


General form of Class:


  class class_name
{
access-specifier:
member…
member…
member…

access-specifier:
member…
member…
member…
}object-list;

Few points to remember:




  • Access-specifier can be anyone of the three private, public and protected.




  • Anything after an access-specifier has that type of access until another
    access-specifier is encountered.




  • There can be any number of access-specifier, but in general all the members
    having same access are grouped together under one access-specifier.




  • So,




    class c1
    {
    private;
    int a;
    int b;

    public:
    int c;

    private:
    int d;
    };

    Should be written as


    class c1
    {
    private:
    int a;
    int b;
    int d;

    public:
    int c;
    };


  • Object list is optional which is used to declare objects of the class.


private and public Access-Specifiers


private tells the compiler that the members following it are private to the
class and can not be accessed by other parts of the program.


Ex.




class c1
{
private:
int a;
int b;
void func();
};

Here, the variable a, b and function func() can can only be accessed by the
members of the class c1.


On the other hand, public members are accessible to the other parts of the
program also.




class c1
{
private:
int a;
int b;
void func();

   public:
void func2();
int c;
}obj;

Here the variable c and function func2() are accessible from other parts of
the program, but the private members are only accessible from the public function
func2().


The public members of the class (i.e. func2() and c) can be accessed from other
parts of the program with the help of the following syntax:


obj.c=10;


functions (public) are also accessed like this:


obj.func2();


A few points to remember:




  • Please note that in the previous example a, b and func() can not be accessed
    from other parts of the program with the help of (.) operator.




  • Member functions can simply access any of the private and public members
    of the class without the use of (.) operator.




  • For example, if func2() is a member function class c2 then it can access
    other members (both private and public) as shown below:


    func2()
    {
    a=b;
    b=c;
    func();
    }



Enough talking…

Now let us move on to a simple program to illustrate:




  • How to define a class and its objects in C++.




  • Use of private and public access-specifiers.




  • How to define and use member functions.




  //C++ Program
#include<stdio.h>
#include<iostream.h>

class employee
{
private:
char name[30];
int emp_no,age;
float salary, net_salary, tax;
void calculate()//in line function
//used for the short ones
{
net_salary=salary-tax;
}

public:
void input();
void output();
};

//----FUNCTION DEFINITION STARTS----
void employee::input()
{
printf("Enter Name: ");
gets(name);
printf("Enter Employee Number: ");
cin>>emp_no;
printf("Enter Age: ");
cin>>age;
printf("Enter Salary: ");
cin>>salary;
printf("Enter Tax Paid: ");
cin>>tax;

//the function below can only be invoked
//from the member function like here
//and not from the other parts of the program
calculate();
}

void employee::output()
{
printf("\n\n EMPLOYEE DETAILS\n");
//'\n' is used to print to the next line
printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("Employee Number: %d\n", emp_no);
printf("Net Salary: %f\n", net_salary);
}
//----FUNCTION DEFINTION ENDS----

void main()
{
employee e1;

e1.input();
e1.output();
}

A few points about the program:




  • Notice how member functions are used to modify data members of the class.




  • Notice the use of private function calculate(), that can only be accessed
    from other member function (i.e. input() and output()).




  • Notice how the member functions are declared and defined.






This article has gone a bit too long but once the discussion on topics like
classes in C++ starts it never seems to end -;)


Good-bye for now!

Check out this stream