0% found this document useful (0 votes)
66 views

When We Consider A C

The document discusses key concepts in C++ including classes, objects, methods, and variables. It then provides an example "Hello World" C++ program and explains each part of the program code. Finally, it covers additional C++ concepts such as data types, comments, variables, and more.

Uploaded by

Khisrav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

When We Consider A C

The document discusses key concepts in C++ including classes, objects, methods, and variables. It then provides an example "Hello World" C++ program and explains each part of the program code. Finally, it covers additional C++ concepts such as data types, comments, variables, and more.

Uploaded by

Khisrav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

When we consider a C++ program, it can be defined as a collection of

objects that communicate via invoking each other's methods. Let us now
briefly look into what do class, object, methods and Instance variables
mean.

 Object - Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behaviors - wagging, barking, eating. An object is an
instance of a class.

 Class - A class can be defined as a template/blueprint that describes the


behaviors/states that object of its type support.

 Methods - A method is basically a behavior. A class can contain many methods.
It is in methods where the logics are written, data is manipulated and all the
actions are executed.

 Instance Variables - Each object has its unique set of instance variables. An
object's state is created by the values assigned to these instance variables.

C++ Program Structure:


Let us look at a simple code that would print the words Hello World.

#include <iostream>
using namespace std;

// main() is where program execution begins.

int main()
{
cout << "Hello World"; // prints Hello World
return 0;
}

Let us look various parts of the above program:

 The C++ language defines several headers, which contain information that is
either necessary or useful to your program. For this program, the
header <iostream> is needed.
 The line using namespace std; tells the compiler to use the std namespace.
Namespaces are a relatively recent addition to C++.

 The next line // main() is where program execution begins. is a single-line


comment available in C++. Single-line comments begin with // and stop at the
end of the line.

 The line int main() is the main function where program execution begins.

 The next line cout << "This is my first C++ program."; causes the message
"This is my first C++ program" to be displayed on the screen.

 The next line return 0; terminates main( )function and causes it to return the
value 0 to the calling process.

Compile & Execute C++ Program:


Let's look at how to save the file, compile and run the program. Please
follow the steps given below:

 Open a text editor and add the code as above.

 Save the file as: hello.cpp

 Open a command prompt and go to the directory where you saved the file.

 Type 'g++ hello.cpp ' and press enter to compile your code. If there are no
errors in your code the command prompt will take you to the next line and
would generate a.out executable file.

 Now, type ' a.out' to run your program.

 You will be able to see ' Hello World ' printed on the window.

$ g++ hello.cpp
$ ./a.out
Hello World

Make sure that g++ is in your path and that you are running it in the
directory containing file hello.cpp.

You can compile C/C++ programs using makefile. For more details, you can
check Makefile Tutorial.
Semicolons & Blocks in C++:
In C++, the semicolon is a statement terminator. That is, each individual
statement must be ended with a semicolon. It indicates the end of one
logical entity.

For example, following are three different statements:

x = y;
y = y+1;
add(x, y);

A block is a set of logically connected statements that are surrounded by


opening and closing braces. For example:

{
cout << "Hello World"; // prints Hello World
return 0;
}

C++ does not recognize the end of the line as a terminator. For this reason,
it does not matter where on a line you put a statement. For example:

x = y;
y = y+1;
add(x, y);

is the same as

x = y; y = y+1; add(x, y);

C++ Identifiers:
A C++ identifier is a name used to identify a variable, function, class,
module, or any other user-defined item. An identifier starts with a letter A
to Z or a to z or an underscore (_) followed by zero or more letters,
underscores, and digits (0 to 9).

C++ does not allow punctuation characters such as @, $, and % within


identifiers. C++ is a case-sensitive programming language.
Thus, Manpowerand manpower are two different identifiers in C++.

Here are some examples of acceptable identifiers:


mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal

C++ Keywords:
The following list shows the reserved words in C++. These reserved words
may not be used as constant or variable or any other identifier names.

asm else new this

auto enum operator throw

bool explicit private true

break export protected try

case extern public typedef

catch false register typeid

char float reinterpret_cast typename

class for return union

const friend short unsigned

const_cast goto signed using

continue if sizeof virtual

default inline static void

delete int static_cast volatile

do long struct wchar_t


double mutable switch while

dynamic_cast namespace template  

Trigraphs:
A few characters have an alternative representation, called a trigraph
sequence. A trigraph is a three-character sequence that represents a single
character and the sequence always starts with two question marks.

Trigraphs are expanded anywhere they appear, including within string


literals and character literals, in comments, and in preprocessor directives.

Following are most frequently used trigraph sequences:

Trigraph Replacement

??= #

??/ \

??' ^

??( [

??) ]

??! |

??< {

??> }

??- ~

All the compilers do not support trigraphs and they are not advised to be
used because of their confusing nature.
Whitespace in C++:
A line containing only whitespace, possibly with a comment, is known as a
blank line, and C++ compiler totally ignores it.

Whitespace is the term used in C++ to describe blanks, tabs, newline


characters and comments. Whitespace separates one part of a statement
from another and enables the compiler to identify where one element in a
statement, such as int, ends and the next element begins. Therefore, in the
statement,

int age;

there must be at least one whitespace character (usually a space) between


int and age for the compiler to be able to distinguish them. On the other
hand, in the statement

fruit = apples + oranges; // Get the total fruit

no whitespace characters are necessary between fruit and =, or between =


and apples, although you are free to include some if you wish for readability
purpose.

Program comments are explanatory statements that you can include in the
C++ code that you write and helps anyone reading it's source code. All
programming languages allow for some form of comments.

C++ supports single-line and multi-line comments. All characters available


inside any comment are ignored by C++ compiler.

C++ comments start with /* and end with */. For example:

/* This is a comment */

/* C++ comments can also


* span multiple lines
*/

A comment can also start with //, extending to the end of the line. For
example:
#include <iostream>
using namespace std;

main()
{
cout << "Hello World"; // prints Hello World

return 0;
}

When the above code is compiled, it will ignore // prints Hello World and
final executable will produce the following result:

Hello World

Within a /* and */ comment, // characters have no special meaning. Within


a // comment, /* and */ have no special meaning. Thus, you can "nest" one
kind of comment within the other kind. For example:

/* Comment out printing of Hello World:

cout << "Hello World"; // prints Hello World

*/

While doing programming in any programming language, you need to use


various variables to store various information. Variables are nothing but
reserved memory locations to store values. This means that when you
create a variable you reserve some space in memory.

You may like to store information of various data types like character, wide
character, integer, floating point, double floating point, boolean etc. Based
on the data type of a variable, the operating system allocates memory and
decides what can be stored in the reserved memory.

Primitive Built-in Types:


C++ offer the programmer a rich assortment of built-in as well as user
defined data types. Following table lists down seven basic C++ data types:

Type Keyword

Boolean bool

Character char

Integer int

Floating point float

Double floating point double

Valueless void

Wide character wchar_t

Several of the basic types can be modified using one or more of these type
modifiers:

 signed

 unsigned

 short

 long

The following table shows the variable type, how much memory it takes to
store the value in memory, and what is maximum and minimum value
which can be stored in such type of variables.

Type Typical Bit Width Typical Range

char 1byte -128 to 127 or 0 to 255


unsigned char 1byte 0 to 255

signed char 1byte -128 to 127

int 4bytes -2147483648 to 2147483647

unsigned int 4bytes 0 to 4294967295

signed int 4bytes -2147483648 to 2147483647

short int 2bytes -32768 to 32767

unsigned short int 2bytes 0 to 65,535

signed short int 2bytes -32768 to 32767

long int 4bytes -2,147,483,648 to 2,147,483,647

signed long int 4bytes -2,147,483,648 to 2,147,483,647

unsigned long int 4bytes 0 to 4,294,967,295

float 4bytes +/- 3.4e +/- 38 (~7 digits)

double 8bytes +/- 1.7e +/- 308 (~15 digits)

long double 8bytes +/- 1.7e +/- 308 (~15 digits)

wchar_t 2 or 4 bytes 1 wide character

The sizes of variables might be different from those shown in the above
table, depending on the compiler and the computer you are using.

Following is the example, which will produce correct size of various data
types on your computer.
#include <iostream>
using namespace std;

int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}

This example uses endl, which inserts a new-line character after every line
and << operator is being used to pass multiple values out to the screen.
We are also using sizeof() operator to get size of various data types.

When the above code is compiled and executed, it produces the following
result which can vary from machine to machine:

Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 8
Size of float : 4
Size of double : 8
Size of wchar_t : 4

typedef Declarations:
You can create a new name for an existing type using typedef. Following is
the simple syntax to define a new type using typedef:

typedef type newname;

For example, the following tells the compiler that feet is another name for
int:
typedef int feet;

Now, the following declaration is perfectly legal and creates an integer


variable called distance:

feet distance;

Enumerated Types:
An enumerated type declares an optional type name and a set of zero or
more identifiers that can be used as values of the type. Each enumerator is
a constant whose type is the enumeration.

To create an enumeration requires the use of the keyword enum. The


general form of an enumeration type is:

enum enum-name { list of names } var-list;

Here, the enum-name is the enumeration's type name. The list of names is
comma separated.

For example, the following code defines an enumeration of colors called


colors and the variable c of type color. Finally, c is assigned the value
"blue".

enum color { red, green, blue } c;


c = blue;

By default, the value of the first name is 0, the second name has the value
1, the third has the value 2, and so on. But you can give a name a specific
value by adding an initializer. For example, in the following
enumeration, green will have the value 5.

enum color { red, green=5, blue };

Here, blue will have a value of 6 because each name will be one greater


than the one that precedes it.
Structure of a program
The best way to learn a programming language is by writing programs. Typically, the first program
beginners write is a program called "Hello World", which simply prints "Hello World" to your computer
screen. Although it is very simple, it contains all the fundamental components C++ programs have:

1 // my first program in C++ Hello World! Edit


2 #include <iostream> &
3 Run
4 int main()
5{
6 std::cout << "Hello World!";
7}

The left panel above shows the C++ code for this program. The right panel shows the result when the
program is executed by a computer. The grey numbers to the left of the panels are line numbers to
make discussing programs and researching errors easier. They are not part of the program.

Let's examine this program line by line:

Line 1: // my first program in C++


Two slash signs indicate that the rest of the line is a comment inserted by the programmer but
which has no effect on the behavior of the program. Programmers use them to include short
explanations or observations concerning the code or program. In this case, it is a brief
introductory description of the program.

Line 2: #include <iostream>

Lines beginning with a hash sign (#) are directives read and interpreted by what is known as
the preprocessor. They are special lines interpreted before the compilation of the program itself
begins. In this case, the directive#include <iostream>, instructs the preprocessor to include
a section of standard C++ code, known as header iostream, that allows to perform standard
input and output operations, such as writing the output of this program (Hello World) to the
screen.

Line 3: A blank line.

Blank lines have no effect on a program. They simply improve readability of the code.

Line 4: int main ()

This line initiates the declaration of a function. Essentially, a function is a group of code
statements which are given a name: in this case, this gives the name "main" to the group of
code statements that follow. Functions will be discussed in detail in a later chapter, but
essentially, their definition is introduced with a succession of a type ( int), a name (main) and a
pair of parentheses (()), optionally including parameters.

The function named main is a special function in all C++ programs; it is the function called when
the program is run. The execution of all C++ programs begins with the main function, regardless
of where the function is actually located within the code.

Lines 5 and 7: { and }

The open brace ({) at line 5 indicates the beginning of main's function definition, and the
closing brace (}) at line 7, indicates its end. Everything between these braces is the function's
body that defines what happens when main is called. All functions use braces to indicate the
beginning and end of their definitions.

Line 6: std::cout << "Hello World!";

This line is a C++ statement. A statement is an expression that can actually produce some effect.
It is the meat of a program, specifying its actual behavior. Statements are executed in the same
order that they appear within a function's body.

This statement has three parts: First, std::cout, which identifies


the standard character output device (usually, this is the computer screen). Second, the
insertion operator (<<), which indicates that what follows is inserted into std::cout. Finally, a
sentence within quotes ("Hello world!"), is the content inserted into the standard output.

Notice that the statement ends with a semicolon ( ;). This character marks the end of the
statement, just as the period ends a sentence in English. All C++ statements must end with a
semicolon character. One of the most common syntax errors in C++ is forgetting to end a
statement with a semicolon.

You may have noticed that not all the lines of this program perform actions when the code is executed.
There is a line containing a comment (beginning with //). There is a line with a directive for the
preprocessor (beginning with #). There is a line that defines a function (in this case, the main function).
And, finally, a line with a statements ending with a semicolon (the insertion into cout), which was
within the block delimited by the braces ( { } ) of the main function. 

The program has been structured in different lines and properly indented, in order to make it easier to
understand for the humans reading it. But C++ does not have strict rules on indentation or on how to
split instructions in different lines. For example, instead of 

1 int main () Edit & Run


2{
3 std::cout << " Hello World!";
4}

We could have written:


  int main () { std::cout << "Hello World!"; } Edit & Run

all in a single line, and this would have had exactly the same meaning as the preceding code.

In C++, the separation between statements is specified with an ending semicolon ( ;), with the
separation into different lines not mattering at all for this purpose. Many statements can be written in a
single line, or each statement can be in its own line. The division of code in different lines serves only to
make it more legible and schematic for the humans that may read it, but has no effect on the actual
behavior of the program.

Now, let's add an additional statement to our first program:

1 // my second program in C++ Hello World! I'm a C++ program Edit


2 #include <iostream> &
3 Run
4 int main ()
5{
6 std::cout << "Hello World! ";
7 std::cout << "I'm a C++ program";
8}

In this case, the program performed two insertions into std::cout in two different statements. Once
again, the separation in different lines of code simply gives greater readability to the program,
since main could have been perfectly valid defined in this way:

  int main () { std::cout << " Hello World! "; std::cout << " I'm a C++ Edit &
program "; } Run

The source code could have also been divided into more code lines instead:

1 int main () Edit & Run


2{
3 std::cout <<
4 "Hello World!";
5 std::cout
6 << "I'm a C++ program";
7}

And the result would again have been exactly the same as in the previous examples.
Preprocessor directives (those that begin by #) are out of this general rule since they are not statements.
They are lines read and processed by the preprocessor before proper compilation begins. Preprocessor
directives must be specified in their own line and, because they are not statements, do not have to end
with a semicolon (;).

Comments
As noted above, comments do not affect the operation of the program; however, they provide an
important tool to document directly within the source code what the program does and how it
operates.

C++ supports two ways of commenting code:

1 // line comment
2 /* block comment */

The first of them, known as line comment, discards everything from where the pair of slash signs ( //)
are found up to the end of that same line. The second one, known as block comment, discards
everything between the /* characters and the first appearance of the */ characters, with the possibility
of including multiple lines.

Let's add comments to our second program: 

1 /* my second program in C++ Hello World! I'm a C++ program Edit


2 with more comments */ &
3 Run
4 #include <iostream>
5
6 int main ()
7{
8 std::cout << "Hello World! "; // prints Hello
9 World!
10 std::cout << "I'm a C++ program"; // prints I'm a
C++ program
}

If comments are included within the source code of a program without using the comment characters
combinations //,/* or */, the compiler takes them as if they were C++ expressions, most likely causing
the compilation to fail with one, or several, error messages.

Using namespace std


If you have seen C++ code before, you may have seen cout being used instead of std::cout. Both
name the same object: the first one uses its unqualified name (cout), while the second qualifies it
directly within the namespace std (asstd::cout).

cout is part of the standard library, and all the elements in the standard C++ library are declared within
what is called anamespace: the namespace std.

In order to refer to the elements in the std namespace a program shall either qualify each and every
use of elements of the library (as we have done by prefixing cout with std::), or introduce visibility of
its components. The most typical way to introduce visibility of these components is by means of using
declarations:

  using namespace std;

The above declaration allows all elements in the std namespace to be accessed in


an unqualified manner (without thestd:: prefix).

With this in mind, the last example can be rewritten to make unqualified uses of cout as:
1 // my second program in C++ Hello World! I'm a C++ program Edit
2 #include <iostream> &
3 using namespace std; Run
4
5 int main ()
6{
7 cout << "Hello World! ";
8 cout << "I'm a C++ program";
9}

Both ways of accessing the elements of the std namespace (explicit qualification


and using declarations) are valid in C++ and produce the exact same behavior. For simplicity, and to
improve readability, the examples in these tutorials will more often use this latter approach
with using declarations, although note that explicit qualification is the only way to guarantee that name
collisions never happen.

Namespaces are explained in more detail in a later chapter.

You might also like