Sei sulla pagina 1di 14

Chapter 1: Introduction to C++

In this chapter, you will learn about the C++ programming language, its features, and the concept of classes.

Introducing C++
C++ was developed by Bjarne Stroustrup at Bell Labs in early 1980s. C++ was originally known as C with classes because it was a superset of the C language. It has object-oriented features, in addition to all the functionality of the C language. One major difference between C# and C++ is that C# is a pure Object-Oriented Programming (OOP) language because every statement in C# is written inside a class whereas in C++ you can write a program with or without classes. Both C# and C++ are case-sensitive programming languages.

Creating Programs
In order to perform specific tasks on a computer, you need to write a set of instructions. These instructions are known as programs and are written in a specific computer language. While creating a program, you may need to temporarily store some values. These values can be stored by using a variable. For example, if you want to create a program that accepts two numbers from the user and displays their sum on the screen, you need to temporarily store the numbers and then add these numbers.

Variables and Data Types


A variable is a location in memory that has a name and is used to temporarily store a value. The value can be an integer value, a decimal value, or a character value. Consider the same example of a program that accepts two numbers from the user and adds them. In this example, the numbers
open in browser PRO version
Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

pdfcrowd.com

entered by the user are stored in two variables. The following figure shows the process of storing the user input in the memory by using variables.

In the preceding figure, the user enters 5 and 3 as input. The digit 5 is stored in the variable Num1, and digit 3 is stored in the variable Num2. To use a variable in a program, you need to declare it to inform the compiler about the name of the variable that will be used and the type of value that it will hold. The syntax to declare a variable is:
<data type> <variable name>;

Note There exist certain set of rules that govern the naming of variables in C++. These rules are similar to the rules followed in C#.

Let's Practice I
open in browser PRO version
Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

pdfcrowd.com

1. Identify the valid variable names from the following list: a. 1address b. address1 c. employee_name d. basic#salary e. long f. this_variable_name_is_very_long In addition to the name, a variable must be declared by specifying its data type. A data type defines the type of data that can be stored in a variable. For example, a variable called name will ideally store characters. Therefore, it should be declared as a character variable, whereas, a variable called salary will store numbers; therefore, it should be declared as a numeric variable. Data types can be categorized into two types, built-in and user-defined data types. A built-in data type is a data type at the lowest level that is used for actual data representation in the memory. Most of the built-in data types used in C++ are similar to the data types used in C#. On the other hand, the user-defined data types, such as classes and structures, are defined by the users. The following table lists the built-in data types used in C# and C++.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

New hot app: Facebook Albums To PDF

pdfcrowd.com

Note In C#, there exists another data type named string having a variable length. The data type equivalent to string in C++ is a character array. You will learn about character arrays in the subsequent chapters.
Sometimes you need to declare a variable whose value will not change throughout the program. This can be done by declaring the variable as a constant variable. You can define a variable as a constant variable by using the const keyword. The const keyword is an access modifier that sets the access property of a variable as read-only. In other words, declaring a variable with the const keyword ensures that
open in browser PRO version
Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

pdfcrowd.com

the value of the variable will not change during the program execution. Consider the following code snippet:
float Pi = 3.14;

In the preceding code snippet, the variable Pi is initialized with the value of 3.14. However, this value can be changed to any value during the program execution. To make this value static throughout the program, you need to use the following code snippet:
const float Pi = 3.14;

Note In C#, the const keyword is used in the same manner as in C++. A constant variable must be initialized during declaration.

Storing Data in a Variable and Displaying Data on the Screen


You can store a value directly in a variable at the time of writing a program or can store a value given by the user during the program execution. Consider the following code snippet:
int number; char chr = D; //Assigning a value at the time of writing a program cin>>number; //Assigning a value at the time of program execution

In the preceding code snippet, cin is a predefined object that is used to accept the data from the user and store it in the variable named number. In C#, the Console.ReadLine() method is used to accept the data from the user and store it in a variable.
open in browser PRO version
Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

pdfcrowd.com

You can display constant strings and the values stored in a variable using the predefined object cout. Consider the following code snippet:
#include<iostream.h> //Preprocessor directive int num1, num2, sum; cout<<"Enter number 1"<<endl; cin>>num1; cout<<"Enter number 2"<<endl; cin>>num2; sum = num1 + num2; cout<<"The sum is:"<<sum;

The preceding code snippet enables you to calculate the sum of the two numbers entered by the user. In the preceding code snippet, cout is used to display the constant strings Enter number 1 to the user. In addition, it displays the calculated value of the variable sum. In C#, the Console.WriteLine() method is used to display the data to the user.

Note The cin and cout objects are defined in the iostream.h file. In order to use these objects in your program, you need to include this file by using the preprocessor directive, #include<>.

Creating and Executing a Program


Similar to C#, a C++ program must contain the main() function. However, there can be other functions in addition to the main() function. C++ is not a pure object-oriented language. Therefore, you can create a program in C++ without using a class. Consider the following code snippet:
open in browser PRO version
Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

pdfcrowd.com

#include<iostream.h> //Preprocessor directive void main() { int num1, num2, sum; cout<<"Enter number1"<<endl; cin>>num1; cout<<"Enter number2"<<endl; cin>>num2; sum=num1+num2; cout<<"The sum is: "<<sum; }

The preceding code snippet does not have a class. The program asks the user to enter two numbers, adds the numbers, and displays their sum. Every C++ program must contain the following components: The preprocessor directive: It is the first statement in every C++ program. It is processed before the program is compiled and is similar to the using System statement of C#. The preprocessor directive includes the code of the header files into the program. The main() function: It is an essential part of a C++ program. The program execution always starts from the main() function. After creating a program, you need to compile and execute it to get the desired output. To compile and execute the program, you need to perform the following steps: 1. 2. 3. 4. Select startRun. The Run dialog box appears. Type cmd in the Open combo box. Click the OK button. The command prompt window appears. Type cd\ at the command prompt, and then press the Enter key.
Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

open in browser PRO version

pdfcrowd.com

5. Change the drive where you have saved the C++ program. For example, type the following command at the command prompt to change the current drive to D:, and then press the Enter key: 6. Type the following command at the command prompt to compile the program, and then press the Enter key: 7. Type the following command to execute the successfully compiled program, and then press the Enter key:

Note The preceding steps are performed to compile a C++ program using the DJGPP compiler. The extension for the file that contains a C++ program is .cpp.

Let's Practice II
1. Create a program that prompts the user to enter the radius of a circle and displays the diameter of the circle. You need to ensure that the value of the mathematical constant, Pi, is fixed and the program is written without the use of classes. Hint: The formula for calculating the diameter of a circle is: Diameter = 2 * Pi * radius where Pi = 3.14

Classes in C++
OOP languages, such as C# and C++, use classes to group objects containing common attributes. A class in C++ is declared by using the class keyword. The class keyword is followed by the name of the class. The start and the end of the class body are indicated by braces {}. The syntax to declare a class in C++ is:
class <class_name>
open in browser PRO version
Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

pdfcrowd.com

{ };

Note that a class declaration in C++ terminates with a semicolon. A class has attributes and behavior. The attributes of a class are represented through member variables, and the behavior is represented through member functions. We have already discussed about variables. When variables are declared within a class, they are known as member variables of that class. Similarly, the functions within a class are known as member functions.

Member Functions
In C#, member functions can only be defined inside the class body. However, in C++, a member function can be defined inside as well as outside the class body. Consider the following code snippet:
class Sum { void Add() { //Function Body } };

In the preceding code snippet, the function Add() is defined inside the class, Sum. If the Add() function is to be defined outside the class, you need to declare it within the class and define it outside the class, as shown in the following code snippet:
class Sum
open in browser PRO version
Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

pdfcrowd.com

{ void Add();//Declaration }; void Sum::Add()//Definition { //Function Body }

In the preceding code snippet, the member function, Add() is declared inside the class body. The declaration of the function provides the function signature. The declaration in the class body (without definition) informs the compiler that this function is a member of the class but will be defined outside the class. The definition of the Add()function is given outside the class body using the scope resolution operator (::). The definition of the function contains the complete function signature with the function body. In C++, it is recommended to define a function outside the class body because it increases the readability of the class. Consider the following code snippet that adds two numbers and displays the result:
class Sum { void Add(); }; void Sum::Add() { int num1, num2, sum; cout<<"Enter number 1"<<endl; cin>>num1; cout<<"Enter number 2"<<endl; cin>>num2; sum = num1 + num2; cout<<"The sum is:"<<sum;
open in browser PRO version
Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

pdfcrowd.com

In the preceding code snippet, the Add() function is performing all the tasks. It is accepting numbers from the user and adding the numbers. However, the Add() function can also be declared in such a way that it performs only one task, which is the addition of two numbers. In this case, the two numbers that are to be added can be passed to the function as parameters and the function will perform addition on these parameters. Consider the following code snippet:
class Sum { void Add(int iVar1,int iVar2); }; void Sum::Add(int iVar1,int iVar2) { int sum=iVar1+iVar2; cout<<"The sum of the two numbers is"<<sum<<endl; }

In the preceding code snippet, the Add() function is declared as:


void Add(int iVar1,int iVar2);

This means that when the Add() function will be called, two integer values need to be passed to the function. The values passed to a function are known as arguments or parameters. A function may or may not have arguments. A function can also have default arguments and constant arguments.

Default Arguments
C++ allows a function to assign a default value to an argument when no value corresponding to that argument is specified in a
open in browser PRO version
Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

pdfcrowd.com

call to that function. The following code snippet shows how a function assigns default arguments:
int Add(int iNum1=10, int iNum2=20) { return iNum1+iNum2; }

In the preceding code snippet, if the Add() function is invoked without any arguments, then the default values 10 and 20 are assigned to the function arguments, iNum1 and iNum2, respectively. However, if the user enters a different set of values during a call to the Add() function, then the values passed by the user will overwrite the default values assigned to the function arguments,iNum1 and iNum2,respectively.

Constant Arguments
There may be situations where you do not want a function to modify the arguments that you pass to it. In such a situation, you can ensure that the argument that is passed to the function is a constant. To make an argument constant, you need to use the const keyword, as shown in the following code snippet:
int Add(const int iVar1, const int iVar2);

In the preceding code snippet, the arguments iVar1 and iVar2 are defined as constants. Therefore, the values of these arguments cannot be changed in the Add()function.

Let's Practice III


1. Create a class, Calculator. The class should have four functions, Add(), Subtract(), Multiply(), and Divide(). All the functions should have two arguments, one of which is a default argument. The function should do the calculation and display the result accordingly. In addition, all the functions should be defined outside the class.

Exercises
open in browser PRO version
Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

pdfcrowd.com

Exercise 1
Define two member functions, books() and journals() inside the body of the class, Library.

Exercise 2
Declare two member functions, books() and journals() inside the body of the class, Library and define them outside the class.

Exercise 3
Declare the Ticket class that consists of three member functions, booking(), status(), and print(). The booking() function should display Accepting passenger's details for booking, the status() function should display Checking whether the passenger's name is in the confirmed or the waiting list, and the print() function should display Printing the confirmed list of passengers. Ensure that the definition of each function is given outside the class body.

Reference Links
Introducing C++
Reference Reading: Books Reference Reading: URLs

Grady Booch, Object-Oriented http://www.hitmill.com/programming/overview. Analysis and Design with html Applications http://www.acm.org/crossroads/xrds1-1/ovp. Yashavant Kanetkar, Let Us html C++ New hot app: Facebook Albums To PDF open in browser PRO version Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

C++ http://www.wiziq.com/tutorial/762-C-Basic-Introduction Stephen Prata, C++ Primer Plus http://www.wiziq.com/tutorial/762-C-Basic-Introduction

Classes in C++
Reference Reading: Books Grady Booch, Object-Oriented Analysis and Design with Applications Reference Reading: URLs http://en.wikipedia.org/wiki/Object-oriented_programming http://www.aonaware.com/OOP1.htm

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

New hot app: Facebook Albums To PDF

pdfcrowd.com

Potrebbero piacerti anche