You are on page 1of 10

QuickStart Tool

C++
Getting a good start in any new technology or programming language often depends on finding the best available
information. The Builder.com QuickStart Tools give you the information you need to quickly grasp the fundamentals of
developing in a new IDE, using a new programming language, or working with a new development tool.
Besides explaining the basics, the Builder.com C++ QuickStart Tool shows you common tasks, exposes strengths
and weaknesses, demonstrates some of the best uses of the technology, and lists a variety of other online and offline
resources that can help you build a solid foundation of practical knowledge in the C++ programming language.

©1995-2004 CNET Networks, Inc. All Rights Reserved.


C++

Table of contents

Fundamentals ................................................................................................................3

Common tasks ..............................................................................................................4

Strengths ........................................................................................................................6

Weaknesses ..................................................................................................................7

Best uses ........................................................................................................................7

Online resources............................................................................................................8

Other resources ............................................................................................................9

Additional resources ....................................................................................................9

Whitepapers....................................................................................................................9

About Builder.com ......................................................................................................10

©1995-2004 CNET Networks, Inc. All Rights Reserved.


C++

Fundamentals
C++ is a multi-paradigm programming language, which allows, among other things: generic programming, Object
Oriented Programming (OOP), and procedural programming. It derives its roots from C, which is a procedural language.
One of its greatest features is that it trusts you—the programmer—by giving you full control. C++ is best used when you
need efficient, generic programming requiring low-level, compact code that interacts with large amounts of data or with
file systems.

Hello World program


Using C++, we will create the standard “Hello World” program.

Begin
Open your favorite C++ IDE and create a New Project. Or, create a text file called helloworld.cpp, and open it in a text
editor. Type the following:
#include <iostream>

int main() {

std::cout << “Hello World” << std::endl;

return 0;

Running your program


The procedure to compile and run the above program will depend on your IDE. In Visual Studio .NET, for example, you
could press [F5]. In Bloodshed-C++, it would be [Ctrl][F9]. If you are using gcc, you can execute gcc helloworld.cpp from
the command line.
After compiling and running the program, “Hello World” will be printed to the console, as shown in Figure A.

Figure A

Hello World

3 ©1995-2004 CNET Networks, Inc. All Rights Reserved.


C++

Common tasks

Task Steps
Including a header file #include <myfile.ext> // or
#include “myfile.ext”
You can include any file with any extension. However, the most common extensions are
.h and .hpp. Also, note that Standard Template Library (STL) header files do not have any
extension.
The difference is that the .h extension will first look within the system headers (the ones
that come with your C++ compiler), while the .hpp extension will first look within your project
headers.

Reading from a file This program reads from the readme.txt file and gathers all lines into an array (“lines”). Then,
it dumps all read lines to the console.
#include <string>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
#include <vector>
int main() {
std::ifstream in(“readme.txt”);
std::vector<std::string> lines;
std::string cur_line;
while ( std::getline(in, cur_line) ) lines.push_back(cur_line);
std::copy( lines.begin(), lines.end(),
std::ostream_iterator<std::string>(std::cout,”\n”));
}

Catching exceptions An exception is thrown using the throw keyword. Figure B


In order to catch an exception, you have to
surround the suspected code in a try/catch block.
In the catch clause, you specify the types of
objects you can handle. (You can specify more
than one type.)
#include <stdexcept>
#include <iostream>
#include <string>
void func() { throw std::runtime_error
(“oops!”); }

Catch an exception.
int main() {
try {
func();
std::cout << “no exception” << std::endl;
} catch(std::exception & exc) {
// catches all exceptions derived from std::exception
std::cout << “caught “ << exc.what() << std::endl;
}
}

4 ©1995-2004 CNET Networks, Inc. All Rights Reserved.


C++

Parsing strings This sample code parses each word from a string and counts how many times each word
occurs. Finally, it dumps this information to the console.
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <map>
void print_word_info(const std::pair<std::string,int> & val) {std::cout <<
“word “ << val.first << “ appeared “ << val.second << “ times.\n”;
}
int main() {
std::istringstream in(“me and you and others and again me and you”);
std::map<std::string,int> counts;
std::string word;
while ( in >> word) ++counts[word];
std::for_each( counts.begin(), counts.end(), print_word_info);
}

Generic max<> This sample code shows a very simple example of a generic algorithm: a max<> algorithm
function that works for any type that has a < (less-than) operator. (Note: All built-in types have the
< operator; however, custom-created types can choose to overload it.)
#include <string>
#include <iostream>
template<class T> T Max( const T & a, const T & b) { return a < b ? b : a; }
int main() {
/* ints */std::cout << “\nMax(1,2)=” << Max(1,2);
/* doubles */std::cout << “\nMax(3.5,2.3)=” << Max(3.5,2.3);
std::string first = “fox”, second = “other”;
/* strings */std::cout << “\nMax(‘fox’,’other’)=” << Max(first,second);
}
Figure C

Max function

Overloading operators You can overload some operators in your classes; however, it is recommended that you over-
load only those that make sense. A good example of operator overloading is the std::string class.
#include <string>
#include <iostream>
struct name {
name(const std::string & first, const std::string & last) : first(first),
last(last) {}
std::string first, last;
};
bool operator==( const name & me, const name & you) {
return me.first == you.first && me.last == you.last;

5 ©1995-2004 CNET Networks, Inc. All Rights Reserved.


C++

int main() {
name john(“John”,”Doe”), james(“James”,”Gucci”);
std::cout << (john == james ? “John=James” : “John not James”) <<
std::endl;
}

Strengths
As with any language, C++ has both strengths and weaknesses. Because it is designed to be efficient, C++ is often
used in back-end applications (servers), while front-end operations are frequently designed in Rapid Application
Development (RAD) environments, using Visual Basic for example.

Strength Description
Support for generic Generic programming allows programmers to create algorithms that will work with any data type,
programming as long as the data satisfies a certain concept.
Therefore, the reusability of generic programming classes and algorithms is an order of magni-
tude higher than OOP. For example, C++ STL can handle arrays and collections very efficiently.

Efficiency C++ is the younger and safer brother of C. Since C was all about efficiency, Bjarne Stroustrup
(the author of C++) made C++ as efficient as possible while also providing extra (type-) safety.

Both high- and C++ allows you to program at the level you desire, depending on the module you’re working on.
low-level While high-level programming is often preferable, there are times when you need to get down
programming and dirty and program at low levels (for instance, when developing drivers), and C++ provides
you that opportunity.

Enforcing the const The const keyword in C++ makes programming safer. If you know that your function won’t
keyword modify a parameter, you’ll say so by making that parameter const. If by mistake you modify that
parameter, a compile-time error will occur. In large applications this is a great help—just by look-
ing at a function, you’ll know which arguments will be modified and which will not.

Streams Writing to and reading from streams is very simple and straightforward. As a bonus, there are
in-memory streams (istringstream, and ostringstream) that you can work with.
out << users << “ users logged on at “ << now; // writing
in >> a >> b; // reading

Multi-paradigm C++ does not force any single paradigm (such as OOP) on the programmer. Different applica-
support tions and even different modules may require different paradigms.

6 ©1995-2004 CNET Networks, Inc. All Rights Reserved.


C++

Weaknesses

Weakness Description
Backward compatibility C++ was developed on top of C, and it has therefore retained a very high degree of C
to C compatibility. However, many C weaknesses have been merged into C++ as well. These
involve dealing with raw pointers, some not-so-straightforward automatic conversions, and a
lot of error-prone functions such as strncpy, memcpy, etc.

GUI C++ does not yet mix well with GUIs. Simple tasks—such as adding or removing a splitter,
manipulating Property Pages, showing tool tips, and handling menus—are really complicated
to implement in C++.

No conforming There’s no compiler that fully implements the ANSI C++ standard, which was released in 1998.
compilers Because C++ has so many features that interact with each other, sometimes in a surprising
manner, compiler errors are common. Depending on the code in question, compilers may gen-
erate a compile error on a good program, or successfully compile an ill-formed program.

Portability Due to the complexity of C++ and the fact that built-in types are not required to have a fixed
size—for instance, on one platform, int might occupy two bytes while on another platform it
may occupy four bytes—it is very hard to write portable code. Therefore, when switching from
one compiler to another, you might experience bugs that are hard to find and fix.

Bad compile-time error A compile-time error generated when using generic programming libraries will be so cryptic
messages when using that you will usually need the help of an experienced programmer to decipher it.
generic programming

Many string A plethora of string classes exists, many with dubious features. In addition, there still are pro-
implementations grammers using raw functions like strcat. The issue is complicated even more by the fact that
you can have ANSI strings (formed of one-byte chars) and Unicode strings (formed of two-byte
or four-byte chars).

Best uses
C++ is best used in an environment where any of the following is true:
• Efficiency is an issue.

• Your application has little or no GUI.

• You’re dealing with lots of arrays and collections of custom data-types.

• You need to do low-level programming.

• You’re developing a server application (other than a Web server application).

• You’re increasing the speed of an application by moving the heavy processing into a Component Object Model (COM)
component.
When using C++, it is highly recommended that you or your team have access to a C++ guru who can act as a mentor.

7 ©1995-2004 CNET Networks, Inc. All Rights Reserved.


C++

Online resources

Newsgroups
These are the two top C++ newsgroups. If you have any C++-related question, post it here and you are almost
guaranteed a reply in one or two days:
comp.lang.c++

comp.lang.c.moderated

The C++ Users Journal


The C++ Users Journal is one of the best online C++-magazines and is designed for medium-to-advanced C++ program-
mers. It has a C++ experts column, featuring leading experts such as Herb Sutter, Andrei Alexandrescu, and others.

GNU Compiler Collection


The GNU Compiler Collection (GCC) is one of the most popular free C++ compilers and implements most of the ANSI
C++ standard.

C++ libraries
The Boost Web site is a very useful collection of libraries for C++. It is almost impossible not to find at least one library
you can successfully use in your current project. The documentation is very good. If you run into any problems, you can
subscribe to the boost-developer list, post your problem, and you’ll quickly get an answer.

STL implementation
STL-port is a very popular implementation of the STL, in case your compiler vendor has not provided one.

ANSI C++ compiler


Comeau Computing provides a C++ compiler considered to be the best at implementing the ANSI C++ standard.
Also, you can compile your C++ code online.

Get free C++ tips in your inbox


If you need to add C++ performance to your applications, subscribe to Builder.com’s free C++ e-newsletter. Delivered
every Wednesday, this e-newsletter supplies the tips and solutions you need. Visit our newsletter center to subscribe to
the C++ e-newsletter.

8 ©1995-2004 CNET Networks, Inc. All Rights Reserved.


C++

Other resources

The C++ Programming Language: 3rd Edition


Bjarne Stroustrup, Addison-Wesley, 1997, ISBN 0-201-88954-4. A must-have for any C++ programmer.
It is highly recommended, especially if you’re learning C++ right now.

Writing Solid Code: Microsoft’s Techniques for Developing Bug-Free C Programs


Steve Maguire, Microsoft Press, 1993, ASIN 1556155514. A very useful book showing many of the traps that you could
run into when programming in C or C++.

Effective C++, 2nd Edition


More Effective C++
Scott Meyers, Addison-Wesley, 1998 and 1996, ISBN 0-201-92488-9 and 0-201-63371-X. These are very useful books
showing many of the C++ traps and how to avoid them.

Generic Programming and the STL: Using and Extending the C++ Standard Template Library
Matthew H. Austern, Addison-Wesley Professional, 1998, ISBN 0-201-30956-4. This book explains the STL—its con-
cepts and algorithms, including examples.

Additional resources

Application Development: Persisting settings in C++

Reduce complexity and boost readability using STL functors and predicates

C++: In search of the perfect convert-to-string function

C++: Removing duplicates from a range

Whitepapers

Persistence EdgeXtend for C++


Persistence EdgeXtend for C++ helps organizations meet the challenges of enterprise software development by
reducing risks during application design and deployment.

Visual C++ in Whidbey: What’s New


The Whidbey release of Visual C++ includes many features and improvements that maximize the power and potential of
programs written in C++.

Rogue Wave LEIF—A Lightweight Approach to Integrating C++ Applications with the Enterprise
This paper presents Rogue Wave Lightweight Enterprise Integration Framework (LEIF), a comprehensive technology
platform that leverages industry-standard networking, XML, and Web services technologies to easily integrate C++
applications directly with the rest of the enterprise infrastructure.

9 ©1995-2004 CNET Networks, Inc. All Rights Reserved.


C++

About Builder.com
Thank you for downloading this Builder.com tool; we hope it helps you make better technology decisions. If you need
help with the site or just want to add your comments, let us know.
Builder.com provides actionable information, tools, trialware, and services to help Web and software developers get
their jobs done. Builder.com serves the needs of developers on all major development platforms, including .NET and
J2EE, and supplies the knowledge and tools every developer needs to build better and more robust applications.
Free how-to articles: Covering everything from open source software to the latest .NET technologies, Builder articles
give developers the breadth and depth of coverage they need to build better applications.
Free e-newsletters: Keep up to date on any aspect of the developer industry—from Web services to Visual Basic—with
Builder’s e-newsletters, delivered right to your e-mail inbox.
Free trialware: We’ve collected all the latest trialware and free downloads—covering everything from application servers
to HTML editors—to make your job easier.
Discussion Center: Open a discussion thread on any article or column, or jump into preselected topics, such as Java,
HTML, and career management. The fully searchable Discussion Center brings you the hottest discussions and threads.
Your free Builder membership opens the door to a wealth of information. Our online developer community provides
real-world solutions, the latest how-to articles, and discussions affecting developers everywhere. Get access to full-text
books, exclusive downloads, and posting privileges to our discussion boards, all free!

10 ©1995-2004 CNET Networks, Inc. All Rights Reserved.

You might also like