C++ Final Notes
C++ Final Notes
C++ was developed by Bjarne Stroustrup of AT&T Bell Laboratories in the early 1980's, and is based on the C language. C++ is an object oriented programming language, it implements data abstraction using a concept called classes along with some other features of oop. apart of the c++ program are easily reusable and extensible code is easily modifiable without actually having to change the code .The "++" is a syntactic construct used in C (to increment a variable), and C++ is intended as an incremental improvement of C .It contains all features of oops.
#include <iostream.h> #include<conio.h> Void main ( ) { int a,b,c; Cout<< enter the number ; Cin>>a>>b; C=a+b; Cout<< sum <<c; getch (); }
For input - cin << For output cout >> Input /output stream- iostream.h Console input/output- conio.h
()
#include <iostream.h> #include <iomanip.h> #include <conio.h> void main() { int a=12345; clrscr(); cout<<" default is right justified \n" <<setw(10)<<a<<"\n using functions " <<"\n setf to set ios:: left\n" <<setw(10); cout.setf(ios::left , ios::adjustfield); cout<<a<<"\n use unsetf to restore default \n"; cout.unsetf(ios::left); cout<<setw(10)<<a; getch(); }
Constants
Constants are expressions with a fixed value.
Literals
Literals are used to express particular values within the source code of a program. For example, when we wrote: a = 5; the 5 in this piece of code was a literal constant.
Literal constants can be divided in Integer Numerals, FloatingPoint Numerals, Characters, Strings and Boolean Values.
Integer Numerals 1776 707 -273 They are numerical constants that identify integer decimal values. Floating Point Numbers They express numbers with decimals and/or exponents. They can include either a decimal point, an e character (that expresses "by ten at the Xth height", where X is an integer value that follows the e character), or both a decimal point and an e character: 3.14159 6.02e23 1.6e-19 3.0 // 3.14159 // 6.02 x 10^23 // 1.6 x 10^-19 // 3.0
Character and string literals There also exist non-numerical constants, like: 'z' 'p' "Hello world" "How do you do?" The first two expressions represent single character constants, and the following two represent string literals composed of several characters. Notice that to represent a single character we enclose it between single quotes (') and to express a string (which generally consists of more than one character) we enclose it between double quotes (").
Scope of variables
A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block.
sizeof()
This operator accepts one parameter, which can be either a type or a variable itself and returns the size in bytes of that type or object: a = sizeof (char); This will assign the value 1 to a because char is a one-byte long type. The value returned by sizeof is a constant, so it is always determined before program execution.
Setbase() : this is used to convert the base of one numeric value to another base value. The general syntax used is :
setbase(base value);
What Is a Function?
A function is, a subprogram that can act on data and return a value. Every C++ program has at least one function, main(). When your program starts, main() is called automatically. main() might call other functions, some of which might call still others. Each function has its own name, and when that name is encountered, the execution of the program branches to the body of that function. When the function returns, execution resumes on the next line of the calling function. This flow is illustrated in Figure
Why Function?
Well-designed functions perform a specific and easily understood task. Complicated tasks should be broken down into multiple functions, and then each can be called in turn. The key is to keep the level of complication low in each function. Dividing the problem into blocks and building larger solutions from the simplified blocks is a key concept in programming. Functions come in two varieties: user-defined and built-in. Built-in functions are part of your compiler package; they are supplied by the manufacturer for your use. The include files that you have used so far are examples of built-in functions.
The function prototype and the function definition must agree exactly about the return type, the name, and the parameter list. If they do not agree, you get a compile-time error. Note, however, that the function prototype does not need to contain the names of the parameters, just their types.
Default Parameters
For every parameter you declare in a function prototype and definition, the calling function must pass in a value. The value passed in must be of the declared type. Thus, if you have a function declared as long myFunction(int); the function must in fact take an integer variable. If the function definition differs or if you fail to pass in an integer, you get a compiler error.
The one exception to this rule is if the function prototype declares a default value for the parameter. A default value is a value to use if none is supplied. The preceding declaration could be rewritten as long myFunction (int x = 50); Any or all of the functions parameters can be assigned default values. The one restriction is this: If any one of the parameters does not have a default value, no previous parameter can have a default value. If the function prototype looks like long myFunction (int Param1, int Param2, int Param3); you can assign a default value to Param2 only if you have assigned a default value to Param3. You can assign a default value to Param1 only if youve assigned default values to both Param2 and Param3.
Overloading Functions
C++ enables us to create more than one function with the same name. This is called function overloading. The functions must differ in their parameter list, with a different type of parameter, a different number of parameters, or both. Heres an example: int myFunction (int, int); int myFunction (long, long); int myFunction (long);
myFunction() is overloaded with three different parameter lists. The first and second versions differ in the types of the parameters, and the third differs in the number of parameters. The return types can be the same or different on overloaded functions. However, different return types alone are not sufficient to distinguish between overloaded functions.
// function overloading #include <iostream.h> int Double(int); long Double(long); float Double(float); double Double(double); void main() { int myInt = 6500; long myLong = 65000; float myFloat = 6.5; double myDouble = 6.5e20; int doubledInt; long doubledLong; float doubledFloat; double doubledDouble; cout << myInt: << myInt << \n; cout << myLong: << myLong << \n; cout << myFloat: << myFloat << \n; cout << myDouble: << myDouble << \n; doubledInt = Double(myInt); doubledLong = Double(myLong);
doubledFloat = Double(myFloat); doubledDouble = Double(myDouble); cout << doubledInt: << doubledInt << \n; cout << doubledLong: << doubledLong << \n; cout << doubledFloat: << doubledFloat << \n; cout << doubledDouble: << doubledDouble << \n; } int Double(int original) { cout << In Double(int)\n; return 2 * original; } long Double(long original) { cout << In Double(long)\n; return 2 * original; }
float Double(float original) { cout << In Double(float)\n; return 2 * original; } double Double(double original) { cout << In Double(double)\n; return 2 * original; }
This is easier to read and easier to use. You dont have to worry about which one to call; you just pass in a variable, and the right function is called automatically.
Inline Functions
When you define a function, normally the compiler creates just one set of instructions in memory. When you call the function, execution of the program jumps to those instructions, and when the function returns, execution jumps back to the next line in the calling function. If you call the function 10 times, your program jumps to the same set of instructions each time. This means there is only one copy of the function, not 10. There is some performance overhead in jumping in and out of functions. It turns out that some functions are very small, just a line or two of code, and some efficiency can be gained if the program can avoid making these jumps just to execute one or two instructions. When programmers speak of efficiency, they usually mean speed: The program runs faster if the function call can be avoided.
If a function is declared with the keyword inline, the compiler does not create a real function: It copies the code from the inline function directly into the calling function. No jump is made; it is just as though you had written the statements of the function right into the calling function. Note that inline functions can bring a heavy cost. If the function is called 10 times, the inline code is copied into the calling functions each of those 10 times. The tiny improvement in speed you might achieve is more than overshadowed by the increase in size of the executable program.
Some of the situations where inline expansion may not work are:
1. For functions returning values, if a loop , a switch, or a goto exist. 2. For functions not returning values, if a return statement exist. 3. If functions contain static variable. 4. If inline functions are recursive.
#include <iostream.h> inline int Double(int); void main() { int target; cout << Enter a number to work with: ; cin >> target; target = Double(target); cout << Target: << target << endl; target = Double(target); cout << Target: << target << endl; target = Double(target); cout << Target: << target << endl; } int Double(int target) { return 2*target; }
Recursion
Besides calling other functions, a function can call itself. This is called recursion, and recursion can be direct or indirect. It is direct when a function calls itself; it is indirect recursion when a function calls another function that then calls the first function.
It is important to note that when a function calls itself, a new copy of that function is run. The local variables in the second version are independent of the local variables in the first, and they cannot affect one another directly, any more than the local variables in main() can affect the local variables in any function it calls.
Empty for
#include <iostream.h> void main() { for (int i = 0; i<5; cout << i: << i++ << endl); }
#include <iostream.h> void main() { int counter=0; // initialization int max; cout << How many hellos?; cin >> max; for (;;) // a for loop that doesnt end { if (counter < max) // test { cout << Hello!\n; counter++; // increment } else break; } }
Recursion
Besides calling other functions, a function can call itself. This is called recursion, and recursion can be direct or indirect. It is direct when a function calls itself; it is indirect recursion when a function calls another function that then calls the first function.
It is important to note that when a function calls itself, a new copy of that function is run. The local variables in the second version are independent of the local variables in the first, and they cannot affect one another directly, any more than the local variables in main() can affect the local variables in any function it calls.
Would assign the address of variable num to the pointer variable p. The & operator is called as address of .
The Indirection Operator The indirection operator (*) is used in two distinct ways with pointers: declaration and dereference. When a pointer is declared, the star (*) indicates that it is a pointer, not a normal variable, as in the following example:
unsigned short * pAge = 0; // make a pointer to an unsigned short
When the pointer is dereferenced, the indirection operator indicates that the value at the memory location stored in the pointer is to be accessed, rather than the address itself. *pAge = 5; // assign 5 to the value at pAge Also note that this same character (*) is used as the multiplication operator. The compiler knows which operator to call based on context.
typedef unsigned short int USHORT; void main() { USHORT myAge; // a variable USHORT * pAge = 0; // a pointer myAge = 5; cout << myAge: << myAge << \n; pAge = &myAge; // assign address of myAge to pAge cout << *pAge: << *pAge << \n\n; cout << *pAge = 7\n; *pAge = 7; // sets myAge to 7 cout << *pAge: << *pAge << \n; cout << myAge: << myAge << \n\n; cout << myAge = 9\n; myAge = 9; cout << myAge: << myAge << \n; cout << *pAge: << *pAge << \n; getch(); }
In the expression !i>14 , NOT (!) operator has more precedence than > symbol. ! is a unary logical operator. !i (!10) is 0 (not of true is false). 0>14 is false (zero).
void inword(int n); void main() { int a; clrscr(); cout<<" enter the number"; cin>>a ; inword(a); getch(); } void inword(int n) { char wtab[]={"Zero","One","two","three","four","five","six","seven","eight","nine"}; if(n>9) { inword(n/10); } cout<<wtab[n%10]<<" " ; }
Explanation: The preprocessor directives can be redefined anywhere in the program. So the most recently assigned value will be taken.
Explanation: Preprocessor executes as a seperate pass before the execution of the compiler. So textual replacement of clrscr() to 100 occurs.The input program to compiler looks like this : main() { 100; cout<<100); } Note: 100; is an executable statement but with no action. So it doesn't give any problem
Explanation:
printf takes the values of the first two assignments of the program. Any number of printf's may be given. All of them take only the first two values.
const Argument
In C++, an argument to function can be declared as const .This type of declaration is significant only when we pass arguments by reference or pointers. 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. For example : int swap(const int *p, int * q, int * r);
External variable #include <iostream.h> #include <conio.h> #include <file2.cpp> int count=1; void main() { int j; clrscr(); fun(); for(j=0;j<=count;j++) { cout<<j<<"\n"; } getch(); }
#include <iostream.h> #include <conio.h> #include <stdlib.h> extern int count; void fun() { count=5; }
Register variable
Using register keyword we can declared the register variable. The register modifier tells the compiler to store a variable in such manner as to access to it as fast as is possible. For example ,
register int counter; The register keyword can be used only with local variables and function parameters.
Static
1. The static modifier causes a local variable to stay in existence throughout the life of a program. 2. 2. All numeric variables of the static storage class are initialized to zero if they are not explicitly initialized by the programmer. 3. Unlike automatic variables , static local variables retain their values when the function is exited.
ObjectObject-Oriented Programming
Abstraction in C++
Abstraction is the process of separating the logical properties from the implementation details. E.g. driving a car is a logical property; the construction of the engine constitutes the
implementation details. We have an abstract view of what the engine does, but are not interested in the engines actual
51
details implementation.
Class
A class is a way to bind the data and its associated functions together. It allows the data and function to be hidden , if necessary, from external use. Generally , a class specification has two parts: 1. Class declaration: the class declaration describes the type and scope of its members 2. class function definition: The class function
Class name
attributes
methods
55
Encapsulation
Encapsulation is the idea that the internal workings of an object can be hidden from the outside world. Under the object-oriented paradigm, encapsulation is performed in two ways: We encapsulate the details of how attributes are stored. We encapsulate the details of how methods are performed.
56
Encapsulation
Why would we want to encapsulate objects?
In terms of object-oriented programming, we reduce the need for outside users to worry about how something is done. This provides significant benefits in the area of program maintenance we can change those details without the users ever being aware (provided that the outside interface remains the same).
57
Encapsulation in C++
The concept of encapsulation is embodied in C++ classs by allowing us to restrict access to an objects members. This is accomplished by a set of keywords used to describe access privileges: 1. private 2. public 3. protected 4. friend
58
Encapsulation in C++
private :
If a classs members are declared as private, then they are not accessible to anything except for the object itself. Thus, the only place where the scope of a private member would be valid is within the objects behaviors/methods. By default, all members of a C++ class are declared as private.
59
Encapsulation in C++
public:
Members that are declared as public are fully accessible to the outside world. Any public member can be accessed by any other C++ object .(assuming that the scope is valid).
60
Encapsulation in C++
If we leave the class declaration as it is, all of the members will be private (default). We could accomplish the same result by explicitly including the private keyword.
Same
61
Encapsulation in C++
If we want all of the members to be public, then we must use the public keyword.
class Car { public: string model; string color; int speed; };
All public
62
Encapsulation in C++
We can mix-and-match keywords in order to obtain different combinations. class Car { string model; public: string color; public int speed; }; class Car { public: string model; string color; private: int speed; };
63
Object In c++ , the class variables are known as object. It is also called the instance of class. Creating Object: class name objectname;
For example, class abc { int number; float cost; public: void getdata(int a, float b); void disp(); } ab,bc; would create the objects ab and bc.
abc x,y; Would create the objects x and y of type abc ( class).
Defining member functions Member functions can be defined in two places: outside the class definition inside the class definition
{ function body; }
When a function is defined inside a class , it is treated as an inline function. restrictions Therefore and , all the that
limitations
class item { int qty; float price; public: void getdata(int a, float b); void disp() { cout<<qty=<<qty<<endl; cout<<price=<<price<<endl; } }; void item:: getdata(int a, float b) { qty=a; price=b; }
{
int x,y;
{
cout<< enter the x and y; cin>>x>>y;
public:
void input(); void disp(); int larg(); }; int abc:: larg() { if(x>y) return (x); else return (y);
}
void abc::disp() { cout<<larg();
}
int main()
{ abc A;
A.input(); A.disp(); return 0; }
Arrays of objects
class emp { char name[40]; int age; public: void getdata(); void putdata(); }; Void emp::getdata() { cout<<enter name; cin>>name; cout<<enter age; cin>>age; } Void emp::putdata() { cout<<name=<<name<<endl; cout<<age=<<age<<endl; } void main() { emp person[3]; for(int i=0;i<3;i++) { cout<<detail of emp <<i+1<<endl; person[i].getdata(); } cout<<endl; for(i=0;i<3;i++) { person[i].putdata(); cout<<endl; } return o; }
Friend Function
The Private members cannot be accessed from outside the class , means one class cannot be
accessed the private members of other class. C++ allows the common function to be made friendly to have access to the private data of these classes. Such a function need not be a member of any of these classes . It is declared using the keyword friend.
class abc { int a; int b; public: void setv() { a=10; b=20; } friend float mean( abc p); }; float mean( abc p) { return float(p.a+p.b)/2; }
abc ab;
ab.set(34); xyz xy; xy.st(45);
max(xy,ab);
return 0;
special characteristics. These are: 1. It is initialized to zero when the first object of its class is created . No other initialization is permitted. 2. Only one copy of that member is created for the entire class and is shared by all the objects of that class. 3. It is visible only within the class , but its lifetime is the entire program.
class item { static int count; int number; public: void geta(int a) { number=a; count++; } void showcount() { cout<<count=<<count<<endl; } }; int item::count; // definition of static //data member.
int main()
{
item a,b,c;
a.showcount(); b.showcount(); c.showcount(); a.geta(45); b.geta(23); c.geta(67);
A member function
that is declared static has the following properties : can have access to only
other static members( functions or variables) declared in the same class. 2. A static member function can be called using the class name( instead of its objects) as follow:class-name::s_function-name();
class test { int code; static int count; public: void setcode() { code=count++; } void showcode() { cout<<" object number="<<code<<"\n"; } static void showcount() { cout<<"count="<<count<<"\n "; } }; int test::count;
void main() { test t1,t2; t1.setcode(); t2.setcode(); test::showcount(); test t3; t3.setcode(); test::showcount(); t1.showcode(); t2.showcode(); t3.showcode(); getch(); }
class test { float x; float y; public: void input(float a, float b) { x=a; y=b; } void show(test); friend test sum(test , test); }; test sum(test c1, test c2) { test t3; t3.x=c1.x+c2.x; t3.y=c1.y+c2.y; return (t3); } void test::show(test c) { cout<<c.x <<" , "<<c.y<<"\n"; }
Returning Objects
void main() { test a,b,c; a.input(2.13,3.24); b.input(4.23,2.76); c=sum(a,b); cout<<"a="; a.show(a); cout<<"b="; b.show(b); cout<<"c="; c.show(c); getch(); }
int main() { item *p = new item[2]; item *d=p; int x,i; float y; for(i=0;i<2;i++) { cout<<" enter the code and price"; cin>>x>>y; p->getdata(x,y); p++; } for(i=0;i<2;i++) { cout<<"item:"<<i+1<<"\n"; d->show(); d++; } getch(); return 0; }
WAP to define a class to represent a bank account . include the following data members: name of depositor, account number, type of account, balance amount and member
functions : to assign initial values, to deposit an amount , to withdraw an amount after checking the balance , to display name and balance.
CONSTRUCTORS
A constructor is a special member function whose task is to initialize the objects of its class. Its name is the same as the class name. The constructor is invoked associated class is created.
A constructor is declared and defined as follows: class import { int m,n; public: import(); // constructor declared. }; Import::import() // constructor defined. { . } };
FEATURES OF CONSTRUCTORS 1. Constructor should be declared in public section. 2. They are invoked automatically when the objects are created. 3. They do not have return type. 4. They con not be inherited. 5. Constructor cannot be virtual. 6. We cannot refer to their addresses.
Note: when a constructor is declared for a class , initialization of the class objects becomes mandatory.
TYPE OF CONSTRUCTORS
1. Default constructor
Parameterized constructor
The constructors that can take arguments are called parameterized constructor. class import { int m,n; public: import ( int x, int y) { m=x; n=y; } }; imort obj1(100, 200); // calling of constructor. Constructor can be call in two way:import obj1= import(10,20); // explicit call or import obj1(23,45); // implicit call