CPlus Pres 1
CPlus Pres 1
What is C++ ?
C++ is a Object oriented programming language. Initially named as C with classes. C++ was developed at AT & T Bell Labs. C++ is superset of C. Three important facilities are added onto C. Classes Functions overloading Operator overloading C++ also allows us to create hierarchy related objects. All C programs are also C++ programs with few differences.
Input / Output
# include <iostream.h> OR # include <iostream> using namespace std
std: standard input/output
cin and cout are predefined objects in <iostream.h> for single interface. cin >> number is an input statement & causes program to wait for user to type in a number. The identifier cin is a predefined object in C++ that corresponds to the standard input stream (keyboard).
Operator >> is known as extraction or get from operator that extracts or gets value from keyboard. This corresponds to scanf( ) . The statement cout << number causes program to put the value of number on standard output stream (screen in this case). Operator << is called insertion or put to operator . Functions printf () & scanf () can still be used but include header file <stdio.h>.
Comments
C /* */ C ++ /* */ useful for multiple lines // useful for single comment line & cant be inserted within the text of a program.
Include files Class declaration Class functions definitions Main function program
So p can be assigned a pointer value of any basic data types. void pointer may not be dereferenced.
User Defined DT
struct and union are same as in C enumerated DT slightly differ in C++ enum shape {circle, square, triangle}; 0 1 2 here shape becomes new type name and can be used to declare new variables. shape ellipse; enum color {red, blue=4, green=8} 0 enum color {red=5, blues=6, green=7} enum {off, on} {without name} 0 1 int switch1 = off; int switch2 = on;
Pointers
int * i; i = & x; // address of x is assigned to i *i = 50; // 50 value assigned to a location // pointed out by i i.e. assigining // value 50 to x through indirection.
10
Variable declaration
In C, all variables are declared at the beginning of the scope. But in C++, declaration of a variable be anywhere in the scope but before the first use.
Advantage
It makes program easier to understand.
Disadvantage
Cant see all variables at a glance used in the scope. Additional feature of C++ is in dynamic initialization i.e., it permits runtime initialization. float average = sum / i;
11
Constants
C++ constants are to be initialized as:
const int size =10; char name[size];
enum { X, Y, Z}; const X = 0; const Y = 1; const Z = 2; enum { X=10, Y=20, Z=15}; const X = 10; const Y = 20; const Z = 15;
12
Reference variables
C++ introduces a new kind of variable called reference variable that provides an alias for previously defined variable.
data type &ref_var = var_name float total; float &sum = total;
sum and total both are same locations. // a is initialized to new line constant char &a = \n Major application is in passing arguments to functions Call by reference mechanism is provided in C++ explicitly
13
Declaration in an inner block hides a declaration of the same variable in an outer block
14
Along with malloc() & calloc(), C++ also defines two unary operators new and delete. These operators operate on the free store of memory (also called free store operators). Life time of an object is directly under our control & unrelated to a block structure. Object created with new will remain until destroyed using delete.
Including user defined pointer_var = new data_type; both of the same type int *p; float *q; p = new int[2]; q = new float; int *p = new int[2]; float *q = new float;
15
Creates memory space for an array of 2 integers where p[0] refers to first element.
delete p; delete q; delete p[ ]
specify size
16
Functions in C++
The function int main ( ) returns a value of type int to the operating system.
(optional as it takes by default)
If int before main ( ) is specified then return statement for termination be used. Normal convention is that if value 0 is returned then the program ran successfully while non zero value means some problem.
17
Function prototyping is must in C++ which gives compiler details as number and type of arguments and return type.
float volume (int, float, float);
However in C, ( ) means any number of arguments . In C++, this can be written open parameter list as void do-something ()
18
Call by reference
In C++, parameters can be passed as reference or value but in C it is passed by value only.
void swap (int &a, int &b) { int t =a; int t; t = a; a = b; b = t; }
In C++
Call - swap(m,n)
void swap (int *a, int *b) { int t; t = *a; *a = *b; *b = t; }
In C Call swap(&m,&n)
19
Return by reference
A function can also return a reference int &max (int &x, int &y); { if (x > y) return x; else return y; } Call max (a, b) returns a reference to either a or b depending upon whether value of a or b is returned. This implies that function call can appear on L.H.S in contrast to other programming Languages (including C).
max ( a, b ) = -1
assigns
a = -1 if a > b b = -1 , otherwise
20
Default Arguments
C++ allows to call a function without specifying all its arguments. In such cases default values are specified when function is declared. Default values are always specified from right to left.
float amount (float p, int t = 3, float r = 0.15);
21
Function Overloading
Same function name can be used to create variety of tasks . It is called function polymorphism in OOP. // declarations int add (int, int); int add (int, int, int); double add (double, double); double add (int, double); double add (double, int); // Calls x = add(5,10); x = add(5,10,15); x = add(2.5,10.2); x = add(5,10.9); x = add(5.5,10);
22
Compiler tries to find exact match where types of actual arguments match. If exact match is not found then it performs internal conversions. float long int float float int
etc.
For multiple matches error message is generated. long sq (long x); double sq (double x); sq (10) long double
error message
23
Inline function
Ordinary function are compiled separately and are called as and when required. In order to save time/overheads in calling function & returning to called program, a powerful facility is available in C++ . Inline function is defined such as
inline int sq (int x ) {return (x *x) } call to inline function is same p = sq (2); q = sq (3);
Inline function are not called at execution time instead function call is expanded by the body of function.
24
Inline modifier lets compiler mark a particular function to be expended rather than compiled. C++ compiler may ignore your request if your function is too long. Advantage of inline function is that it can help you to write well designed, modular programs that remain efficient at the code level.
const rate = 1.5 inline float tax (x) { return (x * rate ) };
y = tax(p + 2);
25
In C, similar effect is achieved by macro definition defined by primitive # define. Here macro preprocessor performs textual substitution. # define rate 1.5 # define tax (x) x * rates Macro call tax (p + 2) is expanded as p + 2 * rate which is not the intention. Macros cant have local variables and it does not even define a block. Macros also do not permit parameter checking. C++ solves the drawbacks of C macro with inline function which is small function of one or two lines.
26
may not work. Functions returning values, if a loop, a switch or a goto exist. Functions not returning values if a return statement exists. If functions contain static variables. If functions are recursive.