We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51
Getting Started with C++
Prepared for CSIT 2nd Semester | New Summit College
C++ is a structured Language • C allows compartmentalization of code and data hence called a structured language. • One way that you achieve compartmentalization is by using subroutines that employ local (temporary) variables. • By using local variables, you can write subroutines so that the events that occur within them cause no side effects in other parts of the program. • C’s main structural component is the function. • In C, functions are the building blocks in which all program activity occurs. They allow you to define and code separately the separate tasks in a program, thus allowing your programs to be modular. C++ is a structured Language • Another way to structure and compartmentalize code in C is through the use of code blocks. • A code block is a logically connected group of program statements that is treated as a unit. • In C, you create a code block by placing a sequence of statements between opening and closing curly braces. Keywords in C & C++ Data Type • Five basic data types are char, int, float, double, and void. • The size and range of these data types may vary between processor types and compilers. • To the five basic data types defined by C, C++ adds two more: bool and wchar_t. • Standard C++ does not specify a minimum size or range for the basic types. Instead, it simply states that they must meet certain requirements. • For example, Standard C++ states that an int will “have the natural size suggested by the architecture of the execution environment.“ • Each C++ compiler specifies the size and range of the basic types in the header <climits>. Modifying the basic types • Except for type void, the basic data types may have various modifiers preceding them. • The list of modifiers is shown here: • Signed • Unsigned • Long • Short • You can apply the modifiers signed, short, long, and unsigned to integer base types. • You can apply unsigned and signed to characters. You may also apply long to double. Identifier Names • In C/C++, the names of variables, functions, labels, and various other user-defined objects are called identifiers. • The first character must be a letter or an underscore, and subsequent characters must be either letters, digits, or underscores. • Here are some correct and incorrect identifier names:
**Note that in an identifier, upper- and lowercase are treated
as distinct. Hence, count, Count, and COUNT are three separate identifiers. Variables • A variable is a named location in memory that is used to hold a value that may be modified by the program. • All variables must be declared before they can be used.
• Variables will be declared in three basic places: inside functions, in
the definition of function parameters, and outside of all functions. These are local variables, formal parameters, and global variables. Variables (contd.) • In C, you must declare all local variables at the start of a block, prior to any "action" statements. • However, in C++, this function is perfectly valid because you can declare local variables at any point within a block, prior to their first use. Formal Parameters • If a function is to use arguments, it must declare variables that will accept the values of the arguments. • These variables are called the formal parameters of the function. • They behave like any other local variables inside the function. Storage Class Specifier • There are four storage class specifiers supported by C: • Extern • Static • Register • Auto • These specifiers tell the compiler how to store the subsequent variable. • C++ adds another storage-class specifier called mutable. extern Type Conversion Multiple Assignments • C/C++ allows you to assign many variables the same value by using multiple assignments in a single statement. • For example, this program fragment assigns x, y, and z the value 0: Preprocessor Directive • The preprocessor contains following directives: True/False in C++ • A conditional expression evaluates to either a true or false value. • In C, a true value is any nonzero value, including negative numbers. A false value is 0. • This approach to true and false allows a wide range of routines to be coded extremely efficiently. • C++ fully supports this definition of true and false. But C++ also defines a Boolean data type called bool, which can have only the values true and false. • In C++, a 0 value is automatically converted into false and a nonzero value is automatically converted into true. And vice versa. Namespaces • Namespaces are to localize the names of identifiers to avoid name collisions. • It localizes the visibility of names declared within it, a namespace allows the same name to be used in different contexts without conflicts arising. • For example, if your program defined a function called abs( ), it could (depending upon its parameter list) override the standard library function abs( ) because both names would be stored in the global namespace. • Name collisions were compounded when two or more third-party libraries were used by the same program. Namespaces (contd.) • The C++ library is now defined within its own namespace, called std, which reduces the chance of name collisions. • You can also create your own namespaces within your program to localize the visibility of any names that you think may cause conflicts. • Anything defined within a namespace statement is within the scope of that namespace. • Below is an example of a namespace. • It localizes the names used to implement a simple countdown counter class. In the namespace are defined the counter class, which implements the counter, and the variables upperbound and lowerbound, which contain the upper and lower bounds that apply to all counters. Namespaces (contd.) Namespaces (contd.) • Inside a namespace, identifiers declared within that namespace can be referred to directly, without any namespace qualification. • For example, within CounterNameSpace, the run( ) function can refer directly to lowerbound in the statement:
• However, since namespace defines a scope, you need to use the
scope resolution operator to refer to objects declared within a namespace from outside that namespace. Namespaces (contd.) • For example, to assign the value 10 to upperbound from code outside CounterNameSpace, you must use this statement:
• Or to declare an object of type counter from outside
CounterNameSpace, you will use a statement like this: The std namespace • Standard C++ defines its entire library in its own namespace called std. • This is the reason that we mostly use the following statement in our c++ program:
• This causes the std namespace to be brought into the current
namespace, which gives you direct access to the names of the functions and classes defined within the library without having to qualify each one with std::. The std namespace • Of course, you can explicitly qualify each name with std:: if you like. • Here, cout, cin, and the manipulator hex are explicitly qualified by their namespace. The std namespace (contd.) • If you are using only a few names from the standard library, it may make more sense to specify a using statement for each individually. • The advantage to this approach is that you can still use those names without an std:: qualification, but you will not be bringing the entire standard library into the global namespace. Input/Output Streams • C++ supports two complete I/O systems: the one inherited from C and the object- oriented I/O system defined by C++. • Since the I/O system inherited from C is extremely rich, flexible, and powerful, you might be wondering why C++ defines yet another system. • The answer is that C's I/O system knows nothing about objects. • Therefore, for C++ to provide complete support for object-oriented programming, it was necessary to create an I/O system that could operate on user-defined objects. Input/Output Stream (contd.) • Standard C++ provides support for its I/O system in <iostream>. In this header, a rather complicated set of class hierarchies is defined that supports I/O operations. • When a C++ program begins execution, four built-in streams are automatically opened. Input/Output Stream (contd.) • By default, the standard streams are used to communicate with the console. • C++ Supports rich set of functions for performing input and output operations. • The syntax using these I/O functions is totally consistent of the device with I/O operations are performed. • C++’s new features for handling I/O operations are called streams. • Streams are abstractions that refer to data flow. Streams in C++ are : • Output Stream • Input Stream. Output Stream • The output stream allows us to write operations on output devices such as screen, disk etc. • Output on the standard stream is performed using the cout object. • C++ uses the bitwise-left-shift operator for performing console output operation. • The syntax for the standard output stream operation is as follows: cout<<variable; Output Stream (contd.) • The word cout is followed by the symbol << , called the insertion or put to operator , and • then with the items (variables, constants, expressions) that are to be output. Output Stream (contd.) • More than one item can be displayed using a single cout output stream object. • Such out put operations in C++ are called cascaded output operations. cout<<”Age is: “<<age<<”years”; • This cout object will display all the items from left to right. If value of age is 30 then this stream prints Age is : 30 years Output Stream (contd.) • C++ does not restricts the maximum number of items to output. • The complete syntax of the standard output streams operation is as follows: cout<<variable1<<vaariable2<<............<<variableN; • The object cout must be associated with at least one argument. • Like printf in C, A constant value can be sent as an argument to the cout object. cout<<’A’; //prints a constant character A cout<<10.99; //Prints constant 10.99 cout<<” “; //prints blanks cout<<”\n”, //prints new line Input Streams • The input stream allows us to perform read operations with input devices such as keyboard, disk etc. • Input from the standard stream is performed using the cin object. • C++ uses the bit-wise right-shift operator for performing console input operation. • The syntax for the standard output stream operation is as follows: cin<<variable;
<< is called extraction or get operator.
Input Stream (contd.) • Input of more than one item can also be performed using the cin input stream object. • Such input operation in C++ are called cascaded input operations. • For example, reading the name of a person his address, age can be performed by the cin as: cin>>name>>address>>age; Input/Output Stream (contd.) • The following are two important points to be noted about the stream operations. • Streams do not require explicit data type specification in I/O statement. • Streams do not require explicit address operator prior to the variable in the input statement. • In C printf and scanf functions, format strings ( %d,%s,%c etc) and address operator (&) are necessary but in cin stream format specification is not necessary and in the cout stream format specification is optional. • Format-free I/O is special features of C++ which make I/O operation comfortable. Manipulators • Manipulators are instructions to the output stream that modify the output in various ways. • For example endl , setw etc. • Manipulators are operators that are used to format the data display. • endl manipulator • when used in an output statement, causes a linefeed to be inserted. • It has same effect as using the new line character “\n”, cout<<“Welcome home!”<< endl; Using endl manipulator Manipulators (contd.) • setw manipulator • To use setw manipulator the “iomanip.h” header file must be included. • The setw manipulator causes the number or string that follows it in the stream to be printed within a field n characters wide , where n is the argument used with setw as stew(n). • The value is right justified within the field. using setw operator Manipulator • We can also write our custom manipulator. Return by Reference • A function can return a value by reference. This is a unique feature of C++. • Normally function is invoked only on the right hand side of the equal sign. • But we can use it on the left side of equal sign and the value returned is put on the right side. Function Prototyping • The function prototype describes the function interface to the compilers by giving details such as the number and types of arguments and the type of return values. • With function prototyping, a template is always used when declaring and defining a function. • When a function is called, the compiler uses the template to ensure that proper arguments are passed, and the return value is treated correctly. • Any violation would result to compiler time error. Default Arguments • C++ allows us to call a function without providing all arguments. • For that, we need to assign default value to the parameters. • Default values are specified when the function is declared. float interest(float p, float r, int t = 1); • The subsequent function call will then be amount = interest(2000, 2.5); • Also, following is valid. amount = interest(2000, 2.5, 3); Default Argument (contd.) • A default arugment is checked for type at the time of declaration and evaluated at the time of call. • Only the trailing arguments can have default values and therefore we must add defaults from right to left. • We can not provide a default value to a particular argument in the middle of an argument list. • Default arguments are useful in situations where some arguments are always have the same value. Constant Arguments • In c++ an argument to a function can be declared as constant. int length(const string &s) • The qualifier const tells the compiler that the function should not modify the argument. The compiler will generate an error when this condition is violated. • This is valid only for the case of pass by reference or pass by pointers. • Experiement yourself!!! Function Overloading • Overloading refers to the use of same for multiple purposes. • C++ allows us to overload functions i.e. we can use the same function name to create functions that perform a variety of different tasks. • This is known as function polymorphism in OOP. • Using the concept of function overloading, we can design a family of functions with one function name but with different argument lists. • The function would perform different operations depending on the argument list in the function call. • The correct function to be invoked is determined by checking the number and type of the argumetns but not on the function type. Function Overloading (contd.) Dynamic Memory Allocation • In addtion to C (malloc, callos and free) function, C++ provides two additional unary operators new and delete to dynamically allocate and free memory. • These two operators are also called free store operators. • An object can be created by using new, and destroyed using delete when require. • A data object created inside a block with new, will remain in existence until it is explicitly destroyed by using delete. i.e. the lifetime of an object is directly under our control and is unrelated to the block structure of the program. Dynamic Memory Allocation (contd.) • The new operator can be used to create objects of any type. pointer-variable = new data-type; • Here, pointer-variable is a pointer of type data-type. • The new operator allocates sufficient memory to hold a data object of type data-type. • The pointer-variabel holds the address of the memory space allocated. p = new int; q = new float; Dynamic Memory Allocation (contd.) • Alternatively, we can also write int *p = new int; float *q = new float; int *r = new int[10]; When a data object is no longer needed, it is destroyed to release the memory space for reuse. delete pointer-variable; delete [size] pointer-varaible; Dynamic Memory Allocation (contd.) • It is always a good idea to check for the pointer produced by new before using it. End of the chapter