Introduction
This primer
is designed to give an overview of C++. Detailed syntax is beyond the scope
of the Primer. It is not the goal of the Primer to teach one to program
in C++, but to give those curious a better idea what C++ is all about. To
learn C++ it is suggested that one take a professional course in it. Such
courses are usually available at Community Colleges and Universities as
well as on-line. An excellent Free course is available from CodeWarriorU
(www.codewarrioru.com).
What
is C++
C++ is a powerful computer
programming language. With C++ the sky is the limit as to what kind of program
you can create. Unless you are exceptionally gifted, don't plan on learning
C++ overnight. Or in less than 6 months, even if you are very smart.
In the early 1970's
Bell Laboratories experimented with new programming languages. In 1972 Dennis
Ritchie of Bell Laboratories working with Ken Thompson on the UNIX operating
system, developed the "C" programming language. One may wonder "why C?"
Actually Thompson had developed a "B" language (which probably came from
an "A" try) which was used as a basis for the "C" language.
By the way, there
is a D programming language. D was conceived in December 1999 by Walter
Bright. D is a general purpose systems and applications programming language.
It is a higher level language than C++, but retains the ability to write
high performance code and interface directly with the operating system API's
and with hardware. D is well suited to writing medium to large scale million
line programs with teams of developers. D is easy to learn, provides many
capabilities to aid the programmer, and is well suited to aggressive compiler
optimization technology. For more information about D, check http://digitalmars.com/d/index.html.
C gives the programmer
nearly complete control over a computer. C programs are written in plain
text or ASCII. This is known as source code. The "source code" is then complied
into "object code." Object code is the one and zero language of computers.
Object code is very compact (all comments and non-required code are stripped
out) and runs very fast. While not impossible to, at least go partially
backward and produce source code, the compiled object code offers a fair
amount of protection from those who would steal your ideas. Compiled standard
console versions (this is what is known as command line interface where
just the keyboard is used, no mouse interaction and no graphics) run on
most any platform with no modifications as long as the source code is compiled
for the platform being used. For graphical user interfaces, special calls
are made for each platform.
In 1989 the American
National Standards Institute(ANSI) adopted a standard for C. This version
of C is known as C89. C89 was later adopted by the International Standards
Organization (ISO) and was slightly amended in 1995. Standards are very
important. One can invest a lot of time and money learning a language. Standards
assure that the language will be widely accepted and around for the near
future.
So far we have been
talking about C not C++. In 1979 Bjarne Stroustrup created C++. C++ is built
on a foundation of C. It wasn't until 1998 that an ANSI/IOS standard for
C++ was adopted. Sometimes C89 is referred to as a "C subset of C++." C++
uses most of C89 plus much more. In fact, the C++ language syntax is nearly
twice the size of C89.
In 1999 a new ANSI/IOS
for C was adopted. This new standard is C99. This includes most of C++ plus
adds some new features. There are also some incompatibilities with both
C89 and C++. At this time, C99 is not widely used and C++ still reins at
the top.
C++ is sometimes called
an Object Oriented Program (OOP). C++ has also been called "C with Classes."
One can take advantage of many of the C++ features without ever using OOP
or Classes. However, the ability to use them increases the power available.
Basic
Format of C++
All programs must have
a main function. This is where the program starts and ends. Calls
to other parts of the program are made from here. The main function
can also have additional functions within main. The basic syntax for
main is as follows:
int main()
{
calls
and functions;
return
0;
}
or
void main()
{
calls
and functions;
}
The second version
may not work properly with some compilers, however.
Many may wonder what
the void is all about. It simply means that the function does not
return a value. In C and C++ you can put things in the ( ) area and
values determined later in the program can be returned to this.
Font Uppercase and
Lowercase
C and C++ characters
are case sensitive. All keywords are lowercase. A trick to avoid using a
keyword unintentionally is to include at least one uppercase letter in each
non-keyword name. The following are treated as separate variables and functions.
myfunction()
Myfunction() // Guaranteed not to be a key word because of at least
one uppercase character
MyFunction() // Guaranteed not to be a key word because of at least
one uppercase character
myvariable
Myvariable
// Guaranteed not to be a key word because of at least one uppercase character
MyVariable // Guaranteed not to be a key word because of at least
one uppercase character
Semicolons
Almost all C and C++
statements end in semicolons. Leaving off a semicolon can produce a host
of errors and many times the errors are not close to the lacking semicolon.
Notes
and Comments
In
C, putting notes and comments into the code was done with /* and */.
/*
Text Note Text Note Text Note
*/
This allowed large
multi line sections to contain notes and be bracketed by the /* at the start
and the */ at the end.
In C++ a line of a
note or comment can also use the /* and */, but the preferred way is to
use a // at the start of each comment line. Everything on the line after
the // is considered part of the note or comment.
//Text Note
//Text Note
//Text Note
MyFunction() //Text Note
The // is helpful for
long comments. If there is not a // at the start of line, then it's not
a note or comment.
Input and Output
With Standard Console
mode both C and C++ programs are limited to keyboard input and screen display.
To get data elsewhere (from an external device or connection) or to output
data to a print or other device it is necessary to use platform specific
calls. This is one more reason why porting a completed program between computer
platforms (e.g., between MacOS and Windows) requires much more than just
compiling source code in the new environment.
In C the program used
scanf() to input data from the keyboard and printf() to send
data to the screen.
printf("What
is the information?\n");
scanf("%s",
data); printf("The information is, %s\n", data);
The C program will
display:
What
is the Information?
The user enters:
The
Universe (return)
The screen displays:
The
information is The Universe
In C++ the basic input
and output is done with cin and cout. When a C++ program begins
execution, there are four built-in functions called "streams" that are opened
automatically.
|
Stream
|
Meaning
|
Default
Device
|
|
cin
|
Standard
Input
|
Keyboard
|
|
cout
|
Standard
output
|
Screen
|
|
cerr
|
Standard
error output
|
Screen
|
|
clog
|
Buffered
version of cerr
|
Screen
|
There are also wide
character version of each of the above; wcin, wcout, wcerr
and wclog.
Multibyte and Wide
Character
The cin is
used with >> or cin >> and the cout is used with <<
or cout <<. The >> is an input operator and called the extractor
because extracts data from the input stream. The << is an output
operator and called the inserter because inserts data into the output
stream.
The above C example
using the C++ cin/cout would be
cout
<< "\nWhat is the information?" << endl;
cin >> data; cout << "\nThe information is " data<< endl;
The C++ program will
display:
What
is the Information?
The user enters:
The
Universe (return)
The screen displays:
The
information is The Universe
Backslash Codes
Note: The Backslash
Codes are the same in C and C++ and are used for formatting the display
text.
|
Code
|
Meaning
|
|
\b
|
backspace
|
|
\f
|
form
feed
|
|
\n
|
new
line
|
|
\r
|
carriage
return
|
|
\t
|
horiznatal
tab
|
|
\"
|
double
quote
|
|
\'
|
single
quote
|
|
\o
|
null
|
|
\\
|
backslash
|
|
\v
|
verticle
tab
|
|
\a
|
alert
|
|
\?
|
question
mark
|
|
\N
|
octal
constant (N= value
|
|
\xN
|
hexadecimal
constant (N= value)
|
Data Hierarchy
Bits
At the bottom of the data hierarchy is a bit. A bit and be in one of two
states. The states used in computers are one and zero and are equivalent
to true and false and a plus voltage and zero voltages (or some voltage
range).
Bytes
Bytes are normally eight bits. This provided 256 combinations. Characters
and functions can be represented by bytes. In ASCII the uppercase "A" is
represented by 10000001 and the lowercase "a" by 01100001.
Wide Characters and
Multibyte Characters
Some C/C++ compilers
support double-byte Kanji, Chinese/Taiwanese and Korean characters. This
support is enabled using a compiler switch. The switch is -zk{0,1,2} where
0=Kanji, 1=Chinese/Taiwanese and 2=Korean.
Wide characters are
much simpler than multibyte characters. They are simply characters with
more than eight bits, so that they have room for more than 256 distinct
codes. The wide character data type, wchar_t, has a range large enough
to hold extended character codes as well as old-fashioned ASCII codes.
An advantage of wide
characters is that each character is a single data object, just like ordinary
ASCII characters. Wide characters also have some disadvantages:
* A program must
be modified and recompiled in order to use wide characters at all.
* Files of wide characters
cannot be read by programs that expect ordinary characters.
Wide character values
0 through 0177 are always identical in meaning to the ASCII character codes.
The wide character value zero is often used to terminate a string of wide
characters, just as a single byte with value zero often terminates a string
of ordinary characters.
The basic element of
text is represented as type Character. A variable of type character can
hold, well, a character. More precisely, something of type Character can
represent any one of the 256 possible characters in the ``Latin-1'' set.
Type Character is sufficient for handling most languages written using Latin-based
characters, such as English, French, and Spanish. Latin-1 is a superset
of the ASCII character set (also called ISO 646), so Character is the right
type for processing ASCII text files.
If you need to handle
non-Latin alphabets (such as Chinese or Arabic) you would use Wide_Character
instead of Character. A Wide_Character can represent any character from
the entire ISO 10646 character set.
Fields
A field is made of one or more bytes or characters. A variable or a constant
is a field. Myfield is an example.
Records
A record contains sets of fields with common information for the record.
In C and C++ this is a template and can be a Structure. In C++ a Class
is a template or structure for a record and an Object is each data
filled record that is created (known as being instantiated).
Files
A file contains sets of a given type of record (all the same fields) with
different data in each record.
Basic Pointers
Both C and C++ use
pointers.
In both C and C++:
An ampersand symbol & (& for address of) in front of
a variable name indicates that you want the address of the variable rather
than the value of the variable.
X
= &D
// The address of the variable D into X.
//
It is said that X now points to (the address of) variable D.
By contrast using
the asterisk * the value of the variable is accessed.
X
= *D
// the value at address D is put into X or p = &x
// the address of x is put into p *p = 25
// the value 25 is put into the address p (formerly the address of x)
Example:
//
Using pointers
void swap (int*x, *y)
{
int
temp;
temp = *x; // save the value a address x in temp
*x = *y // put y in x *y = temp; // put
temp (or original x) into y
}
calling
the function swap()
int a, b;
a= 25; b = 67;
swap(&a, & b) // a is now 67 and b is now 25
Pointers to Class
Members
C++ allows a special
type of pointer to be generated that "points" generically to a member of
a class (pointer to a member), not to a specific instance of that member
in an object. This is not the same as a normal C++ pointer. A pointer to
a member provides only an offset into an object of the member's class. To
access the member of a class given a pointer to it (the class), special
operators are sued (.* and ->*). The .* operator is used to access a reference
to an object. To access an object the ->* is used.
The form used to declare
a pointer to a member is:
type
class-name:: *ptr;
C Structures
In C, the structures
must contain only data members. There are no private, public and protected
parts.
An example of a structure
in C:
struct
Time
{
int
Hour;
int Min;
int Second;
};
C++ Structures
In C++ structures
are classes. The only real difference is that while private is default
for a classes, public is default for structures in C++"
Example of a C++ Structure:
struct
ClassName
{
public:
// Default
// definitions
of public elements
// (usually functions)
private:
// definitions
of private elements
// (usually stored data)
friend
void Myfunction()
//Myfunction has access to the private members
protected:
// definitions
of protected elements
// (usually stored data)
};
Classes
Classes are the key
to C++. Originally Bjarne Stroustrup (the creator of C++) called it "C with
Classes," but the name was quickly shortened to C++.
There are no classes
in C. The class is C++'s basic unit of encapsulation. As mentioned above
a Class is a template from which objects are created.
A class is defined
using the class keyword. A class is a collection of variables and
functions that manipulate those variables. The variables (fields) that form
a class are called members.
The following is the
general format for a class declaration (the order of private, protected
and public is not important):
class ClassName
{
private: // default
// definitions
of private elements
// (usually stored data)
friend void
Myfunction()
//Myfunction has access to the private members
protected:
//definitions
of protected elements
//(usually stored data)
public:
//definitions
of public elements
//(usually functions)
};
In the above example,
if no type is specified, it is implied the elements and variables will be
private.
private: Available
only within the class and designated friends.
protected:
Available only within the class and derived classes.
public: Available
to all in the program.
Friends
If necessary you can
override the private or protected access by declaring a class a friend
of another class. Friend classes have access to the variables and functions
of the class to which they are designate as friends.
Example:
class
MyWork
{
friend Staff;
private:
Mystuff() ....
public:
....
protected:
....
};
This means that all
parts of th Staff class have access to all parts of the MyWork
class (private, public and protected). To declare a friend function, include
the keyword friend followed by the function's prototype name
from the class to which the function will be a friend. friend Mystuff
Objects
As one might expect
Objects are the basis for Object Oriented Programming.
What is an Object?
An object is an entity that has data that describe it and actions that it
can perform. An object is something that has physical existence, e.g., an
airplane, a person or an event.
This can sometimes
be a very confusing point for those learning C++.
To create an object
of a class just specify the class name and object name.
Example:
MyClass
Stuff
// The object Stuff is created using the members of class MyClass
Spacecraft Devices
// The object Devices is created using the members of class Spacecraft
Constructors
and Destructors
No, this is not about
Civil Engineering with cranes and bulldozers.
Constructors
A constructor is used to initialize class members by setting variables equal
to zero (default) or some other value. A constructor does not have return
values. Constructors take the class name. There can be multiple constructors
in a class. There are multi flavors of constructors, default, parameterized,
explicit, implicit, overloaded, copy and convert constructors.
Default Constructors
A default constructor is a constructor that can be invoked with no arguments/parameters.
There can only be one default constructor per class. If one is not stated
in the code by the programmer, the compiler will create one.
Example:
class Data
{
Data(); // Default
constructor
{ }
};
Parameterized
Constructors
A parameterized constructor is just one that has parameters specified in
it.
Example:
class Data
{
Data(float,
int, char); // Parameterized constructor
{ }
};
or
class Data
{
Data(float x,
int y, char a); // Parameterized constructor
{ }
};
Explicit
Constructors
The keyword explicit is a Function Specifier." The explicit specifier applies
only to constructors. Any time a constructor requires only one argument
either of the following can be used to initialize the object. The reason
for this is that whenever a constructor is created that takes one argument,
it also implicitly creates a conversion from the type of that argument to
the type of the class. A constructor specified as explicit will be used
only when an initialization uses the normal constructor syntax, Data (x).
No automatic conversion will take place and Data = x will not be allowed.
Thus, an explicit constructor creates a "nonconverting constructor."
Example:
class Data
{
explicit Data(float
x); // Explicit constructor
{ }
};
Implicit
Constructors
If a constructor is not stated as explicit, then it is by default an implicit
constructor.
Overloaded
Constructors
The same constructor name can be used with multiple cases of the constructor.
The whole string is used by the compiler to identify the constructor, not
just the constructor name.
Example:
class Data
{
Data(); // Default
constructor
{ }
Data(int y,
int z); // Overloaded constructor Data()
{ }
Data(int a,
int b), float c); // Overloaded constructor Data()
{ }
};
Copy
Constructors
One of the more important forms of an overloaded constructor is the copy
constructor. The purpose of the copy constructor is to initialize a new
object with data copied from another object of the same class.
Example:
class Data (Data);
// Class Data declares a copy constructor Data
{
Data :: Data
(Data Test) // Implemented
{
Stuff
}
};
or
class Data //
Class Data declares a copy constructor Data
{
Data (); //
Default constructor
Data (Data &
) // Copy constructor
Data (const Data
& ) // Copy constructor
{
Stuff
}
};
In both
copy constructors in the second example, the parameter type is a reference.
You cannot create a copy constructor using the class tag as this will create
an error. If a copy constructor is not defined, the compiler will provide
one.
Convert
Constructors
A convert constructor is an alternative to overloading. It is a method in
which a constructor is used to convert a non-class member object to a class
member object.
Example:
class Data
{
public: Data
() // Default constructor
{
xyz = "Unknown";
}
Data (const
string& a) // Convert constructor
{
xyz= a;
}
Data (const char*
a) // Convert constructor
{
xyz= a;
} stuff
private:
string xyz;
};
Destructors
A destructor performs termination house keeping. Destructors clear up memory.
Destructors are used primarily with classes with dynamic allocated memory.
A destructor receives no parameters and returns no value. There may be only
one destructor in a class. Destructors cannot be overloaded.
Example:
class Time
{
Time();
//Default constructor
~Time();
// Destructor
};
Namespaces
In C++, it is possible to create local scope using the namespace keyword.
A namespace defines a declarative region. Its purpose is to localize names.
The format is:
namespace MyNameSpace
{
int count;
}
Here, MyNameSpace is
the name of the namespace with the variable count declared inside it.
When C++ was originally
invented, items declared in the C++ library were in global (i.e., unnamed)
namespace. However, Standard C++ puts all those items into the std namespace.
Hence:
using
namespace std;
Operators
Dot (.) Operator
The dot operator accesses a structure or class member via the variable name
for the object or via a reference to the object.
Example
cout
<< Data.Stuff
This will
display the member Stuff of the structure referenced by Data.
Scope
Resolution (::) Operator
The scope resolution operator specifies the scope to which a member belong.
Example
Data::MyStuff
Data
is the class or namespace that contains the member MyStuff. To reference
a global scope, the scope name is not specified. For example to refer to
a global variable called MyData that is being hidden by a local variable
called MyData, use
::
MyData
Polymorphism
Polymorphism is the ability to have classes in the same inheritance hierarchy
respond differently to the same message. A program is using polymorphism
when member functions in different classes have the same signature, but
differ in content of the function body.
Example:
#include
<iostream>
using
namespace std;
class B // Base
Class B
{
public:
int i;
virtual void Print()
// Virtual Function print_i()
// Function prints the current value of i and "-inside B"
{
cout << i
<< "-inside B" << endl;
}
};
class D : public
B // Derived Class D
{
public:
void Printi()
// inherited Virtual Function Print()
// Function prints the current value of i and "-inside D"
{
cout << i
<< "-inside D" << endl;
}
};
int main()
{
B b; // Instantiates
object b of class B
B* pb = &b;
// &b is the address of b
cout << "\n&b=
" << &b << endl;
cout << "\n&b= " << Address << endl;
cout << "pb= " << pb << endl;
D f; // Instantiates
object f of class D
f.i = 1 + (b.i
= 1);
// b.i sets int i in Base Class B to 1
// f.i sets int i in Derived Class D to 1
// + the value of i in the Base Class B
pb -> Print();
// Calls Print() for Base Class B
pb = &f;
// Allows implicit conversion
// &f is the address of f
// pb now is equal to the address of f
cout << "\n&f=
" << &f << endl;
cout << "pb= " << pb << endl;
pb -> Print();
// Calls Print() for Derived Class D
return 0;
}
Inline
Functions
C++ uses the inline function to reduce execution-time overhead. The keyword,
inline, informs the compiler to generate a copy of the functionÕs code in
place instead of generating a function call. Default values can also be
defined when using inline functions.
Trade-offs:
Some compilers can ignore the inline keyword for all except for the smallest
functions. Multiple copies of the function code are inserted in the program
rather than having the program pass control to a single copy each time the
function is called.
Example:
// Using an inline
function to calculate the volume of a cube
#include <iostream>
using namespace std;
inline float cube(
const float s ) { return s * s * s; }
main ()
{
cout << ÒEnter
the side length of your cube: Ò;
float side;
cin >> side;
cout << ÒVolume of cube with side Ò << side << Ò is Ò << cube( side
) << endl;
return 0;
}
Default
value example
// Using default
arguments.
#include <iostream>
//
Calc the volume of a box inline
int BoxVolume( int iLength = 1, int Width = 1, int iHeight = 1 ) { return
iLength * iWidth * iHeight; }
main()
{
cout << ÒThe
default box volume is: Ò << BoxVolume() << endl << endl
<< ÒThe volume of a box with length 10, width 1, and height1
is: Ò << BoxVolume(10) << endl << endl
<< ÒThe volume of a box with length 10, width 5, and height 1 is: Ò
<< BoxVolume(10, 5) << endl << endl
<< ÒThe volume of a box with length 10, width 5, and height 2 is: Ò
<< BoxVolume(10, 5, 2) << endl;
return 0 ;
}
Tips
The ? operator. This can be used to replace and simplify the if-else
statement.
For example:
With the
if-else statement:
if(b
< 22) a= 33
else a= 99;
With
the ? operator:
a
= (b < 22) ? 33 : 99
If b
is less than 22, a equals 33, else a equals
99.
Using
the ? operator not only saves typing, the compiler can produce much
faster code than when using the if-else statement.
Sample
Code
Sample
1
Reading and printing a sequential file.
Sample
2
C++ Sample Code Using Classes.
Sample
3
More
Complex Code Using Classes
Page
created 18 November 2003
Modified 18 November 2003
RETURN