Free Essay

C++ Language

In:

Submitted By Python
Words 798
Pages 4
cplusplus.com

C++ Language Tutorial

Written by: Juan Soulié Last revision: June, 2007

Available online at:

http://www.cplusplus.com/doc/tutorial/
The online version is constantly revised and may contain corrections and changes

The C++ Language Tutorial

This document and its content is copyright of cplusplus.com © cplusplus.com, 2008. All rights reserved. Any redistribution or reproduction of part or all of the content in any form is prohibited other than to print a personal copy of the entire document or download it to a local hard disk, without modifying its content in any way (including, but not limited to, this copyright notice). You may not, except with express written permission from cplusplus.com, distribute the content of this document. Nor may you transmit it or store it in any other website or other form of electronic retrieval system.
2

© cplusplus.com 2008. All rights reserved

The C++ Language Tutorial

Table of contents
Table of contents ...............................................................................................................................3 Introduction ......................................................................................................................................5 Instructions for use ................................................................................................................................... 5 Basics of C++ ......................................................................................................................................7 Structure of a program ............................................................................................................................. 7 Variables. Data Types. ............................................................................................................................. 11 Constants ................................................................................................................................................ 17 Operators ................................................................................................................................................ 21 Basic Input/Output.................................................................................................................................. 29 Control Structures ............................................................................................................................ 34 Control Structures ................................................................................................................................... 34 Functions (I) ............................................................................................................................................ 41 Functions (II) ........................................................................................................................................... 47 Compound data types ...................................................................................................................... 54 Arrays ...................................................................................................................................................... 54 Character Sequences .............................................................................................................................. 60 Pointers ................................................................................................................................................... 63 Dynamic Memory.................................................................................................................................... 74 Data structures........................................................................................................................................ 77 Other Data Types .................................................................................................................................... 82 Object Oriented Programming.......................................................................................................... 86 Classes (I)................................................................................................................................................. 86 Classes (II) ............................................................................................................................................... 95 Friendship and inheritance ................................................................................................................... 100 Polymorphism ....................................................................................................................................... 107 Advanced concepts ........................................................................................................................ 113 Templates.............................................................................................................................................. 113 Namespaces .......................................................................................................................................... 120 Exceptions ............................................................................................................................................. 123 Type Casting .......................................................................................................................................... 127

3

© cplusplus.com 2008. All rights reserved

The C++ Language Tutorial

Preprocessor directives......................................................................................................................... 133 C++ Standard Library ...................................................................................................................... 138 Input/Output with files ......................................................................................................................... 138

4

© cplusplus.com 2008. All rights reserved

The C++ Language Tutorial

Introduction

Instructions for use
To whom is this tutorial directed?
This tutorial is for those people who want to learn programming in C++ and do not necessarily have any previous knowledge of other programming languages. Of course any knowledge of other programming languages or any general computer skill can be useful to better understand this tutorial, although it is not essential. It is also suitable for those who need a little update on the new features the language has acquired from the latest standards. If you are familiar with the C language, you can take the first 3 parts of this tutorial as a review of concepts, since they mainly explain the C part of C++. There are slight differences in the C++ syntax for some C features, so I recommend you its reading anyway. The 4th part describes object-oriented programming. The 5th part mostly describes the new features introduced by ANSI-C++ standard.

Structure of this tutorial
The tutorial is divided in 6 parts and each part is divided on its turn into different sections covering a topic each one. You can access any section directly from the section index available on the left side bar, or begin the tutorial from any point and follow the links at the bottom of each section. Many sections include examples that describe the use of the newly acquired knowledge in the chapter. It is recommended to read these examples and to be able to understand each of the code lines that constitute it before passing to the next chapter. A good way to gain experience with a programming language is by modifying and adding new functionalities on your own to the example programs that you fully understand. Don't be scared to modify the examples provided with this tutorial, that's the way to learn!

Compatibility Notes
The ANSI-C++ standard acceptation as an international standard is relatively recent. It was first published in November 1997, and revised in 2003. Nevertheless, the C++ language exists from a long time before (1980s). Therefore there are many compilers which do not support all the new capabilities included in ANSI-C++, especially those released prior to the publication of the standard. This tutorial is thought to be followed with modern compilers that support -at least on some degree- ANSI-C++ specifications. I encourage you to get one if yours is not adapted. There are many options, both commercial and free.

Compilers
The examples included in this tutorial are all console programs. That means they use text to communicate with the user and to show their results.

5

© cplusplus.com 2008. All rights reserved

The C++ Language Tutorial

All C++ compilers support the compilation of console programs. Check the user's manual of your compiler for more info on how to compile them.

6

© cplusplus.com 2008. All rights reserved

The C++ Language Tutorial

Basics of C++

Structure of a program
Probably the best way to start learning a programming language is by writing a program. Therefore, here is our first program: // my first program in C++ Hello World! #include using namespace std; int main () { cout

Similar Documents

Free Essay

C Language

...Solving and 'C' Programming Version: PSC/Handout/1107/1.0 Date: 16-11-07 Cognizant 500 Glen Pointe Center West Teaneck, NJ 07666 Ph: 201-801-0233 www.cognizant.com Problem Solving and C Programming TABLE OF CONTENTS About this Document ....................................................................................................................6 Target Audience ...........................................................................................................................6 Objectives .....................................................................................................................................6 Pre-requisite .................................................................................................................................6 Session 2: Introduction to Problem Solving and Programming Languages ...........................7 Learning Objectives ......................................................................................................................7 Problem Solving Aspect ...............................................................................................................7 Program Development Steps .......................................................................................................8 Introduction to Programming Languages ...................................................................................14 Types and Categories of Programming Languages ...............

Words: 4320 - Pages: 18

Free Essay

C Language

...UNIT 1 NOTES Digital Computer A digital computer is an electronic computing machine that uses the binary digits (bits) 0 and 1 to represent all forms of information internally in digital form. Every computer has a set of instructions that define the basic functions it can perform. Sequences of these instructions. Component of Digital Computer: (1)CPU: The Central Processing Unit (CPU) or the processor is the portion of a computer system that carries out the instructions of a Computer, and is the primary element carrying out the computer's functions. This term has been in use in the computer industry at least since the early 1960s . The form, design and implementation of CPUs have changed dramatically since the earliest examples, but their fundamental operation remains much the same. (2)ALU: an arithmetic logic unit (ALU) is a Digital computer that performs arthimatic and logical operations. The ALU is a fundamental building block of the central processing unit(CPU) of a computer, and even the simplest microprocessor contain one for purposes such as maintaining timers. The processors found inside modern CPUs and graphics processing units(CPU) accommodate very powerful and very complex ALUs; a single component may contain a number of ALUs. Mathematician proposed the ALU concept in 1945, when he wrote a report on the foundations for a new computer called the EDVAC. (3)Memory: memory is an organism's ability to store, retain, and recall information. Traditional studies of memory...

Words: 2515 - Pages: 11

Free Essay

C++ Languages

...Object-Oriented Programming B.Sc. Programme in Electrical and Computer Engineering C++ Basics Roman Podraza Institute of Computer Science Warsaw University of Technology Project is co-financed by European Union within European Social Fund What Is OOP ? • Object-oriented programming (OOP) is a currently popular and powerful programming technique • Main characteristics of OOP: – Encapsulation: a form of information hiding. – Inheritance: code reusability, refinement of ideas. – Polymorphism: multiple meanings in the context of inheritance. • Origins of C++ 2 A Sample Program in C++ // The first program in C++ #include using namespace std; int main () { cout 0 ) ; else x *= 3; // quite often // a block is used // // // // // e.g. empty statement keyword (optional) statement executed if boolean expression is false 22 Instructions – Multiway if-else statement if (x > 0 && x < 10) x += 10; else if (x >= 10 && x < 20) x += 20; else if (x >= 20 && x < 30) x += 30; else if (x >= 30 && x < 40) x += 40; else x += 100; 23 Instructions if (x > 0) if (y > 2) x -= y; else x += y; if (x > 0) { if (y > 2) x -= y; } else x += y; 24 Instructions • switch statement controlling expression switch ( ch ){ case (’A’): cout name == 0) // a new string (not found in the array) { res->name = new char[strlen(p) + 1]; strcpy (res->name, p); res->val = 0; } return res->val; } 40 References int main(){ const int MAX = 256; char buf[MAX]; while (cin>>buf)...

Words: 260 - Pages: 2

Free Essay

C Sharp Language Specification

...C# Language Specification Version 4.0 Notice © 1999-2010 Microsoft Corporation. All rights reserved. Microsoft, Windows, Visual Basic, Visual C#, and Visual C++ are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries/regions. Other product and company names mentioned herein may be the trademarks of their respective owners. Table of Contents 1. Introduction 1 1.1 Hello world 1 1.2 Program structure 2 1.3 Types and variables 4 1.4 Expressions 6 1.5 Statements 8 1.6 Classes and objects 12 1.6.1 Members 12 1.6.2 Accessibility 13 1.6.3 Type parameters 13 1.6.4 Base classes 14 1.6.5 Fields 14 1.6.6 Methods 15 1.6.6.1 Parameters 15 1.6.6.2 Method body and local variables 16 1.6.6.3 Static and instance methods 17 1.6.6.4 Virtual, override, and abstract methods 18 1.6.6.5 Method overloading 20 1.6.7 Other function members 21 1.6.7.1 Constructors 22 1.6.7.2 Properties 23 1.6.7.3 Indexers 23 1.6.7.4 Events 24 1.6.7.5 Operators 24 1.6.7.6 Destructors 25 1.7 Structs 25 1.8 Arrays 26 1.9 Interfaces 27 1.10 Enums 29 1.11 Delegates 30 1.12 Attributes 31 2. Lexical structure 33 2.1 Programs 33 2.2 Grammars 33 2.2.1 Grammar notation 33 2.2.2 Lexical grammar 34 2.2.3 Syntactic grammar 34 2.3 Lexical analysis 34 2.3.1 Line terminators 35 2.3.2 Comments 35 2.3.3 White space 37 2.4 Tokens 37 2.4.1 Unicode character escape sequences 37 2.4.2 Identifiers 38 2.4.3 Keywords 39 ...

Words: 47390 - Pages: 190

Free Essay

C++Language Compasion

...++Starting Out with Programming Logic and Design, 3rd Edition By Tony Gaddis C++ Language Companion or Copyright © 2013 Pearson Education, Inc. Table of Contents Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Introduction 3 Introduction to Computers and Programming 4 Input, Processing, and Output 9 Functions 19 Decision Structures and Boolean Logic 27 Repetition Structures 41 Value-Returning Functions 49 Input Validation 59 Arrays 61 Sorting and Searching Arrays 72 Files 77 Menu-Driven Programs 86 Text Processing 89 Recursion 95 Object-Oriented Programming 97 Page 2 Introduction Welcome to the C++ Language Companion for Starting Out with Programming Logic and Design, 3rd Edition, by Tony Gaddis. You can use this guide as a reference for the C++ Programming Language as you work through the textbook. Each chapter in this guide corresponds to the same numbered chapter in the textbook. As you work through a chapter in the textbook, you can refer to the corresponding chapter in this guide to see how the chapter's topics are implemented in the C++ programming language. In this book you will also find C++ versions of many of the pseudocode programs that are presented in the textbook. Note: This booklet does not have a chapter corresponding to Chapter 15 of your textbook because C++ does not provide a GUI programming library. Page 3 Chapter 1 This chapter accompanies...

Words: 1609 - Pages: 7

Free Essay

C Language

...Teach Yourself C++ in 21 Days, Second Edition Introduction Week 1 at a Glance: Day 1 Getting Started Day 2 The Parts of a C++ Program Day 3 Variables and Constants Day 4 Expressions and Statements Day 5 Functions Day 6 Basic Classes Day 7 More Program Flow Week 1 in Review Week 2 at a Glance: Day 8 Pointers Day 9 References Day 10 Advanced Functions Day 11 Arrays Day 12 Inheritance Day 13 Polymorphism Day 14 Special Classes and Functions Week 2 in Review Week 3 at a Glance: Day 15 Advanced Inheritance Day 16 Streams Day 17 The Preprocessor Day 18 Object-Oriented Analysis and Design Day 19 Templates Day 20 Exceptions and Error Handling Day 21 Whats Next Week 3 in Review Appendixes A Operator Precedence B C++ Keywords C Binary and Hexadecimal D Answers Index Teach Yourself C++ in 21 Days, Second Edition Dedication This book is dedicated to the living memory of David Levine. Acknowledgments A second edition is a second chance to acknowledge and to thank those folks without whose support and help this book literally would have been impossible. First among them are Stacey, Robin, and Rachel Liberty. I must also thank everyone associated with my books, both at Sams and at Wrox press, for being professionals of the highest quality. The editors at Sams did a fantastic job, and I must especially acknowledge and thank Fran Hatton, Mary Ann Abramson, Greg Guntle, and Chris Denny. I have taught an online course based on this book for a couple years, and many folks there...

Words: 4907 - Pages: 20

Free Essay

C Language

...Computer Programming Language Week 11 Data Files Objectives Understand Text and Binary Files  Declaring, Opening, and Closing File Streams  Reading from and Writing to Text Files  Passing and Returning Filenames  Reading from and Writing to Binary Files (Optional)  2 Files   File: collection of data that is stored together under a common name, usually on a disk, magnetic tape, or CD-ROM Each file has a unique filename, referred to as the file’s external name  For example, prices.dat and info.txt 3 Text and Binary Files  A file can be thought as an array of bytes. Characters Displayed 768A Code page: ASCII Code Software Interpretation Binary numbers, in decimal numbers: 55 54 56 65 4 ASCII Table 5 Other Code Page* How this text file is stored in computer? Hello 您好 Encode simplified Chinese • GB2312 • GB18030 • UTF-8 6 Declaring, Opening, and Closing File Streams  To store and retrieve data outside a C program, you need two items:   A file A file stream  File stream: one-way transmission path used to connect a file stored on a physical device to a program   Input file stream: receives data from a file into a program Output file stream: sends data to a file 7 File Streams 8 Declaring a File Stream    File stream is a data structure For each file that your program uses, a file stream must be named (declared) and created (opened) Declare a file stream ...

Words: 1171 - Pages: 5

Premium Essay

Learn C Programming Language in 24 Hours

...Yourself C in 24 Hours Previous | Table of Contents | Next Hour 1 - Getting Started A journey of a thousand miles is started by taking the first step. —Chinese proverb High thoughts must have high language. —Aristophanes Welcome to Teach Yourself C in 24 Hours. In this first lesson you'll learn the following:     What C is Why you need to learn C The ANSI standard Hardware and software required in order to run the C program What Is C? C is a programming language. The C language was first developed in 1972 by Dennis Ritchie at AT&T Bell Labs. Ritchie called his newly developed language C simply because there was a B programming language already. (As a matter of fact, the B language led to the development of C.) C is a high-level programming language. In fact, C is one of the most popular general-purpose programming languages. In the computer world, the further a programming language is from the computer architecture, the higher the language's level. You can imagine that the lowest-level languages are machine languages that computers understand directly. The high-level programming languages, on the other hand, are closer to our human languages. (See Figure 1.1.) Figure 1.1. The language spectrum. High-level programming languages, including C, have the following advantages:    Readability: Programs are easy to read. Maintainability: Programs are easy to maintain. Portability: Programs are easy to port across different computer platforms. The C language's...

Words: 73255 - Pages: 294

Free Essay

Assignment and Essay.... Others)Information Technology (Programming/ Languages (Java, C++, Vb,.Net, & Etc)/Database Design/ Computer Networking/ System Analysis/ Project Management/Project Development/ It & Society/ and.

...ASSIGNMENT and ESSAY. ... others)Information Technology (Programming/ Languages (Java, C++, VB, .NET, & etc)/Database Design/ Computer Networking/ System Analysis/ Project Management/Project Development/ IT & Society/ and. - NET programmers continue to struggle with the complexities of a hybrid managed/unmanaged environment. ..... Sorry, I had to laugh at that paper! ... Java on the other hand is cross-platform, and also traditionally runs as an ... - NET programmers continue to struggle with the complexities of a hybrid managed/unmanaged environment. ..... Sorry, I had to laugh at that paper! ... Java on the other hand is cross-platform, and also traditionally runsASSIGNMENT and ESSAY. ... others)Information Technology (Programming/ Languages (Java, C++, VB, .NET, & etc)/Database Design/ Computer Networking/ System Analysis/ Project Management/Project Development/ IT & Society/ and. - NET programmers continue to struggle with the complexiASSIGNMENT and ESSAY. ... others)Information Technology (Programming/ Languages (Java, C++, VB, .NET, & etc)/Database Design/ Computer Networking/ System Analysis/ Project Management/Project Development/ IT & Society/ and. - NET programmers continue to struggle with the complexities of a hybrid managed/unmanaged environment. ..... Sorry, I had to laugh at that paper! ... Java on the other hand is cross-platform, and also traditionally runs as an ... - NET programmers continue to struggle with the complexities of a hybrid managed/unmanaged environment...

Words: 784 - Pages: 4

Free Essay

Computer Science C++

...Report Bundle C++Ox: The Dawning of a New Standard Contents C++0x: The Dawning of a New Standard It's been 10 years since the first ISO C++ standard, and 2009 will bring us the second. In this special report, DevX delves into the new features being discussed by the standards team. Learn how these new features will revolutionize the way you code. Overview: C++ Gets an Overhaul It's been 10 years since the first ISO C++ standard, and 2009 will bring us the second. Learn about the new features being added and how they will revolutionize the language. Easier C++: An Introduction to Concepts C++0x concepts bring the full power of the Generic Programming paradigm to C++, making templates more expressive, easier to write, and easier to use. Spectacularly poor template error messages are a thing of the past! Simpler Multithreading in C++0x The new standard will support multithreading, with a new thread library. Find out how this will improve porting code, and reduce the number of APIs and syntaxes you use. The State of the Language: An Interview with Bjarne Stroustrup C++ founding father assesses the language on the eve of its new standard. Timeline: C++ in Retrospect From its nascent pre-processor in 1979 to today's incredibly sophisticated language features and libraries, we've documented each step along the way. C++0x: The Dawning of a New Standard Overview: C++ Gets an Overhaul Overview: C++ Gets an Overhaul C++Ox: The Dawning...

Words: 6570 - Pages: 27

Free Essay

123456789

...document. Embedded styles affect only the tags on the page they are embedded in. ex. <style type="text/css"> p { color: #00f; } </style> * external styles External styles are styles that are written in a separate document and then attached to various Web documents. External style sheets can affect any document they are attached to. ex. <link rel="stylesheet" type="text/css" href="styles.css" /> Define JavaScript? -JavaScript is an interpreted programming or script language from Netscape. It is somewhat similar in capability to Microsoft'sVisual Basic, Sun's Tcl, the UNIX-derived Perl, and IBM'sREXX. In general, script languages are easier and faster to code in than the more structured and compiled languages such as C and C++. Script languages generally take longer to process than compiled languages, but are very useful for shorter programs. Give an example of each operator in the ff below: Arithmetic There are four main arithmetic operators in C. addition + subtraction - multiplication * division / ex: y=5; z=2; x=y+z; Logical These five...

Words: 393 - Pages: 2

Free Essay

It/218 Object Oriented Programming

...Object oriented programming refers to a method of programming in which individual objects, usually called "methods" and "functions", are created and used in junction with each other to perform a function. These objects are organized within the program through use of things called structures or classes. A class is something we use to create a blueprint of sorts for a assortment of variables and components. Similarly, a structure serves the same purpose. The only difference between a structure and a class is that a structure's members are public by default and a classes members are private by default. Another form of "blueprint" used by programmers is the data union. While a union is very primitive in comparison to a structure or class, it is a good tool to use to conserve memory in larger applications. A union uses the same memory block for multiple variables at different points. While two variables in a union cannot be accessed at the same time, a union is a good way to re-use blocks of memory that would normally be left void after a variable is finished with. Now that I have covered the basic points of classes, structures and unions, I will go into more detail of just how powerful a class or structure can be. In basic reference, a class is simply a blueprint to something we create instances of later in the program. This is a very vague statement however, because in object-oriented programming the class is the backbone of the program. It is what makes the...

Words: 813 - Pages: 4

Free Essay

Cuda Overview

...speedups in fields such as medical imaging and natural resource exploration, and creating breakthrough applications in areas such as image recognition and real-time HD video playback and encoding. CUDA enables this unprecedented performance via standard APIs such as the soon to be released OpenCL™ and DirectX® Compute, and high level programming languages such as C/C++, Fortran, Java, Python, and the Microsoft .NET Framework. The CUDA Architecture The CUDA Architecture consists of several components, in the green boxes below: 1. 2. 3. 4. Parallel compute engines inside NVIDIA GPUs OS kernel-level support for hardware initialization, configuration, etc. User-mode driver, which provides a device-level API for developers PTX instruction set architecture (ISA) for parallel computing kernels and functions Device-level APIs Language Integration Applications Using DirectX Applications Using OpenCL Applications Using the CUDA Driver API C for CUDA Compute Kernels Applications Using C, C++, Fortran, Java, Python, ... C for CUDA Compute Functions HLSL Compute Shaders OpenCL C Compute Kernels DirectX Compute OpenCL Driver C...

Words: 1261 - Pages: 6

Free Essay

Akashmsd

...Introduction to the C Programming Language Science & Technology Support High Performance Computing Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212-1163 Table of Contents • • • • • • • • • Introduction C Program Structure Variables, Expressions, & Operators Input and Output Program Looping Decision Making Statements Array Variables Strings Math Library Functions • • • • • • • • • User-defined Functions Formatted Input and Output Pointers Structures Unions File Input and Output Dynamic Memory Allocation Command Line Arguments Operator Precedence Table 2 C Programming Introduction • Why Learn C? 3 C Programming Why Learn C? • • • • • • • • • Compact, fast, and powerful “Mid-level” Language Standard for program development (wide acceptance) It is everywhere! (portable) Supports modular programming style Useful for all applications C is the native language of UNIX Easy to interface with system devices/assembly routines C is terse 4 C Programming C Program Structure • • • • • Canonical First Program Header Files Names in C Comments Symbolic Constants 5 C Programming Canonical First Program • The following program is written in the C programming language: #include main() { /* My first program */ printf("Hello World! \n"); } • • C is case sensitive. All commands in C must be lowercase. C has a free-form line structure. End of each...

Words: 4639 - Pages: 19

Premium Essay

Let Us C - Yashwant Kanetkar.Pdf

...Let Us C Fifth Edition Yashavant P. Kanetkar Dedicated to baba Who couldn’t be here to see this day... About the Author Destiny drew Yashavant Kanetkar towards computers when the IT industry was just making a beginning in India. Having completed his education from VJTI Mumbai and IIT Kanpur in Mechanical Engineering he started his training company in Nagpur. Yashavant has a passion for writing and is an author of several books in C, C++, VC++, C#, .NET, DirectX and COM programming. He is a much sought after speaker on various technology subjects and is a regular columnist for Express Computers and Developer 2.0. His current affiliations include being a Director of KICIT, a training company and DCube Software Technologies, a software development company. In recognition to his contribution Microsoft awarded him the prestigious “Best .NET Technical Contributor” award recently. He can be reached at kanetkar@kicit.com. Preface to the Fifth Edition It is mid 2004. World has left behind the DOTCOM bust, 9/11 tragedy, the economic downturn, etc. and moved on. Countless Indians have relentlessly worked for close to two decades to successfully establish “India” as a software brand. At times I take secret pleasure in seeing that a book that I have been part of, has contributed in its own little way in shaping so many budding careers that have made the “India” brand acceptable. Computing and the way people use C for doing it keeps changing as years go by. So overwhelming...

Words: 46379 - Pages: 186