Sie sind auf Seite 1von 92

The history of C++

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

()

: insertion symbol , : Extraction Operator : double quote : parenthesis

#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

These are four valid numbers with decimals expressed in C++.

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 (").

Defined constants (#define)


You can define your own names for constants that you use very often without having to resort to memory consuming variables, simply by using the directive. Its format is: #define identifier value For example: #define PI 3.14159 #define NEWLINE '\n This defines two new constants: PI and NEWLINE. #define preprocessor

Declared constants (const)


With the const prefix you can declare constants with a specific type in the same way as you would do with a variable: const int pathwidth = 100; const char tabulator = '\t'; Here, pathwidth and tabulator are two typed constants. They are treated just like regular variables except that their values cannot be modified after their definition.

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);

Explicit type casting operator


Type casting operators allow you to convert a datum of a given type to another. There are several ways to do this in C++. The simplest one, is to precede the expression to be converted by the new type enclosed between parentheses (()): int i; float f = 3.14; i = (int) f; The previous code converts the float number 3.14 to an integer value (3), the remainder is lost. Here, the typecasting operator was (int). Another way to do the same thing in C++ is using the functional notation: preceding the expression to be converted by the type and enclosing the expression between arentheses: i = int ( f ); int a,b; float c; a=3; b=2; c=(float) a/3; Both ways of type casting are valid in C++.

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.

Declaring and Defining Functions


The declaration tells the compiler the name, return type, and parameters of the function. The definition tells the compiler how the function works. No function can be called from any other function that hasnt first been declared. The declaration of a function is called its prototype. The function prototype is a statement, which means that it ends with a semicolon. It consists of the functions return type, name, and parameter list. The parameter list is a list of all the parameters and their types, separated by commas. Example of the function prototype.

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.

Defining the Function


The definition of a function consists of the function header and its body. The header is exactly like the function prototype, except that the parameters must be named, and there is no terminating semicolon. The body of the function is a set of statements enclosed in braces. Figure shows the header and body of a function.

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.

pointer A pointer is a variable that holds a memory address of another variable.


Advantages of pointer : 1. Pointers are more efficient in handling arrays and data table. 2. Pointers can be used to return multiple values from a function via function arguments. 3. Pointers allow C to support dynamic memory management. 4. Pointer provide an efficient tool for manipulating dynamic data structures such as structure , linked lists, queues, stacks and tree. 5. Pointer reduce length and complexity of programs. 6. Pointer increase the execution speed and thus reduce the program execution time.

Accessing the address of a variable


The actual location of a variable in the memory is system dependent . The address of a variable can be accessed by operator & immediately

preceding a variable. For example


Int *p, num; P= &num;

Would assign the address of variable num to the pointer variable p. The & operator is called as address of .

// Demonstrates address of operator and addresses of local variables


#include <iostream.h> void main() { int var1 =5; float Var2=6553; long sVar = -65535; cout << var1:\t << var1 << Address of var1:\t << &var1 << \n; cout << var2:\t << var2 << Address of var2:\t << &var2 << \n; cout << sVar:\t << sVar << Address of sVar:\t << &sVar << \n; getch(); }

Declaring and initializing pointer


The declaration of a pointer variable takes the following form; data type * Pointer-name; 1. the asterisk (*) tells that the variable Pointer_name is a pointer variable. 2. Pointer_name needs a memory location. 3. pointer_name points to a variable of type datatype.
For Example;int *p; Declares the variable p as a pointer that points to an integer data type. float *x; Declares the variable x as a pointer that points to a floating point data type variable.

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(); }

POINTER INCREMENTS AND SCALE FACTOR


When we increment a pointer, its value is increased by the length of the data type that it points to. This length called the scale factor.

The length of various data type are as follows:


char int float long int double 1 byte 2 bytes 4 bytes 4 bytes 8 bytes

Assignment I MCA-II C++ Theory Assignment Submission date: 9-03-2010.


1. 2. 3. 4. 5. 6. 7. Explain the History of c++ Language. Explain the data types in c++. Explain the Identifier , Keyword and constants with example. Explain the c++ operators with example. What is type casting or type conversion explain with example. Explain the manipulators available in c++. Explain the decision making statements, loop statements, break, goto , and continue, switch statement. 8. What is an array? Explain the different types of array. 9. What is function ? Explain the types and categories of function. Also Write the advantages of function . 10. What is difference between call by value and call by reference ? Explain with example . 11. What is recursion? Write a program to print the Fibonacci series using recursion. 12. Explain the storage class specifiers . 13. What is pointer? Explain pointers and array, pointers and structure with example. 14. Explain the bit fields typed, typedef and enumeration. 15. Explain the inline function. 16. Explain the default value argument.

Assignment I MCA-II C++ Theory Assignment Submission date: 10-03-2010.


1. WAP to find the greatest number between three given numbers using conditional operator. 2. WAP to enter the days and convert them into months and days. 3. WAP to find the factorial of a given number. 4. WAP to convert number into word. Like 145 -- one four five

void main() { int i=10; i=!5>14; cout <<i; getch(); } Explanation:

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]<<" " ; }

#include <stdio.h> #define a 10 main() { #define a 50 out <<a; getch(); }

Explanation: The preprocessor directives can be redefined anywhere in the program. So the most recently assigned value will be taken.

#define clrscr() 100 main() { clrscr(); cout<<clrscr(); }

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

main() { int i=400,j=300; printf( %d %d ); }

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);

Storage class specifiers

1.Auto 2.Extern 3.Register 4.Static

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


Object-oriented programming (OOP) is associated with object-oriented design (OOD).

There are four principles of OOD, i.e.


1. Abstraction - take only important information 2. Encapsulation - hiding or combine data and operations on data in a single unit. 3. Inheritance - create new objects from existing objects. 4. Polymorphism - the ability to use the same expression to denote different operations.
50

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

definition describe how the class function are implemented.

The general format of a class declaration is :


class class_name { access modifier: data type data member name; data type data member name; .. .. member function() declaration; . . }; The body of class is enclosed within braces and terminated by a semicolon. The class body contains the declaration of variables and functions. These functions and variables are collectively called class members.

Declaring a class in C++


The class diagram for the Car class is as below:


Our first step is to define a new class for our car:

Car model:string Color:string Speed:int drive ( ) stop ( ) turn( )

Class name

class Car { // Declare our Car class here };

attributes

methods

Declaring a class in C++


Next, we want to add the attributes which we have defined for a car. object-oriented In programming, we refer to attributes as members of a class, or data members. For the car object class, we define that the model and color are of type string, and speed is an int. Car Model:string Color:string Speed:int drive ( ) stop ( ) turn( )

class Car { string model; string color; int speed; };

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.

class Car { string model; string color; int speed; };

Same

class Car { private: string model; string color; int speed; };

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

C++ Method Declarations


Object behaviors are implemented in C++ using functions that are referred to as methods. A method (also known as a member function) is a function that is defined within a class. Instances of an object class can execute all of the methods that their class defines. Just as with any function, the first step in writing a method is to determine its interface/header. The interface is simply the name of the method, the parameters it requires, and its 64 return value.

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).

Accessing class members


The private data of a class can be accessed only through the member function of that class. The main() cannot access private data directly. The following is the format for calling a member function: object-name.function-name( actual-arguments);

Defining member functions Member functions can be defined in two places: outside the class definition inside the class definition

Outside the class definition


The general form of a member function definition is :
Return type class-name :: function-name ( argument declaration)

{ function body; }

Inside the class definition


Class item { int qty; float price; public: void getdata( ) { cout<< qty and price; cin>>qty>>price; } void putdata() // inline function { cout<<qty<<endl; cout<<price<<endl; } };

When a function is defined inside a class , it is treated as an inline function. restrictions Therefore and , all the that

limitations

apply to an inline function are also applicable here.

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; }

main() { item x; x.getdata(10,25.55); x.disp(); item y; y.getdata(23,67.33); y.disp(); return 0; getch(); }

Making an outside function inline


class item { int qty; float price; public: void getdata(int a, float b); }; inline void item:: getdata(int a, float b) { qty=a; price=b; }

Nesting of Member Functions


A member function can be called by using its name inside another function of the same

class. This is known as nesting of member function.


class abc void abc::input()

{
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; }

Private Member Functions


A private member function can only be called by another function that is a member of its class. An object cannot invoke a private function using the dot operator.
class xyz { int a; void read(); public: void update(); void write(); }; If x is an object of xyz , then x.read(); // is illegal ,object cannot access //private members The function read() can be called by the function update() to update the value of a. void xyz :: update() { read(); }

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; }

Objects as function arguments


class time { int hours; int minutes; public: void gettime( int h, int m) { hours=h; minutes=m} void puttime() { cout<<hours<< hours and ; cout<<minutes<<minutes<<endl; } void add(time t1, time t2) { minutes=t1.minutes+t2.minutes; hours=minutes/60; minutes=minutes%60; hours=hours+t1.hours+t2.hours; } }; int main() { time T1, T2, T3; T1.gettime(4,45); T2.gettime(5,23); T3.add(T1,T2); // T3=T1+t2 cout<<T1=; T1.puttime(); cout<<T2=; T2.puttime(); cout<<T3=; T3.puttime(); return 0; }

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.

Characteristics of friend function


1. It is not the scope of the class to which it has been declared as friend. 2. It can not be called using the object of that class. 3. The function definition does not use either the keyword friend or the scope operator :: . 4. It can be declared either in the public or private part of a class without affecting its meaning. 5. It can be invoked like a normal function without the help of any object. 6. Usually , it has the objects as arguments.

Declaration of friend function


class class-name { --------------public: friend void function-name(); };

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; }

int main() { abc x; x.setv(); cout<<mean(x); return 0; }

A function Friendly to two classes.


class abc { int x; public: void set(int i) { x=i; } friend void max(xyz, abc); }; class xyz { int a; public: void st(int i) { a=i; } friend void max(xyz, abc); }; void max(xyz m, abc n) { if(m.a>n.x) cout<<m.a; else cout<<n.x; } int main()
{

abc ab;
ab.set(34); xyz xy; xy.st(45);

max(xy,ab);
return 0;

Static data members


Static member variables are normally used to maintain values common to the entire class. Static Keyword is used to create static data member. A static member variable has certain

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);

cout<< after reading data\n;


a.showcount(); b.showcount(); c.showcount(); getch(); return 0; }

Static member function:


1. A static function

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(); }

Pointer and Objects


class item { int code; float price; public: void getdata(int a, float b) { code=a; price=b; } void show() { cout<<"code="<<code<<endl; cout<<"price="<<price<<endl; } };

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. { . } };

whenever an object of its

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 2. Parameterized constructor 3. Copy constructor

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