Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Introduction to C++ Programming
Introduction to C++ Programming
Introduction to C++ Programming
Ebook561 pages5 hours

Introduction to C++ Programming

Rating: 3 out of 5 stars

3/5

()

Read preview

About this ebook

Welcome to Introduction to C++ Programming, an example based textbook, written to cater to the needs of beginners and intermediate users. C++ is an object-oriented programming language, which is a preferred programming approach followed by the software industry. C++ enjoys the distinction of being the most popular and widely used OOP language in the world. The syntax, style, features and philosophy of the language form the basis of many other programming languages such as Java and C#.

Created by Bjarne Stroustrup in the early 1980s, C++, over the period, has undergone many changes and improvements. In 1998, the language was standardized by the American National Standards Institute (ANSI) and the International Standards Organization (ISO). The textbook confirms to these standards and explains various features of the language in a simple and easy style.

The highlight of the textbook is that each concept introduced in it has been exemplified by a program to clarify and facilitate better understanding. Also, the line-by-line explanation of each program ensures that the users with no previous programming experience are able to understand the concepts and master the programming techniques and use them with flexibility whiledesigning programs.

LanguageEnglish
Release dateJun 1, 2017
ISBN9781386468387
Introduction to C++ Programming
Author

Prof Sham Tickoo

Prof. Sham Tickoo is professor of Manufacturing Engineering at Purdue University Northwest, USA where he has taught design, drafting, CAD and other engineering courses for over nineteen years. Before joining Purdue University, Prof. Tickoo has worked as a machinist, quality control engineer, design engineer, engineering consultant, and software developer. He has received a US patent for his invention Self Adjusting Cargo Organizer for Vehicles. Professor Tickoo also leads the team of authors at CADCIM Technologies to develop world-class teaching and learning resources for Computer Aided Design and Manufacturing (CAD/CAM) and related technologies.

Read more from Prof Sham Tickoo

Related to Introduction to C++ Programming

Related ebooks

Programming For You

View More

Related articles

Reviews for Introduction to C++ Programming

Rating: 2.888888888888889 out of 5 stars
3/5

9 ratings1 review

What did you think?

Tap to rate

Review must be at least 10 words

  • Rating: 2 out of 5 stars
    2/5
    The author does a good job of explaining concepts and overall it is a reasonable resource only the formatting of code samples is unreadable. It wouldn't be an issue if you intend to write each line by hand, but if you want to quickly jog your memory on a topic the formatting is going to cause you pain.

Book preview

Introduction to C++ Programming - Prof Sham Tickoo

Introduction to C++ Programming

CADCIM Technologies

525 St. Andrews Drive

Schererville, IN 46375

USA

(www.cadcim.com)
Contributing Author

Sham Tickoo

Professor

Purdue University Calumet

Hammond, Indiana

USA


LOGO01.PCX

Introduction to C++ Programming

Sham Tickoo

CADCIM Technologies

525 St Andrews Drive

Schererville, Indiana 46375, USA

www.cadcim.com

Copyright © 2016 by CADCIM Technologies, USA. All rights reserved. Printed in the United States of America except as permitted under the United States Copyright Act of 1976.

No part of this publication may be reproduced or distributed in any form or by any means, or stored in the database or retrieval system without the prior permission of CADCIM Technologies.

ISBN 978-1-942689-38-6

NOTICE TO THE READER

Publisher does not warrant or guarantee any of the products described in the text or perform any independent analysis in connection with any of the product information contained in the text. Publisher does not assume, and expressly disclaims, any obligation to obtain and include information other than that provided to it by the manufacturer.

The reader is expressly warned to consider and adopt all safety precautions that might be indicated by the activities herein and to avoid all potential hazards. By following the instructions contained herein, the reader willingly assumes all risks in connection with such instructions.

The Publisher makes no representation or warranties of any kind, including but not limited to, the warranties of fitness for particular purpose or merchantability, nor are any such representations implied with respect to the material set forth herein, and the publisher takes no responsibility with respect to such material. The publisher shall not be liable for any special, consequential, or exemplary damages resulting, in whole or part, from the reader’s use of, or reliance upon, this material.

www.cadcim.com

LOGO01.PCX

CADCIM Technologies

DEDICATION

To teachers, who make it possible to disseminate knowledge

to enlighten the young and curious minds

of our future generations

To students, who are dedicated to learning new technologies

and making the world a better place to live

THANKS

To employees of CADCIM Technologies for their valuable help


Online Training Program Offered by CADCIM

Technologies

CADCIM Technologies provides effective and affordable virtual online training on various software packages including Computer Aided Design and Manufacturing and Engineering (CAD/CAM/CAE), computer programming languages, animation, architecture, and GIS. The training is delivered ‘live’ via Internet at any time, any place, and at any pace to individuals as well as the students of colleges, universities, and CAD/CAM training centers. The main features of this program are:

Training for Students and Companies in a Classroom Setting

Highly experienced instructors and qualified engineers at CADCIM Technologies conduct the classes under the guidance of Prof. Sham Tickoo of Purdue University Calumet, USA. This team has authored several textbooks that are rated one of the best in their categories and are used in various colleges, universities, and training centers in North America, Europe, and in other parts of the world.

Training for Individuals

CADCIM Technologies with its cost effective and time saving initiative strives to deliver the training in the comfort of your home or work place, thereby relieving you from the hassles of traveling to training centers.

Training Offered on Software Packages

CADCIM provides basic and advanced training on the following software packages:

CAD/CAM/CAE: CATIA, Pro/ENGINEER Wildfire, PTC Creo Parametric, Creo Direct, SOLIDWORKS, Autodesk Inventor, Solid Edge, NX, AutoCAD, AutoCAD LT, AutoCAD Plant 3D, Customizing AutoCAD, EdgeCAM, and ANSYS

Architecture and GIS: Autodesk Revit Architecture, AutoCAD Civil 3D, Autodesk Revit Structure, AutoCAD Map 3D, Revit MEP, Navisworks, Primavera, and Bentley STAAD Pro

Animation and Styling: Autodesk 3ds Max, Autodesk 3ds Max Design, Autodesk Maya, Autodesk Alias, The Foundry NukeX, MAXON CINEMA 4D, Adobe Flash, and Adobe Premiere

Computer Programming: C++, VB.NET, Oracle, AJAX, and Java

For more information, please visit the following link: http://www.cadcim.com

Note

If you are a faculty member, you can register by clicking on the following link to access the teaching resources: www.cadcim.com/Registration.aspx. The student resources are available at //www.cadcim.com. We also provide Live Virtual Online Training on various software packages. For more information, write us at sales@cadcim.com.


Table of Contents

Chapter 1: Introduction to C++

Chapter 2: Getting Started with C++

Chapter 3: Control Statements

Chapter 4: Functions and Arrays

Chapter 5: Strings, Pointers, and Structures

Chapter 6: Union, Enumeration, and Preprocessor

Chapter 7: Data Structure

Chapter 8: Classes and Objects

Chapter 9: Constructors, Destructors, and Operator Overloading

Chapter 10: Inheritance

Chapter 11: Virtual Functions and Polymorphism

Chapter 12: The C++ Console I/O Operations

Chapter 13: Exception Handling

Chapter 14: The File I/O System


Preface

C++

Welcome to Introduction to C++ Programming, an example based textbook, written to cater to the needs of beginners and intermediate users. C++ is an object-oriented programming language, which is a preferred programming approach followed by the software industry. C++ enjoys the distinction of being the most popular and widely used OOP language in the world. The syntax, style, features and philosophy of the language form the basis of many other programming languages such as Java and C#.

Created by Bjarne Stroustrup in the early 1980s, C++, over the period, has undergone many changes and improvements. In 1998, the language was standardized by the American National Standards Institute (ANSI) and the International Standards Organization (ISO). The textbook confirms to these standards and explains various features of the language in a simple and easy style.

The highlight of the textbook is that each concept introduced in it has been exemplified by a program to clarify and facilitate better understanding. Also, the line-by-line explanation of each program ensures that the users with no previous programming experience are able to understand the concepts and master the programming techniques and use them with flexibility while designing programs.

The main features of the book are as follows:

Programming Approach: This textbook introduces the key ideas of object-oriented programming in an intuitive way. The concepts are illustrated through best programming examples, covering all aspects of OOP and C++.

Notes: Additional information is provided to the users in the form of notes.

Illustrations: There is an extensive use of examples, schematic representation, flow-charts, tables, screen capture images, and programming exercises.

Learning Objectives: The first page of every chapter summarizes the topics that are covered in it.

Self-Evaluation Test, Review Questions, and Exercises: Each chapter ends with a Self-Evaluation Test so that the users can assess their knowledge. The answers of the Self-Evaluation Test are given at the end of the chapter. Also, the Review Questions and Exercises are given at the end of each chapter that can be used by the Instructors as test questions and exercises.

Free Companion Website

It has been our constant endeavor to provide you the best textbooks and services at affordable price. In this endeavor, we have come out with a Free Companion Website that will facilitate the process of teaching and learning of C++. If you purchase this textbook, you will get access to the files on the Companion website. The following resources are available for faculty and students in this website:

Faculty Resources

• Technical Support

You can get online technical support by contacting techsupport@cadcim.com.

• Instructor Guide

Solutions to all the review questions and exercises in the textbook are provided to

help the faculty members test the skills of the students.

• Example Files

The C++ files used in examples are available for free download.

Student Resources

• Technical Support

You can get online technical support by contacting techsupport@cadcim.com.

• Example Files

The C++ files used in examples are available for free download.

If you face any problem in accessing these files, please contact the publisher at sales@cadcim.com or the author at stickoo@purduecal.edu or tickoo525@gmail.com.

Stay Connected

You can now stay connected with us through Facebook and Twitter to get the latest information about our textbooks, videos, and teaching/learning resources. To stay informed of such updates, follow us on Facebook (www.facebook.com/cadcim) and Twitter (@cadcimtech). You can also subscribe to our YouTube channel (www.youtube.com/cadcimtech) to get the information about our latest video tutorials.

Chapter 1

Introduction to C++

Learning Objectives

After completing this chapter, you will be able to:

Understand the concept of procedure-oriented programming

• Understand the concept of object-oriented programming

• Understand the features of object-oriented programming

• Understand the fundamentals of C++

• Understand the >>(extraction) and<<(insertion) operators

Introduction

In early 1980’s, a new programming language was developed by Bjarne Stroustrup at Bell Laboratories, USA. This language, an extended version of C language, is known as C++. Apart from the features of the C language, C++ also has some additional features such as classes, objects, and so on. When C++ language was developed, it was known as ‘C with classes’. In 1983, the name was changed to C++. The ++ sign specifies that it is an incremented version of the C language. This means that the code written in C can also be executed in the C++ environment. Basically, C++ was developed to eliminate some of the limitations of the C language and also to provide some new features to the user.

In this chapter, you will know about procedure-oriented programming, key concepts of object-oriented programming, and also some C++ fundamentals.

Procedure-Oriented Programming

Procedure-oriented programming (POP) is a programming technique in which a problem is divided into subparts. These subparts are solved by using different functions. In this type of programming technique, all the programs are developed around functions. These functions work on global data (data that can be accessed by all the members of a program) and can also manipulate it. In this type of programming technique, the primary focus is on the functions. For example, you may want to solve a problem that performs three different operations such as reading data from the user, processing the data, and printing the output. Three different functions are created to handle these operations, see Figure 1-1. This figure illustrates that all the three operations are performed by three different functions.

c01d01.pcx

Figure 1-1 Representation of an POP

In procedure-oriented programming, the data that can be accessed by all the functions is declared as global. Each function can also have its own local data.

A major drawback of procedure-oriented programming is that the data is not treated as a critical element and can be manipulated by any of the functions. Another drawback is that you cannot solve the real world problems by using the procedure-oriented technique. As the size of the program increases, it becomes more complex and difficult to understand.

Object-Oriented Programming

Object-oriented programming (OOP) developed to overcome the limitations of the procedure-oriented programming is an improved technique for developing the programs. In case of OOP, the data is treated as the most critical element and the primary focus is on the data and not on the procedures. In this technique, the data is grouped together with the functions that operate on it. A problem is divided into entities known as objects. Each object maintains its own copy of data and functions. The data cannot be accessed directly by the other objects of the program. It can only be accessed through a proper interface such as functions, as shown in Figure 1-2.

c01d02.pcx

Figure 1-2 Representation of OOP

Features of Object-Oriented Programming

There are certain features that have made object-oriented programming very popular. These features are as follows:

1. Objects

2. Classes

3. Encapsulation

4. Inheritance

5. Polymorphism

Objects

In object-oriented programming, a problem is divided into certain basic entities called objects. The objects can be used to represent real life objects such as people, bank account, and so on. In this type of programming, all communication is carried out between the objects. When a program is executed, the objects interact with each other by sending messages. The objects contain the data and the functions that can be used to manipulate the data. Each object maintains its own copy of the data and methods, which can communicate with each other through a proper channel or interface.

Classes

A class is a user-defined data type which is used to group the data and the functions together. These objects are the instances of a class. A class can also contain important members such as a constructor to create objects. The objects that belong to same class must have certain properties in common. For example, a table and a chair are the objects of the furniture class. Both the objects have certain properties in common. For example, both are made of wood and so on.

Encapsulation

Encapsulation is a mechanism used for wrapping up the data along with the functions that can operate on the data directly. This mechanism is used to keep the data safe from outside interferences. It hides the internal data and only provides the external interface (functions) through which it can be accessed. Encapsulation also provides the concept of data hiding or information hiding so that it cannot be accessed directly.

Inheritance

Different kinds of objects often have certain amount of properties in common with each other. Inheritance is the process by which one object can acquire the properties of another object. This is called the reusability of code. In inheritance, whenever a new object is created, it can only define those properties that make it unique from the other objects. Inheritance supports the concept of the hierarchical classifications. For example, the fruit ‘Apple’ is a part of the class ‘Fruits’, which is again a part of the class ‘Food’, as shown in Figure 1-3.

c01d03.pcx

Figure 1-3 Hierarchical classification

In the above figure, the two classes Fruits and Vegetables, apart from inheriting certain properties from the class Food, add some properties of their own. The classes Apple and Mango inherit the properties of the Fruits class while the classes Cabbage and Carrot inherit the properties of the Vegetables class.

Polymorphism

Polymorphism is another feature of object-oriented programming. Polymorphism is a Greek term that consists of two words, poly and morph. Poly means many and morph means forms. So, polymorphism means ‘one name many forms’. In polymorphism, an operation shows different behaviors depending on the type of data used in it. In polymorphism, the internal structure (functioning) of the operation is different but the external interface (name) is the same. When an operator shows different behaviors in different contexts, it is known as operator overloading. When a single function name is used to perform different operations, it is known as function overloading, as shown in Figure 1-4.

c01d04.pcx

Figure 1-4 Polymorphism

Concept of c++

In the C++ programming, you can write a sequence of commands called source file. A C++ source file normally carries the .CPP extension. This source file can be converted into a machine-language program. This conversion is called compiling and is done by the compiler. The machine code is combined with some setup and instructions and some standard library routines in a process known as linking. Together, compiling and linking are known as building. The resulting machine-executable files carry the extension .EXE in Windows.

Code::Blocks Environment

Code::Blocks is a open-source platform IDE (integrated development environment) that supports multiple compilers. It comes in an easy-to-install, compressed executable file that is compatible with all versions of Windows, Macintosh, and Linux.

When you install Code::Blocks for the first time, it scans the system for any supported compilers. Once this scan is finished, Code::Blocks is correctly configured for any detected compilers. Code::Blocks also have default configurations even for those compilers that are not detected. The process for downloading and installing Code::Blocks is given next.

Downloading Code::Blocks

1. Navigate to http://www.codeblocks.org in your browser; the Code::Blocks page is displayed, as shown in Figure 1-5. Next, choose the Downloads tab from this page; the page with the Downloads area is displayed, as shown in Figure 1-6.

c00sc12.tif

Figure 1-5 The Code::Blocks page

c00sc13.tif

Figure 1-6 The Downloads area

2. Click on the Download the binary release link; a page is displayed with links for downloading Code::Blocks for various operating systems, as shown in Figure 1-7.

c00sc14.tif

Figure 1-7 Links for downloading Code::Blocks displayed

3. In the Windows XP/Vista/7/8.x/10 area of the page, click the Sourceforge.net link corresponding to the codeblocks-16.01mingw-setup.exe file, as shown in Figure 1-8. After few seconds, a dialog box appears. Navigate to the desired location and then save the file.

c00sc19.tif

Figure 1-8 Downloading the link

Note.pcx Note

The codeblocks-16.01mingw-setup.exe file includes the GCC/G++ compiler and GDB debugger.

Installing the Code::Blocks

1. Navigate to the location where you saved the file and then double-click on the executable file; the User Account Control dialog box is displayed. Next, choose the Yes button from this dialog box; the Welcome to CodeBlock Setup page of the Code::Block Installation dialog box is displayed

2. Choose the Next button from this page; the License Agreement page is displayed.

3. Choose the I Agree button from this page; the Choose Components page of the Code::Blocks Installation dialog box is displayed. Choose the Next button from this page; the Choose Install Location page is displayed.

4. Accept the default location and then choose the Install button from this page; the installing process begins. When the installation completes, the Code::Block Installation message box is displayed. Choose Yes from this message box; the Compilers auto-detection dialog box is displayed. Now, choose OK from the Compilers auto-detection dialog box to open the Code::Blocks environment.

Note.pcx Note

When you install Code::Blocks for the first time, the File Associates dialog box is displayed prompting you to associate the C/C++ file type to Code::Blocks. Select the Yes, associate Code::Blocks with C/C++ file types radio button and then choose the OK button.

Writing Your First Program

In this section, you will create your first C++ program. In this program, you will display the text CADCIM Technologies. Before you create your first program, you need to create a directory in your drive where you will save the file that you will create while following examples of this textbook.

1. Open Window Explorer and then navigate to C drive. Create a new folder with the name cplusproject and then create a sub-folder in the cplusprojects folder with the name c01.

2. Choose File > New > Empty file from the menubar or press CTRL+SHIFT+N; the Untitled1 tab is displayed in the editor.

3. Choose the File > Save file from the menubar or press CTRL+S; the Save file dialog box is displayed. In this dialog box, type cadcim.cpp in the File name text box and then choose the Save button to save the file.

4. Type the following code in the Untitled1 tab.

#include

using namespace std;

int main()

{

cout << Cadcim Technologies! << endl;

return 0;

}

Note.pcx Note

Once you save a file, the syntax highlighting feature will be enabled. This feature displays text, especially source code, in different colors and fonts according to the category of terms.

5. Choose Build > Build and run from the menubar or press F9 to build and run the program. On doing so, the c:\cplusprojects\c01 window is displayed with the output CADCIM Technologies, as shown in Figure 1-9. Press any key to close the window.

c00sc20.tif

Figure 1-9 The output of program

Creating a Project in Code::Blocks

In Code::Blocks, a project is a collection of C++ files. The example shown in the previous section is an example of a console application that runs in the text mode in the terminal window. A terminal window is the best way of creating basic programming concept. However, when your program is configured, you need to create a project to host all the corresponding files. In this section, you will create the project.

1. Choose File > New > Project from the menubar; the New from template wizard is displayed, as shown in Figure 1-10.

2. In this wizard, select Console application and then choose the Go button; the Console application page is displayed, as shown in Figure 1-11. In this page, select the Skip this page next time check box to skip this page the next time. Now, choose the Next button; the Console application page with the Please make selection list is displayed. Select the C++ option from the list, as shown in Figure 1-12.

c00sc1.tif

Figure 1-10 The New from template wizard

c00sc3.tif

Figure 1-11 The Console application page

3. In the next displayed page of the wizard, type FirstProject in the Project title text box. Next, choose the browse button located next to the Folder to create project in text box, refer to Figure 1-13; the Browse For Folder dialog box is displayed, as shown in Figure 1-14. In the Browser for Folder dialog box, browse to the c:\cplusproject\c01 and then choose the OK button. The project file will be saved with the extension .cpp.

Notice that the name of the project file is FirstProject.cpp and it will be saved at the following location: c:\cplusprojects\c01\FirstProject.

c00sc2.tif

Figure 1-12 The C++ option selected

c00sc30.tif

Figure 1-13 Choosing the browse button

c00sc31.tif

Figure 1-14 The Browse For Folder dialog box

4. Choose the Next button from the Console application wizard; the Compiler drop-down list and Debug/Release configuration settings are displayed. Accept the default settings and then choose the Finish button, refer to Figure 1-15

c00sc11.tif

Figure 1-15 The Compiler drop-down and Debug\Release configuration settings displayed

Notice that the project structure is displayed in the Management > Projects tab of the IDE, refer to Figure 1-16.

c00sc24.tif

Figure 1-16 The project structure

5. Expand the Sources node from the Projects tab; the main.cpp node is displayed. Double-click on the node to open it in the editor. This file contains the following standard code:

#include

using namespace std;

int main()

{

cout << Hello world! << endl;

return 0;

}

6. Press F9 to build and run the code.

Adding a Pre-Existing File

In this section, you will split the main.cpp file and create a header file for the hello function.

1. In main.cpp, replace with hello.h and cout << Hello world! << endl; with hello ();. Delete the line using namespace std;. Given below is the resulting code of main.cpp.

#include hello.h

int main()

{

hello ();

return 0;

}

2. Choose File > New > File from the menubar; the New from template wizard is displayed.Select C/C++ header from the right pane of the wizard, refer to Figure 1-17, and then choose the Go button; the C/C++ header page is displayed, refer to Figure 1-18. In the C/C++ header page, choose the browse button corresponding to the File name with full path text box and then navigate to C:\ cplusprojects\c01\FirstProject in the Select filename dialog box. Now, type hello.h in the File name text box and then choose the Save button, refer to Figure 1-19.

c00sc28.tif

Figure 1-17 The New from template wizard

c00sc25.tif

Figure 1-18 The C/C++ header page

c00sc32.tif

Figure 1-19 The Select filename dialog box

3. Choose the Finish button from the C/C++ header page of the wizard.

Note.pcx Note

A header file in C++ has an extension .h. This file sometimes is also referred to as the include file. The header files hold declarations for other files to use.

4. In the hello.h tab of the editor, type void hello(). The resulting code is given below.

#ifndef HELLO_H_INCLUDED

#define HELLO_H_INCLUDED

void hello();

#endif // HELLO_H_INCLUDED

5. Create a new file with the name hello.cpp and save it in the

Enjoying the preview?
Page 1 of 1