-1-                        C++ (C with Classes)Object Oriented Programming (OOP)       The term ‘‘Object Oriented Programm...
-2-functions. OOP allows us to decompose a problem into a number ofentities called objects and built data and functions ar...
-3-Polymorphism (many forms)      An ability to have more than one function with the same name,each having different funct...
-4-The data is not accessible to the outside world and only those functionswhich are placed in the class can access it, th...
-5-      Member functions definition      Main function      {             Local declaration;             Object declarati...
-6-    •   private members of a class are accessible only within the class        and by the public members of the same cl...
-7-is that in the first case the function will automatically be considered aninline member function by the compiler, while...
-8-    void inputdata();    void outputdata();};ex:-employ emp[5];Create A Class With The Name Bank And Create An Array Wi...
-9-    cin>>cbal;}void bank::output(){    cout<<"ACCOUNT NUMBER IS                :"<<acno<<endl;    cout<<"CUSTOMER NAME ...
- 10 -         cout is an object, defined in standard output stream(ostream).The standard output stream normally flows to ...
- 11 -          A reference variable provides an alias (alternative name) for apreviously defined variable.          Synta...
- 12 -    getch();    c=3500;    cout<<"A VALUE IS :"<<a<<endl;    cout<<"B VALUE IS :"<<b<<endl;    cout<<"C VALUE IS :"<...
- 13 -# include <iostream.h># include <stdio.h># include <conio.h>int add(int a,int b,int c=0,int d=0,int e=0){    return ...
- 14 -The Heap represents the remaining unused memory. This part ofmemory isgenerally used during the execution of the pro...
- 15 -               float *q;               p = new int[10];               q = new float [20];       Where p is a pointer...
- 16 -cout<<"ENTER NUMBER OF CELLS";cin>>n;a=new int[n];for(p=a;(p-a)<n;p++){    cout<<"ENTER ANY VALUE TO ARRAY :";    ci...
- 17 -    {        cout<<"ENTER STUDENT NUMBER:";        cin>>sno;        cout<<"ENTER STUDENTS NAME:";        cin>>sna;  ...
- 18 -    clrscr();    cout<<"THE VALUE OF THE ARRAY IS :";    for(p1=p;(p1-p)<n;p1++)    {        tot=p1->get_tot();     ...
- 19 -of type & the second method sum performing its operation by takingtwo arguments of type int and so on. Ex:sum(15) //...
- 20 -The process of creating a new class by deriving the features from existingclasses. It provides the concept of reusab...
- 21 - The access-specifer specifies the method of accessing the informationprovided in the base class & it will be access...
- 22 -      In all the above three cases the private data members of the baseclass is not inheritable. If we want to acces...
- 23 -multiple inheritance. On the other hand, the properties of one class maybe inherited by more than one class. This pr...
- 24 -class and therefore they are accessible to the objects of the dedrivedclass.               In both the cases private...
- 25 -    }    class b:public a          //deriving a derived class    {        int m,n;        public:        void accept...
- 26 -# include <iostream.h># include <stdio.h># include <string.h># include <conio.h>class student{    int sno;    char s...
- 27 -    public:    void accept()    {        cout<<"ENTER COURSE NAME            :";        cin>>cou;        cout<<"ENTE...
- 28 -        cout<<"ENTER MARKS IN CHEMISTRY :";        cin>>mc;    }    void resout()    {        tm=mm+mp+mc;        am...
- 29 -    obj.input();//member function of class student    obj.accept();//member function of class fees    obj.marksin();...
- 30 -             C++ provides a third visibility modifier protected, which serve alimited purpose in inheritance. A memb...
- 31 -class C:private B{    - - - - - - //members of class A are    - - - - - - //private to class C    ------};class D:pu...
- 32 -        cout<<"ENTER EMPLOY ADDRESS :";        cin>>eadd;        cout<<"ENTER BASIC SALARY      :";        cin>>bs; ...
- 33 -        cout<<"ENTER INCOME TAX:";        cin>>it;    }};class salary:public employ,public allow,public ded{    int ...
- 34 -    }};void main(){    salary s;    s.input();    s.accept();    s.dedinput();    clrscr();    s.calc_sal();    s.ou...
- 35 -    void input()    {        cout<<"ENTER STUDENTS NUMBER          :";        cin>>sno;        cout<<"ENTER STUDENTS...
- 36 -        cout<<"ENGLISH MARKS ARE         :"<<me<<endl;    }};class mathes:public lang{    int mm,mp,mc;    public:  ...
- 37 -        cout<<"ENTER MARKS IN MATHS :";        cin>>mmt;        cout<<"ENTER MARKS IN PHYSICS          :";        ci...
- 38 -    {        cout<<"HISTORY MARKS ARE       :"<<mhs<<endl;        cout<<"ECONOMICS MARKS ARE :"<<mec<<endl;        c...
- 39 -    getch();}Example for Hybrid Example. (The Combination Of Any Two InheritanceIs Called Hybrid Inheritance.# inclu...
- 40 -    public:    void mentry()    {        cout<<"ENTER MARKS IN MATHS :";        cin>>mm;        cout<<"ENTER MARKS I...
- 41 -        avg=tot/3;        if(sm>50)        avg=avg+5;        if(avg>=75)        strcpy(res,"DISTINCTION");        el...
- 42 -    clrscr();    r.input(); //member function of student class    r.mentry(); //member function of test class    r.s...
- 43 -The function declaration should be preceded by the keyword "friend".The function definition does not use the keyword...
- 44 -    }    void output()    {        cout<<"A VALUE IS   :"<<a<<endl;    }    friend int getsum(myclass m,sample a)};c...
- 45 -    d.accept();    t=getsum(c,d); //friend function calling    clrscr();    c.output();    d.accept();    cout<<"TOT...
- 46 -    friend void calc_sal(employ e,allow a,ded d);};class allow{    int da,hra,cca;    public:    void getallow()    ...
- 47 -    ns=gs-tded;    clrscr();    cout<<"ENTER EMPLOY NUMBER :"<<e.eno<<endl;    cout<<"ENTER EMPLOY NAME             ...
- 48 -class test;class sample{    int a;    float b;    public:    void input()    {        cout<<"ENTER ANY INTEGER AND F...
- 49 -        cout<<"M VALUE IS   :"<<m<<endl;        cout<<"N VALUE IS   :"<<n<<endl;    }    friend sample setsum(sample...
- 50 -Constructors            A constructor is a special member function whose task is toinitialize the objects or variabl...
- 51 -    }};void main(){    clrscr();    sample s;    getch();}Characteristics of a constructor                1. It shou...
- 52 -# include <stdio.h># include <conio.h>class test{    int a;    float b;    long c;    public:    test() //constructo...
- 53 -    s.output();    cout<<"VALUES OF R ARE          :"<<endl;    r.output();    getch();}Example for Constructor Func...
- 54 -    }    void output()    {        cout<<"students number is :"<<sno<<endl;        cout<<"students name is   :"<<sna...
- 55 -# include <conio.h># include <string.h>class sales{    int sno,samt;    char sna[10];    public:    sales(int a,char...
- 56 -}Constructors in derived class:               If the base class contain a constructor with one or morearguments, the...
- 57 -and the function ends) or because it is an object dynamically assignedand it is released using the operator delete.T...
- 58 -                         function_body;                }where return_type is the type of value returned by the speci...
- 59 -        b=25.65;        c=42500;    }    exam operator ++() //operator overloading function    {        a+=100;     ...
- 60 -    cout<<"x value is :"<<x<<endl;    getch();}Output:            Values before function calling                   A...
- 61 -    {        cout<<"FIRST INTEGER IS     :"<<a<<endl;        cout<<"SECOND INTEGER IS           :"<<b<<endl;        ...
- 62 -    q.print();    cout<<"addition object values are      :"<<endl;    r.print();    getch();}Example Program For Ove...
- 63 -    }    int operator *(int n)    {        return(nou * n);    }};void main(){    sales s;    int rpu,samt;    clrsc...
- 64 -      Polymorphism means one name multiple forms.               Polymorphismcan be classified into      1. Compile t...
- 65 -Ex: ptr->getdata();//by using ->operator   (*ptr).getdat();We can also created the objects with the help of new oper...
- 66 -i.e., there is only one virtual table for a class irrespective of the numberof virtual functions it contains. This v...
- 67 -of bytes. On input, a program extracts (>>) bytes from an input stream.On output, a program inserts (<<) bytes into ...
- 68 -        A program typically involves either or both of the following kinds ofdata communication   (1) Data transfer ...
- 69 -                    Inherits all the functions from istream and ostream                    classes through iostream ...
- 70 -Opening Files using open ():          The function open() can be used to open multiple files that use thesame stream...
- 71 -               {                       exit(1);                   }         eof() is a member function of ios class....
- 72 -All these flags can be combined using the bitwise operator OR (|). Forexample, if we want to open the file example.b...
- 73 -parameters as this member. Therefor, we could also have declared theprevious myfile object and conducted the same op...
- 74 -template <class T> class classname    {        class member specification with anonymous type T        wherever appr...
- 75 -    cout<<"ENTER TWO FLOATS :"<<endl;    cin>>f>>p;    cout<<"ENTER TWO LONGS              :"<<endl;    cin>>l>>r;  ...
- 76 -    cout<<"ENTER AN INTEGER :"<<endl;    cin>>m;    cout<<"ENTER A FLOAT VALUE :"<<endl;    cin>>f;    cout<<"ENTER ...
- 77 -        cout<<"ENTER THIRD VALUE :";        cin>>f;    }    A total()    {        return(n+m+f);    }    void output...
- 78 -    cout<<endl<<"FLOAT VALUES ARE :"<<endl;    T2.output();    cout<<"TOTAL VALUE IS :"<<T2.total()<<endl;    cout<<...
Upcoming SlideShare
Loading in …5
×

My c++

5,012 views

Published on

Published in: Education, Technology
1 Comment
6 Likes
Statistics
Notes
No Downloads
Views
Total views
5,012
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
417
Comments
1
Likes
6
Embeds 0
No embeds

No notes for slide

My c++

  1. 1. -1- C++ (C with Classes)Object Oriented Programming (OOP) The term ‘‘Object Oriented Programming” means a programminglanguage that fully supports the object oriented (features) style ofprogramming.Introduction C++ is an object-oriented programming language developed byBjarne Stroustrup at AT & T Bell Labs in the early 1980’s.Since the class concept was the major addition to the original Clanguage, it is called as "C with classes". However later in 1983, thename was changed to C++. The idea of C++ comes from the C incrementoperator "++", there by suggesting that C++ is an incremented version ofC.C++ is a superset of C. Therefore almost all C programs are valid C++programs.Difference between C & C++ ‘C’ is a procedure-oriented programming language whereeverything is placed in the form of procedures or functions. While weconcentrate on functions very little attention is given to the data that arebeing used by various functions & any function can access theinformation provided in other functions. It doesn’t model the real worldproblems very well. It employs top-down approach in program design.Where as ‘C++’ is an object-oriented programming language which treatsdata as a critical element in the program and it doesn’t allow movingfreely around the system. It binds the data & the functions that operateon data together and protects it from accidental use of other
  2. 2. -2-functions. OOP allows us to decompose a problem into a number ofentities called objects and built data and functions around these objects.Advantages of OOP 1. Object Oriented Approach 2. Closer to real world object 3. Dynamic Declaration 4. Data Security 5. Code Re-Usability & ExtensibilityBasic concepts of ‘Object-Oriented’ programming languageClassA class is a blueprint or prototype that defines the variables and themethods common to all objects of a certain kind.A class is a logical construct of an object.A class is an abstract representation of something, whereas an object isa usable example of the class.A class is an expanded concept of a structure in C, instead of holdingonly data; it can hold both data and functions. Once a class has beendefined, you can create any number of objects based on that class.Object An object is an instance (example or illustration) of a class. Interms of variables, a class would be the data type and an object wouldbe the variable.An object is a physical reality.An object is a software bundle of related variables and methods.Software objects are often used to model real-world objects you find ineveryday life.
  3. 3. -3-Polymorphism (many forms) An ability to have more than one function with the same name,each having different functionality. The function going to execute isdetermined at run time. Polymorphism refers to the fact that a singleoperation can have different behavior in different objects.E.g.: Overloading, Overriding. Overloading: Overloading is the practice of supplying more than onedefinition for a given function name in the same scope. The compiler isleft to pick the appropriate version of the function or operator based onthe arguments with which it is called.Inheritance The mechanism of creating new classes by deriving the featuresfrom existing classes is called Inheritance.In OOP the concept of inheritance provides the idea of reusability &extensibility. This means that we can add additional features of anexisting class without modifying it. This is possible by deriving a newclass from the existing one. The new class will have the combinedfeatures of both the classes.Encapsulation The method of packing all the data members & member functionsinto a single unit called class and the process is called ‘Encapsulation’Data Hiding The process of hiding the data members and member functionsfrom access by the other class objects other than the same class objects.
  4. 4. -4-The data is not accessible to the outside world and only those functionswhich are placed in the class can access it, these functions provide theinterface between objects data and the program. The insulation of datafrom direct access by the program is called data hiding.Data Abstraction It is the process of accessing the data members & memberfunctions with the objects.Abstraction refers to the act of representing essential features withoutincluding the background details and explanations. Classes use theconcept of abstraction and defined as a list of abstraction attributes.Since the classes use the concept of data abstraction they are known asAbstract Data Type (ADT).Data Binding Binding refers to the act of associating an object or a class with itsmember. If we can call a method fn() on an object o of a class c, we saythat the object o is binded with the method fn(). This happens at compiletime and is known as static or compile - time binding.The calls to the virtual member functions are resolved during run-time.This mechanism is known as dynamic binding. The most prominentreason why a virtual function will be used is to have a differentfunctionality in the derived class. The difference between a non-virtualmember function and a virtual member function is the non-virtualmember functions are resolved at compile time.Structure of C++ program: Include files Class declaration
  5. 5. -5- Member functions definition Main function { Local declaration; Object declaration; Executable coding; }Syntax for Class Declaration class class_name { access_specifier_1: data members; access_specifier_2: member functions; ………. } object_names;where class_name is a valid identifier for the class, object_names is anoptional list of names for objects of this class. The body of thedeclaration can contain members, which can be either data or functiondeclarations, or optionally access specifiers.All is very similar to the declaration on structures, except the new thingcalled access specifier.An access specifier is one of the following three keywords:private, public or protected. These specifiers modify the access rightsthat the members following them acquire:
  6. 6. -6- • private members of a class are accessible only within the class and by the public members of the same class or from their friends. • protected members are accessible from members of their same class and from their friends, but also from members of their derived classes. • public members are accessible from anywhere in the program where the object is visible.By default, all members of a class declared with the class keyword haveprivate access for all its members.Function Definitions outside the class Member functions that are declared inside a class have to bedefined separately outside the class. They should have a functiondefinition outside the class asreturn_type class_name :: function_name(arguments list){ function body;} The membership label class_name :: tells the compiler that thefunction belongs to the class class_name. That is the scope of thefunction is restricted to the class_name specified in the header line.The symbol "::" is called Scope Resolution operator.The scope operator (::) specifies the class to which the member beingdeclared belongs, granting exactly the same scope properties as if thisfunction definition was directly included within the class definition.The only difference between defining a class member function completelywithin its class and to include only the prototype and later its definition,
  7. 7. -7-is that in the first case the function will automatically be considered aninline member function by the compiler, while in the second it will be anormal (not-inline) class member function, which in fact supposes nodifference in behavior.Inline Function They are shortcut functions that are not actually called; rathertheir code is expanded at the point of execution. If a function is declaredwith the keyword inline, the compiler does not call the actual functioninstead it copies the code from the inline function directly into the callingfunction.Inline is a hint to the compiler that you would like the function to beinlined. The compiler is free to ignore the hint and make a real functioncall.this pointer: "this" is a pointer that points the address of the current object.The unique pointer is automatically passed to a member function when itis called. The pointer "this" acts as an implicit argument to all themember functions.Object Arrays We know that an array can be of any data type including struct,similarly we can also have arrays of variables that are of the type class.Such variables are called arrays of objects.class employ{ char name[10]; int age; public:
  8. 8. -8- void inputdata(); void outputdata();};ex:-employ emp[5];Create A Class With The Name Bank And Create An Array With 5 CellsAnd Accept Data And Print Data.Example for an Object Arrays.# include <stdio.h># include <iostream.h># include <conio.h>class bank{ int acno,cbal; char cname[20]; public: void input(); void output();};void bank::input(){ cout<<"ENTER A/C NUMBER :"; cin>>acno; cout<<"ENTER CUSTOMER NAME :"; cin>>cname; cout<<"ENTER CURRENT BALANCE :";
  9. 9. -9- cin>>cbal;}void bank::output(){ cout<<"ACCOUNT NUMBER IS :"<<acno<<endl; cout<<"CUSTOMER NAME IS :"<<cname<<endl; cout<<"CURRENT BALANCE IS :"<<cbal<<endl;}void main(){ int i; bank b[5]; for(i=0;i<5;i++) { cout<<"ENTER VALUES FOR CELL :"<<i<<endl; b[i].input(); } clrscr(); for(i=0;i<5;i++) { cout<<"THE VALUES OF THE CELL :"<<i<<endl; b[i].output(); getch(); }}Stream A stream is defined as a collection of pre-defined objects. Theiostream (Input/Output stream) defines the following two objects.cout
  10. 10. - 10 - cout is an object, defined in standard output stream(ostream).The standard output stream normally flows to the screen. cout is anobject of the class ostream_withassign, which is derived from ostreamclass.<< The operator << is called insertion or put to operator. It directsthe contents of the variable on its right to the object on its left.Screen <----- cout <----- << <--- variablee.g; screen<---cout<<"welcome";cin cin is an object, defined in standard input stream (istream). Thisstream represents data coming from the keyboard. cin is an object ofistream_withassign class, which is derived from istream class.>> This operator is called extraction or get from operator. It takesthe value from the stream on its left and places it in the variable on itsright.Keyboard ---> cin ---> >> ---> variableeg: keyboard-->cin>>x;Basic Data Types Built-in-Data types: int, char, float, double, void User-defined types: structure, union, class, enumeration Derived types: array, function, pointer, referenceReference Variable
  11. 11. - 11 - A reference variable provides an alias (alternative name) for apreviously defined variable. Syntax: data_type &ref_var_name = variable; E.g.: int x = 200; int &xref = x;A reference variable must be initialized at the time of declaration. Thisestablishes the correspondence between the reference and the dataobject that it names. Here the "&" is not an address operator. Thenotation datatype followed by "&" means that it is the reference to thatdatatype.Example for Reference Variable#include <stdio.h>#include <conio.h># include <iostream.h>void main(){ int a=200; int &b=a; int &c=b; clrscr(); cout<<"A VALUE IS :"<<a<<endl; cout<<"B VALUE IS :"<<b<<endl; cout<<"C VALUE IS :"<<c<<endl; getch(); b=55; cout<<"A VALUE IS :"<<a<<endl; cout<<"B VALUE IS :"<<b<<endl; cout<<"C VALUE IS :"<<c<<endl;
  12. 12. - 12 - getch(); c=3500; cout<<"A VALUE IS :"<<a<<endl; cout<<"B VALUE IS :"<<b<<endl; cout<<"C VALUE IS :"<<c<<endl; getch();}Default Arguments C++ allows calling a function without specifying all its arguments.In such cases the function assigns a default value to the parameterwhich does not have a matching argument in the function call. We haveto specify the default values when the function is declared. The compilerlooks at the prototype (declaration) to see how many arguments thefunction uses and alerts the program for possible default values. Oneimportant point is that only the trailing arguments can have defaultvalues i.e. you must add default from right to left. It is not possible toprovide a default value to a particular argument in the middle of theargument list.Ex: int add (int x, int y=0, int z=0); int mul (int a=1,int b=20,int c=40) Ex: add (10,20,30); add (10,20); add (10); add (); does not allow because there is no default valuefor argument x.Another Example for Default arguments
  13. 13. - 13 -# include <iostream.h># include <stdio.h># include <conio.h>int add(int a,int b,int c=0,int d=0,int e=0){ return (a+b+c+d+e);}void main(){ int m,n,p,q,r; clrscr(); cout<<"ENTER ANY FIVE INTEGERS :"<<endl; cin>>m>>n>>p>>q>>r; cout<<"ADDITION OF 2 NUMBERS ARE :"<<add(m,n)<<endl; cout<<"ADDITION OF 3 NUMBERS ARE :"<<add(m,n,p)<<endl; cout<<"ADDITION OF 4 NUMBERS ARE :"<<add(m,n,p,q)<<endl; cout<<"ADDITION OF 5 NUMBERS ARE :"<<add(m,n,p,q,r)<<endl; getch();}Memory Management Operators (Dynamic Memory Allocation) The part of the computer memory available to programmers, isdivided into two areas: The Stack and The Heap (or Free Store). The Stack is used for those items that have a definite size andlifetime, forexample, variables, arrays, etc. All the elements of a program where theyareexplicitly defined before compilation are stored ‘statically’.
  14. 14. - 14 -The Heap represents the remaining unused memory. This part ofmemory isgenerally used during the execution of the program. Any object that iscreated atrun time is a dynamic object. Such an object has an unknown size andlifetime.Creating dynamic objects is very useful in creating highly interactiveprograms.Memory Management operators: C uses malloc() and calloc() functions to allocate memorydynamically at runtime. Similarly it uses the function free() to freedynamically allocated memory. Although C++ supports these functions,it also defines two unary operators new and delete that perform thetask of allocating and freeing the memory in a better and easier way.Since these operators manipulate memory on the free store, these arealso known as free store operators. To allocate the memory space dynamically during run time we canuse ‘new’ operator & in order to free the memory space which is allocatedwith ‘new’ we can use the operator ‘delete’. The new operator can be used to create objects of any type. Syntax: pointer_variable_name = new datatype Here pointer_variable is a pointer of type datatype. The newoperator allocates sufficient memory to hold a data objects of TYPEdatatype and return the address of the object. The datatype may be anyvalid datatype. The pointer variable holds the address of the memoryspace allocated.E.g. int *p;
  15. 15. - 15 - float *q; p = new int[10]; q = new float [20]; Where p is a pointer of type int and q is a pointer of type float. When a data object is no longer needed, it is destroyed to releasethe memory space for reuse, in that case we can use delete operator.Syntax: delete pointer_variable; The pointer_variable is the pointer that points to a data objectcreated with new operator.E.g. delete p; delete []p//for freeing an array of size delete q; sales s; sales *q; q =&s; qinput() or sales.input(); qprint() or sales.print();Example Program for Dynamic Memory Allocation.# include <iostream.h># include <stdio.h># include <conio.h>void main(){int n,*a,*p;clrscr();
  16. 16. - 16 -cout<<"ENTER NUMBER OF CELLS";cin>>n;a=new int[n];for(p=a;(p-a)<n;p++){ cout<<"ENTER ANY VALUE TO ARRAY :"; cin>>*p;}clrscr();for(p=a;(p-a)<n;p++){ printf("THE CELL NUMBER IS %dt:",(p-a)); printf("THE CELL ADDRESS IS n:",p); cout<<"VALUE OF ARRAY :"<<*p<<endl;}delete a;getch();}Example Program for Object Arrays with Dynamic Memory Allocation.# include <iostream.h># include <stdio.h># include <conio.h>class st{ int sno, m1, m2, m3; char sna[20]; public: void accept()
  17. 17. - 17 - { cout<<"ENTER STUDENT NUMBER:"; cin>>sno; cout<<"ENTER STUDENTS NAME:"; cin>>sna; cout<<"ENTER THE MARKS OF THREE SUBJECTS:"; cin>>m1>>m2>>m3; } int get_tot() { return(m1+m2+m3); } void print() { cout<<"STUDENT NUMBER IS:"<<sno<<endl; cout<<"STUDENTS NAME IS:"<<sna<<endl; cout<<"MARKS IN THREE SUBJECTSARE:"<<m1<<"t"<<m2<<"t"<<m3<<endl; }};void main(){ st *p,*p1; int tot,av,n; clrscr(); cout<<"ENTER NUMBER OF CELLS:"; cin>>n; p=new st[n]; for(p1=p;(p1-p)<n;p1++) p1->accept();
  18. 18. - 18 - clrscr(); cout<<"THE VALUE OF THE ARRAY IS :"; for(p1=p;(p1-p)<n;p1++) { tot=p1->get_tot(); av=tot/3; printf("THE ADDRESS OF CELL IS n",p1); cout<<"THE VALUE OF CELL IS :"<<(p1-p)<<endl; p1->print(); cout<<"TOTAL MARKS ARE :"<<tot<<endl; cout<<"AVERAGE MARKS ARE :"<<av<<endl; getch(); }delete p;}Function Overloading Function overloading means we have to perform the differentoperations by using the same method. The compiler will come to know the execution of a particular functiondepending on the maching of number of arguments & their return typeduring the function call Ex: int sum(int) int sum(int,int) void sum(float, int) void sum(float, int,int) In the above example we are using the same method sum but thefirst method sum performing its operation by taking only one argument
  19. 19. - 19 -of type & the second method sum performing its operation by takingtwo arguments of type int and so on. Ex:sum(15) //will make a call to first function sum sum(25,60)//will make a call to second function sumSTATIC MEMBERS If we want to declare the data members that is common to all theobjects created in that class we have to declare those data members asthe static data members & the syntax for declaring static data member isstatic data-type variable-name; Ex: static int a;The above data member a will be shared by all the objects created inthat class i.e only one copy of that data member is created for all theobject without creating a separate copy. Whenever we create a datamember as a static it will be initialized to 0 automatically, and we candefine the value for the static data members outside the class i.e with thehelp of the scope resolution operator & its syntax is data-type class-name :: data-member-name=value Ex: int example :: a; It means the value of a is initialized to 0 int example :: a=10; It means the value of a is initialized to 10Static member function: We can also declare a member function as a static. The syntax fordeclaring a member function as static isSyntax: static return-type function-name(arguments);Inheritance:
  20. 20. - 20 -The process of creating a new class by deriving the features from existingclasses. It provides the concept of reusability & extensibility. The term reusability means the ability to use the data provided in oneclass by another class & Extensibility provides the ability to add somemore data members & member functions to the already existing class The main class is called as base class & the class which is acquiringthe features of the base class is called as derived class & the syntax fordefining the derived class isclass derived_class_name : access_specifier base_class_name{ //data members & member function of derived class}
  21. 21. - 21 - The access-specifer specifies the method of accessing the informationprovided in the base class & it will be accessed in any one of the threeways. 1. private 2. protected 3. publicInheriting in private mode: If the derived class acquires the features ofbase class in private mode base derived private will become private protected private public privateInheriting in protected mode: If we acquire the features of base classin protected mode its characteristics will be base derived private will become private protected " protected public " protectedInheriting in public mode: In public access specifier the following thecharacteristics of the base class in derived class base derived private will become private protected " private public " public
  22. 22. - 22 - In all the above three cases the private data members of the baseclass is not inheritable. If we want to access those private data memberswe have to declare a function in public mode in the base class & withthat member function we can access them in the derived classIf we want to define those data members in the derived class itself wehave declare those data members in protected mode, but these will beavailable up to one level only i.e its accessible to the immediate classwhich is accessing its features Both private & protected data members are not accessible in themain() function. public data-members & member functions will beaccessible anywhere in our program i.e they are accessible in the main()function alsoReusability is another important feature of OOP. It is always nice if wecould reuse something that already exists rather than trying to create thesame all over again. C++ strongly supports the concept of reusability.The C++ classes can be reused in several ways. Once a class has beenwritten and tested, it can be adopted by other programmers to send theirrequirements. Creating new classes, reusing the properties of the existingones basically does this. The mechanism of deriving a new class from anold one is called "Inheritance" (or derivation). The old class referred to asthe base class and the new one is called derived class. The derived class inherits some or all the properties of the baseclass. A class can also inherit properties from more than one class offrom more than one level. A derived class with only one base class is called singleinheritance, and one derived class with several base classes is called
  23. 23. - 23 -multiple inheritance. On the other hand, the properties of one class maybe inherited by more than one class. This process is known ashierarchical inheritance. The mechanism of deriving a class from anotherderived class is known as multilevel inheritance. The combination of anyof two inheritances is called hybrid inheritance.Defining a Derived Class A derived class is defined by specifying its relationship with thebase class in addition to its own details.Syntax: class derived class_name : visibility_mode base class name { - ------- - ------- //members of derived class - ------- }; The colon (:) indicates that the derived class name is derived fromthe base class name. The visibility mode is optional and if present, it maybe either private or public. The default visibility mode is private. Thismode specifies whether the features of the base class are privatelyderived or publicly derived. When a base class is privately inherited by a derived class, ‘publicmembers’ of the base class become ‘private members’ of the derived classand therefore the public members of the base class can only be accessedby the member functions of the derived class. They are inaccessible tothe objects of the derived class. A public member of a class can beaccessed by its own objects using the dot operator. The result is that nomember of the base class is accessible to the objects of the derived class. When a base class is publicly inherited by a derived class, publicmembers of the base class becomes the pubic members to the derived
  24. 24. - 24 -class and therefore they are accessible to the objects of the dedrivedclass. In both the cases private members are not inherited and thereforethe private members of a base class will never become the members ofits derived class.E.g.:class B:public A{ - - - - - - //members of class B ------ ------ ------};Example Program for Single Inheritance.# include <iostream.h># include <conio.h>class a{ int x,y; void input(int p,int r) { x=p; y=r; } void print() { cout<<"X VALUE IS :"<<x<<endl; cout<<"Y VALUE IS :"<<y<<endl;
  25. 25. - 25 - } class b:public a //deriving a derived class { int m,n; public: void accept() { cout<<"ENTER TWO INTEGERS :"; cin>>m,n; } void display() { cout<<"M VALUE IS :"<<m<<endl; cout<<"N VALUE IS :"<<n<<endl; } };void main(){ b t; //object declared for class b clrscr(); t.input(253,445);//member function of base class t.accept(); //function of the derived class clrscr(); t.print(); //function of the base class t.display(); //function of the derived class getch();}Example Program for Multilevel Inheritance or a Derived Class fromanother Derived Class.
  26. 26. - 26 -# include <iostream.h># include <stdio.h># include <string.h># include <conio.h>class student{ int sno; char sna[10],sadd[10]; public: void input() { cout<<"ENTER STUDENT NUMBER :"; cin>>sno; cout<<"ENTER STUDENTS NAME :"; cin>>sna; cout<<"ENTER STUDENTS ADDRESS :"; cin>>sadd; } void output() { cout<<"STUDENT NUMBER IS "<<sno<<endl; cout<<"STUENTS NAME IS "<<sna<<endl; cout<<"STUDENTS ADDRESS IS "<<sadd<<endl; }};class fees:public student{ int tf,fp,due; char cou[10];
  27. 27. - 27 - public: void accept() { cout<<"ENTER COURSE NAME :"; cin>>cou; cout<<"ENTER TOTAL FEE :"; cin>>tf; cout<<"HOW MUCH FEE IS PAID :"; cin>>fp; due=tf-fp; } void display() { cout<<"COURSE NAME IS :"<<cou<<endl; cout<<"TOTAL FEE IS :"<<tf<<endl; cout<<"FEE PAID IS :"<<fp<<endl; cout<<"DUE FEE IS :"<<tf-fp<<endl; }};class marks:public fees{ int tm,mm,mp,mc,am; char res[15]; public: void marksin() { cout<<"ENTER MARKS IN MATHS :"; cin>>mm; cout<<"ENTER MARKS IN PHYSICS :"; cin>>mp;
  28. 28. - 28 - cout<<"ENTER MARKS IN CHEMISTRY :"; cin>>mc; } void resout() { tm=mm+mp+mc; am=tm/3; if(am>75) strcpy(res,"DISTINCTION"); else if(am>=60) strcpy(res,"FIRST CLASS"); else if(am>=50) strcpy(res,"SECOND CLASS"); else if(am>=35) strcpy(res,"THIRD CLASS"); else strcpy(res,"FAILED"); cout<<"MARKS IN MATHS ARE :"<<mm<<endl; cout<<"MARKS IN PHYSICS ARE :"<<mp<<endl; cout<<"MARKS IN CHEMISTRY ARE :"<<mc<<endl; cout<<"TOTAL MARKS ARE :"<<tm<<endl; cout<<"AVERAGE MARKS ARE :"<<am<<endl; cout<<"RESULT IS--------------:"<<res<<endl; }};void main(){ clrscr(); marks obj; //object declaration
  29. 29. - 29 - obj.input();//member function of class student obj.accept();//member function of class fees obj.marksin();//member function of class marks clrscr(); obj.output(); //member function of class student obj.display();//member function of class fees obj.resout();//member function of class marks getch();}Multiple Inheritance: A class can inherit the attributes of two or more classes. This isknown as multiple inheritance. Multiple inheritance allows combiningthe features of several existing classes as a starting point for defining anew class.Syntax:class derived_class : visibility label base class, visibility label baseclass………{ -- - - - - - - - - - ----------- ----------- -----------} Where visibility label is either public or private. Comma separatethe base classes.Protected Members:
  30. 30. - 30 - C++ provides a third visibility modifier protected, which serve alimited purpose in inheritance. A member declared as protected isaccessible by the member functions with in its class and any classderived from it as the public member of the base class. It cannot beaccessed by the functions outside these classes. When a protected member is inherited in public mode, it becomesprotected in the derived class too and therefore it is accessible by themember functions of the derived class. It is also ready for furtherinheritance. A protected member is inherited in the private mode derivation,that becomes private in the derived class. Although it is available to themember functions of the derived class. It is not available for furtherinheritance since private members cannot be inherited.E.g.:class A{ protected: int a; ------- ------- -------};class B:public A{ - - - - - - //members of class A are - - - - - - //protected to class B ------};
  31. 31. - 31 -class C:private B{ - - - - - - //members of class A are - - - - - - //private to class C ------};class D:public C{ - - - - - - //members of class A cannot be - - - - - - //accessed in class D ------};Example Program For Multiple Inheritance And Protected Members. (TwoOr More Base Classes One Derived Class Is Called Multiple Inheritance).# include <iostream.h># include <conio.h>class employ{ protected: int eno,bs; char ena[10],eadd[15]; public: void input() { cout<<"ENTER EMPLOY NUMBER :"; cin>>eno; cout<<"ENTER EMPLOY NAME :"; cin>>ena;
  32. 32. - 32 - cout<<"ENTER EMPLOY ADDRESS :"; cin>>eadd; cout<<"ENTER BASIC SALARY :"; cin>>bs; }};class allow{ protected: int da,hra,cca; public: void accept() { cout<<"ENTER DA:"; cin>>da; cout<<"ENTER HRA:"; cin>>hra; cout<<"ENTER CCA:"; cin>>cca; }};class ded{ protected: int pf,it; public: void dedinput() { cout<<"ENTER PROVIDENT FUND:"; cin>>pf;
  33. 33. - 33 - cout<<"ENTER INCOME TAX:"; cin>>it; }};class salary:public employ,public allow,public ded{ int tall,tded,gs,ns; public: void calc_sal() { tall=da+hra+cca; tded=pf+it; gs=bs+tall; ns=gs-tded; } void output() { cout<<"EMPLOY NUMBER IS:"<<eno<<endl; cout<<"EMPLOY NAME IS :"<<ena<<endl; cout<<"EMPLOY ADDRESS IS :"<<eadd<<endl; cout<<"BASIC SALARY IS :"<<bs<<endl; cout<<"EMPLOYS DA IS :"<<da<<endl; cout<<"EMPLOYS HRA IS :"<<hra<<endl; cout<<"EMPLOYS CCA IS :"<<cca<<endl; cout<<"EMPLOYS PF IS :"<<pf<<endl; cout<<"EMPLOYS IT IS :"<<it<<endl; cout<<"TOTAL ALLOWANCES :"<<tall<<endl; cout<<"TOTAL DEDUCTIONS :"<<tded<<endl; cout<<"EMPLOYS GROSS SALARY IS :"<<gs<<endl; cout<<"EMPLOYS NET SALARY IS :"<<ns<<endl;
  34. 34. - 34 - }};void main(){ salary s; s.input(); s.accept(); s.dedinput(); clrscr(); s.calc_sal(); s.output(); getch();}Hierarchical Inheritance: In the hierarchical inheritance different classes are derived fromone base class. A subclass can be constructed by inheriting theproperties of the base class. A subclass can serve as a base class for thelower classes and so on.Example Program for Hierarchical Inheritance.# include <iostream.h># include <conio.h># include<string.h>class student{ int sno; char sna[10],sadd[10]; public:
  35. 35. - 35 - void input() { cout<<"ENTER STUDENTS NUMBER :"; cin>>sno; cout<<"ENTER STUDENTS NAME :"; cin>>sna; cout<<"ENTER STUDETS ADDRESS :"; cin>>sadd; } void output() { cout<<"STUDENTS NUMBER IS :"<<sno<<endl; cout<<"STUDENTS NAME IS :"<<sna<<endl; cout<<"STUDENTS ADDRESS IS :"<<sadd<<endl; }};class lang{ int mt,me; public: void accept() { cout<<"ENTER MARKS IN TELUGU:"; cin>>mt; cout<<"ENTER MARKS IN ENGLISH :"; cin>>me; } void display() { cout<<"TELUGU MARKS ARE :"<<mt<<endl;
  36. 36. - 36 - cout<<"ENGLISH MARKS ARE :"<<me<<endl; }};class mathes:public lang{ int mm,mp,mc; public: void sentry() { cout<<"ENTER MARKS IN MATHS :"; cin>>mm; cout<<"ENTER MARKS IN PHYSICS :"; cin>>mp; cout<<"ENTER MARKS IN CHEMISTRY:"; cin>>mc; } void sprint() { cout<<"MARKS IN MATHS ARE :"<<mm<<endl; cout<<"MARKS IN PHYSICS ARE :"<<mp<<endl; cout<<"MARKS IN CHEMISTRY ARE :"<<mc<<endl; cout<<"TOTAL MARKS ARE :"<<mt+me+mm+mp+mc<<endl; }};class computers:public lang{ int mmt,mph,mcs; public: void sentry() {
  37. 37. - 37 - cout<<"ENTER MARKS IN MATHS :"; cin>>mmt; cout<<"ENTER MARKS IN PHYSICS :"; cin>>mph; cout<<"ENTER MARKS IN COMPUTERS:"; cin>>mcs; } void sprint() { cout<<"MARKS IN MATHS ARE :"<<mmt<<endl; cout<<"MARKS IN PHYSICS ARE :"<<mph<<endl; cout<<"MARKS IN COMPTERS ARE :"<<mcs<<endl; cout<<"TOTAL MARKSARE :"<<mt+me+mmt+mph+mcs<<endl; }};class arts:public lang{ int mhs,mec,mci; public: void sentry() { cout<<"ENTER MARKS IN HISTORY :"; cin>>mhs; cout<<"ENTER MARKS IN ECONOMICS:"; cin>>mec; cout<<"ENTER MARKS IN CIVICS :"; cin>>mci; } void sprint()
  38. 38. - 38 - { cout<<"HISTORY MARKS ARE :"<<mhs<<endl; cout<<"ECONOMICS MARKS ARE :"<<mec<<endl; cout<<"CIVICS MARKS ARE :"<<mci<<endl; cout<<"TOTAL MARKS ARE :"<<mt+me+mhs+mec+mci<<endl; }};void main(){ mathes m; computers cs; arts a; clrscr(); m.accept(); m.sentry(); clrscr(); cs.accept(); cs.sentry(); clrscr(); a.accept(); a.sentry(); clrscr(); m.display(); m.sprint(); getch(); cs.display(); cs.sprint(); getch(); a.display(); a.sprint();
  39. 39. - 39 - getch();}Example for Hybrid Example. (The Combination Of Any Two InheritanceIs Called Hybrid Inheritance.# include <iostream.h># include <stdio.h># include <conio.h># include <string.h>class student{ protected: int sno; char sna[20],sadd[25]; public: void input() { cout<<"ENTER STUENT NUMBER :"; cin>>sno; cout<<"ENTER STUDENTS NAME :"; cin>>sna; cout<<"ENTER STUDENTS ADDRESS:"; cin>>sadd; }};class test:public student{ protected: int mm,mp,mc;
  40. 40. - 40 - public: void mentry() { cout<<"ENTER MARKS IN MATHS :"; cin>>mm; cout<<"ENTER MARKS IN PHYSICS :"; cin>>mp; cout<<"ENTER MARKS IN CHEMISTRY:"; cin>>mc; }};class sports{ protected: int sm; public: void sentry() { cout<<"ENTER SPORTS MARKS :"; cin>>sm; }};class result:public test, public sports{ int tot,avg; char res[20]; public: void findres() { tot=mm+mp+mc;
  41. 41. - 41 - avg=tot/3; if(sm>50) avg=avg+5; if(avg>=75) strcpy(res,"DISTINCTION"); else if(avg>=60) strcpy(res,"FIRST CLASS"); else if(avg>=50) strcpy(res,"SECOND CLASS"); else if(avg>=35) strcpy(res,"THIRD CLASS"); else if(avg<35) strcpy(res,"FAILED"); } void display() { cout<<"STUDENT NUMBER IS :"<<sno<<endl; cout<<"STUDENTS NAME IS :"<<sna<<endl; cout<<"STUDENTS ADDRESS IS :"<<sadd<<endl; cout<<"MARKS IN MATHS ARE :"<<mm<<endl; cout<<"MARKS IN PHYSICS ARE :"<<mp<<endl; cout<<"MARKS IN CHEMISTRY ARE:"<<mc<<endl; cout<<"TOTAL MARKS ARE :"<<tot<<endl; cout<<"AVERAGE MARKS ARE :"<<avg<<endl; cout<<"RESULT OBTAINED :"<<res<<endl; }};void main(){ result r;
  42. 42. - 42 - clrscr(); r.input(); //member function of student class r.mentry(); //member function of test class r.sentry(); //member function of sports class r.findres(); //member function of result class clrscr(); r.display(); getch();}Friend function A friend function is a special function which is not a member ofany class but it is declared to access the private member data &functions provided in that class. C++ allows a common function to be made friendly with one ormore classes, there by allowing the function to have access to the privatedata of these classes, such a function need not be a member of any ofthese classes, only thing is to declare that function as a friend to theclass.Syntax for defining a friend functionclass sample{ private: member declaration; public: member function declaration; friend return_type function_name(arguments); //friend};
  43. 43. - 43 -The function declaration should be preceded by the keyword "friend".The function definition does not use the keyword friend or the scoperesolution operator "::". The functions that are declared with the keyword friend are known as friend functions. A function can be declaredas a friend in any number of classes.A friend function should possess the following characteristics (1)It is not in the scope of the class to which it has been declaredas friend(2)It cannot be called with the scope resolution operator(3)It can be invoked just like a normal function without help of any object(4)It can be declared either in public or private without affecting itsmeaning(5)Usually it has the objects as arguments(6)It cannot access the member names directly and has to use an objectname and dot membership operator with each member name (Ex. s.a);Friend Function Example.# include <iostream.h># include <conio.h>class sample;class myclass{ int a; public: void input() { cout<<"ENTER VALUE FOR A:"; cin>>a;
  44. 44. - 44 - } void output() { cout<<"A VALUE IS :"<<a<<endl; } friend int getsum(myclass m,sample a)};class sample{ int x; public: void accept() { cout<<"ENTER A VALUE :"; cin>>x; } //friend function declaration friend int getsum(myclass m,sample s)};int getsum(myclass m,sample s){ return(m.a+s.x);}void main(){ myclass c; sample d; int t; clrscr(); c.input();
  45. 45. - 45 - d.accept(); t=getsum(c,d); //friend function calling clrscr(); c.output(); d.accept(); cout<<"TOTAL VALUE IS :"<<t<<endl; getch();}2nd Example for a Friend Function.# include <iostream.h># include <stdio.h># include <conio.h>class allow;class ded;class employ{ int eno,bs; char ena[10]; public: void accept() { cout<<"ENTER EMPLOY NUMBER :"; cin>>eno; cout<<"ENTER EMPLOY NAME :"; cin>>ena; cout<<"ENTER BASIC SALARY :"; cin>>bs; }
  46. 46. - 46 - friend void calc_sal(employ e,allow a,ded d);};class allow{ int da,hra,cca; public: void getallow() { cout<<"ENTER DA, HRA, CCA :"<<endl; cin>>da>>hra>>cca; } friend void calc_sal(employ e,allow a,ded d);};class ded{ int pf,it; public: void getded() { cout<<"ENTER PF, IT :"<<endl; cin>>pf>>it; } friend void calc_sal(employ e,allow a,ded d);};void calc_sal(employ e,allow a,ded d){ int gs,ns,tall,tded; tall=d.pf+d.it+a.cca; tded=d.pf+d.it; gs=e.bs+tall;
  47. 47. - 47 - ns=gs-tded; clrscr(); cout<<"ENTER EMPLOY NUMBER :"<<e.eno<<endl; cout<<"ENTER EMPLOY NAME :"<<e.ena<<endl; cout<<"ENTER BASIC SALARY :"<<e.bs<<endl; cout<<"DA IS :"<<a.da<<endl; cout<<"HRA IS :"<<a.hra<<endl; cout<<"CCA IS :"<<a.cca<<endl; cout<<"PF IS :"<<d.pf<<endl; cout<<"IT IS :"<<d.it<<endl; cout<<"GROSS SALARY IS :"<<gs<<endl; cout<<"NET SALARY IS :"<<ns<<endl;}void main(){ employ emp; allow all; ded s; clrscr(); emp.accept(); all.getallow(); s.getded(); calc_sal(emp,all,s); getch();}Friend Functions with Objects as Arguments and Return Type.# include <iostream.h># include <conio.h>
  48. 48. - 48 -class test;class sample{ int a; float b; public: void input() { cout<<"ENTER ANY INTEGER AND FLOAT VALUES :"<<endl; cin>>a>>b; } void display() { cout<<"A VALUE IS :"<<a<<endl; cout<<"B VALUE IS :"<<b<<endl; } friend sample setsum(sample x,test y);};class test{ int m; float n; public: void accept() { cout<<"ENTER INTEGER AND FLOAT :"<<endl; cin>>m>>n; } void print() {
  49. 49. - 49 - cout<<"M VALUE IS :"<<m<<endl; cout<<"N VALUE IS :"<<n<<endl; } friend sample setsum(sample x,test y);};sample setsum(sample x,test y){ sample r; r.a=x.a+y.m; r.b=x.b+y.n; return r;}void main(){ sample s,p; test t; clrscr(); s.input(); t.accept(); clrscr(); p=setsum(s,t); cout<<"VALUE OF FIRST OBJECT IS :"<<endl; s.display(); cout<<"VALUE OF SECOND OBJECT IS :"<<endl; t.print(); cout<<"VALUE OF RESULT OBJECT IS :"<<endl; p.display(); getch();}
  50. 50. - 50 -Constructors A constructor is a special member function whose task is toinitialize the objects or variables of a class. The constructor is invokedimplicitly (automatically) whenever an object is created. It is calledconstructor, because it will be called implicitly upon the construction ofan object.A constructor is declared as follows.class class_name{ data members;public: class_name(arguments) //constructor { statements; }};E.g.:class sample{ private: int a,b; float x,y; public: sample() //constructor function { a=100; b=200; x=35.15; y=564.25;
  51. 51. - 51 - }};void main(){ clrscr(); sample s; getch();}Characteristics of a constructor 1. It should have the same name as the class name 2. They are invoked automatically when the objects are created. 3. They cannot be called explicitly. 4. Like C++ functions they can have default arguments. 5. They do not return any value not even void 6. They cannot be inherited but the derived class can call the base class constructor 7. It cannot be virtual 8. We cannot refer to their addresses 9. They will make implicit called to new & delete operator when memory allocation is requiredTypes of constructors (3 Types) 1. Default constructor (Non Parameterized): It won’t take anyarguments. 2. Parameterized constructor: It can take any no. of arguments. 3. Copy constructor: It will take a reference of an object as anargument.Example for Constructors# include <iostream.h>
  52. 52. - 52 -# include <stdio.h># include <conio.h>class test{ int a; float b; long c; public: test() //constructor function { a=230; b=654.13; c=54865; } void output() { cout<<"INTEGER VALUE IS :"<<a<<endl; cout<<"FLOAT VALUE IS :"<<b<<endl; cout<<"LONG VALUE IS :"<<c<<endl; }};void main(){ clrscr(); test t,s,r; clrscr(); cout<<"VALUES OF T ARE :"<<endl; t.output(); cout<<"VALUES OF S ARE :"<<endl;
  53. 53. - 53 - s.output(); cout<<"VALUES OF R ARE :"<<endl; r.output(); getch();}Example for Constructor Function.# include <iostream.h># include <conio.h>class stud{ int sno,tf,fp,due; char sna[10],cou[10]; public: stud() { cout<<"enter students number :"; cin>>sno; cout<<"enter students name :"; cin>>sna; cout<<"enter course name :"; cin>>cou; cout<<"enter total fee is :"; cin>>tf; cout<<"enter fee paid :"; cin>>fp; due=tf-fp;
  54. 54. - 54 - } void output() { cout<<"students number is :"<<sno<<endl; cout<<"students name is :"<<sna<<endl; cout<<"course name is :"<<cou<<endl; cout<<"total name is :"<<tf<<endl; cout<<"fee paid is :"<<fp<<endl; cout<<"due fee is :"<<due<<endl; }};void main(){ clrscr(); stud s,t,u; clrscr(); cout<<"values of s"<<endl; s.output(); cout<<"values of t"<<endl; t.output(); cout<<"values of u"<<endl; u.output(); getch();}Example for Constructor with Arguments.# include <iostream.h>
  55. 55. - 55 -# include <conio.h># include <string.h>class sales{ int sno,samt; char sna[10]; public: sales(int a,char n[],int b) { sno=a; strcpy(sna,n); samt=b; } void output() { cout<<"SALES MAN NUMBER IS :"<<sno<<endl; cout<<"SALES MAN NAME IS :"<<sna<<endl; cout<<"SALES AMOUNT IS :"<<samt<<endl; }};void main(){ clrscr(); sales t(100,"RAVI",2500); sales b=sales(101,"KIRAN",3000); cout<<"VALUES OF T :"<<endl; t.output(); cout<<"VALUES OF B :"<<endl; b.output(); getch();
  56. 56. - 56 -}Constructors in derived class: If the base class contain a constructor with one or morearguments, then it is mandatory for the derived class to have aconstructor and to pass the arguments to the bas class constructors,since while applying inheritance we usually create the objects by usingthe derived class. Thus, it makes sense for the derived class to passarguments to the base class constructor. When both the base class &derived class contain constructors, the base constructor is executed firstand then the constructor in the derived class is executed. The syntax for defining the constructor in the derived class isConstructor(arglist) : initialization-section { assignment section }Destructor A destructor as the name implies, is used to destroy the objectsthat have been created by a constructor. Like a constructor, thedestructor is also a member function whose name is same as the classname and is preceded by a tilde (~) symbol. A destructor neither takesany arguments nor returns any value. It will be invoked implicitly by thecompiler upon exit from the program to clean up the storage that is nolonger accessible.The destructor fulfills the opposite functionality. It is automatically calledwhen an object is destroyed, either because its scope of existence hasfinished (for example, if it was defined as a local object within a function
  57. 57. - 57 -and the function ends) or because it is an object dynamically assignedand it is released using the operator delete.The destructor must have the same name as the class, but preceded witha tilde sign (~) and it must also return no value.The use of destructors is especially suitable when an object assignsdynamic memory during its lifetime and at the moment of beingdestroyed we want to release the memory that the object was allocated.Overloading Constructors Like any other function, a constructor can also be overloaded withmore than one function that have the same name but different types ornumber of parameters. Remember that for overloaded functions thecompiler will call the one whose parameters match the arguments usedin the function call. In the case of constructors, which are automaticallycalled when an object is created, the one executed is the one thatmatches the arguments passed on the object declaration:Important: Notice how if we declare a new object and we want to use itsdefault constructor (the one without parameters), we do not includeparentheses ():Operator Overloading C++ has the ability to provide the special meaning to an existingoperator. The mechanism of giving such special meaning to an operatoris known as operator overloading.This is done with help of a special function, called operator function,which describes the task.Syntax: return_type class_name :: operator op(arg_list) {
  58. 58. - 58 - function_body; }where return_type is the type of value returned by the specified operationand op is the operator being overloaded. The keyword "operator" shouldprecede the "op". operator op is the function name.It can be either member function or friend function. The basic differenceis a friend function will have only one argument for unary operator & twofor binary operator. But the member function will have no arguments forunary operator & one argument for binary operatorSome Operator Which Cannot Be Overloaded Are1). & ->2) sizeof() [operator]3) scope resolution operator(::)4) conditional operator(:?)Example for Operator Overloading Of Unary Operator:# include <iostream.h># include <conio.h>class exam{ int a; float b; long c; public: exam() //constructor function { a=10;
  59. 59. - 59 - b=25.65; c=42500; } exam operator ++() //operator overloading function { a+=100; b+=100; c+=100; return *this; } void print() { cout<<"A VALUE IS :"<<a<<endl; cout<<"B VALUE IS :"<<b<<endl; cout<<"C VALUE IS :"<<c<<endl; }};void main(){ exam e; int x=15; clrscr(); cout<<"VALUE BEFORE FUNCTION CALLING :"<<endl; e.print(); cout<<"x value is :"<<x<<endl; ++e; //operator function calling x++; cout<<"value after function calling "<<endl; e.print();
  60. 60. - 60 - cout<<"x value is :"<<x<<endl; getch();}Output: Values before function calling A value is 10, B value is 25.65, C value is 42000 and X valueis 15. Values after function calling A value is 110, B value is 125.65, C value is 142000 and Xvalue is 16.Example Program for Operator Overloading a Binary Operator "+":# include <iostream.h># include <stdio.h># include <conio.h>class sample{ int a,b; float m,n; public: void get_data() { cout<<"ENTER ANY TWO INTEGERS AND TWO FLOATS :"; cin>>a>>b>>m>>n; } void print()
  61. 61. - 61 - { cout<<"FIRST INTEGER IS :"<<a<<endl; cout<<"SECOND INTEGER IS :"<<b<<endl; cout<<"FIRST FLOAT IS :"<<m<<endl; cout<<"SECOND FLOAT IS :"<<n<<endl; } //operator overloading function sample operator +(sample s) { sample t; t.a=this->a+s.a; t.b=this->b+s.b; t.m=this->m+s.m; t.n=this->n+s.n; return(t); }};void main(){ sample p,q,r; clrscr(); p.get_data(); q.get_data(); clrscr(); r=p+q; //function calling cout<<"values of first object :"<<endl; p.print(); cout<<"values of second object :"<<endl;
  62. 62. - 62 - q.print(); cout<<"addition object values are :"<<endl; r.print(); getch();}Example Program For Overloading A Binary Operator "*":# include <iostream.h># include <stdio.h># include <conio.h>class sales{ int sno,nou; char sna[10]; public: sales() //constructor { cout<<"ENTER SALES MAN NUMBER :"<<endl; cin>>sno; cout<<"ENTER SALES MAN NAME :"<<endl; cin>>sna; cout<<"ENTER NUMBER OF UNITS :"<<endl; cin>>nou; } void print() { cout<<"SALES MAN NUMBER IS :"<<sno<<endl; cout<<"SALES MAN NAME IS :"<<sna<<endl; cout<<"NUMBER OF UNITS ARE :"<<nou<<endl;
  63. 63. - 63 - } int operator *(int n) { return(nou * n); }};void main(){ sales s; int rpu,samt; clrscr(); cout<<"ENTER RATE PER UNIT :"<<endl; cin>>rpu; clrscr(); samt=s*rpu; //operator function calling s.print(); cout<<"RATE PER UNIT IS :"<<rpu<<endl; cout<<"SALES AMOUNT IS :"<<samt<<endl; getch();}Abstract class: An abstract class is one that is not used to create objects. It isdesigned only to act as a base class upon which the other classes maybuild.Polymorphism:
  64. 64. - 64 - Polymorphism means one name multiple forms. Polymorphismcan be classified into 1. Compile time polymorphism a. Function overloading b. Operator overloading The overloaded member functions are selected for invoking mymatching arguments both type and number. This information is knownto the compiler at the compile time and therefore, the compiler is able toselect the appropriate function for a particular call at the compile timeitself. This is called early binding or static binding or static linking. It’salso known as compile time polymorphism, early binding simply meansthat an object is bound to its function call at compile time.2. Runtime polymorphism a. Virtual functionsThe process of selecting the appropriate member function during runtime is known as runtime polymorphism also known as late bindingPointers to Objects: Object pointers are useful for creating objects at run-time. We canalso use an object pointer to access the public members of an object. Thesyntax for defining a pointer to an object is Class name pointer-variable-name Ex: item *ptr;We can refer to the member functions of item in two ways
  65. 65. - 65 -Ex: ptr->getdata();//by using ->operator (*ptr).getdat();We can also created the objects with the help of new operator as follows Item *ptr=new item;The above statement allocates enough memory for the data members inthe object structure and assigns the address of the memory space to ptr.Virtual functions: A virtual function is a member function of a class, whosefunctionality can be over-ridden in its derived classes. It is one that isdeclared as virtual in the base class using the virtual keyword. Thevirtual nature is inherited in the subsequent derived classes and thevirtual keyword need not be re-stated there. The whole function body canbe replaced with a new set of implementation in the derived class.How does a Virtual Function work? Whenever a program has a virtual function declared, a v - table isconstructed for the class. The v-table consists of addresses to the virtualfunctions for classes that contain one or more virtual functions. Theobject of the class containing the virtual function contains a virtualpointer that points to the base address of the virtual table in memory.Whenever there is a virtual function call, the v-table is used to resolve tothe function address. An object of the class that contains one or morevirtual functions contains a virtual pointer called the vptr at the verybeginning of the object in the memory. Hence the size of the object in thiscase increases by the size of the pointer. This vptr contains the baseaddress of the virtual table in memory. Note that virtual tables are classspecific,
  66. 66. - 66 -i.e., there is only one virtual table for a class irrespective of the numberof virtual functions it contains. This virtual table in turn contains thebase addresses of one or more virtual functions of the class. At the timewhen a virtual function is called on an object, the vptr of that objectprovides the base address of the virtual table for that class in memory.This table is used to resolve the function call as it contains the addressesof all the virtual functions of that class. This is how dynamic binding isresolved during a virtual function call.Rules for virtual functions: 1. The virtual functions must be member of some class 2. They cannot be static members 3 .They are accessed by using object pointers 4. It can be friend of another class 5. We cannot have virtual constructors but we can have virtualdestructors 6. While a base pointer point to any type of the derived object thereverse is not possiblePure virtual functions: When we declare a function as virtual inside the base class andredefine in the derived class the function defined inside the base class isseldom used for performing any task. It only serves as a placeholder.Such functions are called do-nothing functions. A do-nothing function may be defined as follows Virtual void display() = 0; Such functions are called pure virtual functionsFile Streams Remember that a C++ program views input (or output) as a stream
  67. 67. - 67 -of bytes. On input, a program extracts (>>) bytes from an input stream.On output, a program inserts (<<) bytes into the output stream. Thestream acts as a mediator between the program and the streams sourceor destination.In this same manner, input and output data is handled by use of astream buffer.A buffer is a block of memory used as an intermediate, temporary storagearea for the transfer of information between a program and a device (e.g.file). Many real-life problems handle large volumes of data and in suchsituations we need to use some of the devices such as floppy disk or harddisk to store the data. The data is stored in these devices using theconcept of files. A file is a collection of related data stored in a particulararea on the disk. Programs can be designed to perform the read andwrite operations on these files
  68. 68. - 68 - A program typically involves either or both of the following kinds ofdata communication (1) Data transfer between the console unit and the program (2) Data transfer between the program and a disk fileThe I/O system of C++ contains a set of classes that define the filehandling methods. These include ifstream, ofstream and fstream. Theseclasses are derived from fstreambaseClass Contentsfstreambase Provides operations common to the file stream. Serves as a base for fstream, ifstream and ofstream class. Contains open() and close() functionsifstream Provides input operations. Contains open() withdefault input mode. Inherits the functions get(),getline(),read(), seekg() and tellg() functions from ostreamofstream Provides output operations. Contains open() with default output mode. Inherits put(), seekp(), tellp() and write() functions from ostreamfstream Provides support for simultaneous input and output operations. Contains open() with default input mode.
  69. 69. - 69 - Inherits all the functions from istream and ostream classes through iostream For opening a file we must first create a file stream and then linkto the file name. A file stream can be defined using the classes ifstream,ostream, and fstream that are contained in the header file fstream. Theclass to be used depend upon the purpose, that is, whether we want toread data from file or write data to it. A file can be opened in two ways.(1)Using the constructor function of the class(2)Using the member function open() of the class The first method is used when we use only one file in the system.The second method is used when we want manage with multiple filesusing one stream.Opening file using constructor: A constructor is used to initialize an object while it is beingcreated. Here a file name is used to initialize the file stream object. Thisinvolves the following steps 1. Create a file stream object to manage the stream using theappropriate class. That is to say, the class ofstream is used to create theoutput stream and the class ifstream to create the input stream. 2. Initialize the file object with the desired file For example, the following statement opens a file named “results”for outputofstream outfile(“results”);
  70. 70. - 70 -Opening Files using open (): The function open() can be used to open multiple files that use thesame stream object. There are two forms for open() methodWith One argument:File-stream-class stream-object;Stream-object.open(“filename”);Ex:ifstream fin;With two arguments:Stream-object.open(“filename”,mode);File mode parameters:Parameter Meaningios::in opening file for reading onlyios::out opening file for writing onlyDetecting end of file: Detecting end-of-file is necessary for preventing any furtherattempt to read the data from the file. We can use the following methodsfor detecting the end of the file By using while loop for ex:while(fin) By using the method eof() for ex: if(fin1.eof()!=0)
  71. 71. - 71 - { exit(1); } eof() is a member function of ios class. It returns a non-zero valueif the end of the file is encountered and a zero otherwise.Fail() This method returns true when an input or output operation hasfailedREAD() AND WRITE(): To read and write the class objects onto the file wehave to use the methods read() and write() and its syntax is Infile.read((char *)&v, sizeof(v)); Outfile.write((char *)&v,sizeof(v)); The above two functions will take two arguments 1. Address of the variable 2. Size of the variableios::in Open for input operations.ios::out Open for output operations.ios::binary Open in binary mode. Set the initial position at the end of the file.ios::ate If this flag is not set to any value, the initial position is the beginning of the file. All output operations are performed at the end of the file, appending the content to the current content of the file. Thisios::app flag can only be used in streams open for output-only operations. If the file opened for output operations already existed before,ios::trunc its previous content is deleted and replaced by the new one.
  72. 72. - 72 -All these flags can be combined using the bitwise operator OR (|). Forexample, if we want to open the file example.bin in binary mode to adddata we could do it by the following call to member function open(): ofstream myfile; myfile.open ("example.bin", ios::out | ios::app | ios::binary);Each one of the open() member functions of the classes ofstream,ifstream and fstream has a default mode that is used if the file is openedwithout a second argument: class default mode parameterofstream ios::outifstream ios::infstream ios::in | ios::outFor ifstream and ofstream classes, ios::in and ios::out are automaticallyand respectivelly assumed, even if a mode that does not include them ispassed as second argument to the open() member function.The default value is only applied if the function is called withoutspecifying any value for the mode parameter. If the function is calledwith any value in that parameter the default mode is overridden, notcombined.File streams opened in binary mode perform input and output operationsindependently of any format considerations. Non-binary files are knownas text files, and some translations may occur due to formatting of somespecial characters (like newline and carriage return characters).Since the first task that is performed on a file stream object is generallyto open a file, these three classes include a constructor thatautomatically calls the open() member function and has the exact same
  73. 73. - 73 -parameters as this member. Therefor, we could also have declared theprevious myfile object and conducted the same opening operation in ourprevious example by writing: ofstream myfile ("example.bin", ios::out | ios::app | ios::binary);Combining object construction and stream opening in a single statement.Both forms to open a file are valid and equivalent.Templates Templates in one the important features of C++ which enables usto create generic programming. It is an approach where generic typesare used as parameters in algorithms so that they work for a variety ofsuitable data types and data structures. It can be considered as a kind ofmacro. They are also called as ‘parameterized classes or functions’. We can define templates for both classes and functions. A templatecan be used to create a family of classes or functions. A template can becontributed as a kind of macro. When an object of a specific type isdefined for actual use, the template definition for that class issubstituted with the required data type. Since a template is defined witha parameter that would be replaced by the specified data type at the timeof actual use of the class or function, the templates are some times calledparameterized classes or functions.The class template definition is very similar to an ordinary classdefinition except the prefix template <class T> and the use of type T.This prefix tells the compiler that we are going to declare a template anduse T as a type name in the declaration.The general format for class template is
  74. 74. - 74 -template <class T> class classname { class member specification with anonymous type T wherever appropriate }The general format for template functiontemplate <class T> return_type function_name (arguments of type T) { body of function}Example Program for Template Function.# include <iostream.h># include <conio.h>template<class A>A add(A x,A y){ return x+y;}void main(){ int m,n; float f,p; long l,r; clrscr(); cout<<"ENTER TWO INTERGER :"<<endl; cin>>m>>n;
  75. 75. - 75 - cout<<"ENTER TWO FLOATS :"<<endl; cin>>f>>p; cout<<"ENTER TWO LONGS :"<<endl; cin>>l>>r; cout<<"FIRST INTEGER IS :"<<m<<endl; cout<<"SECOND INTEGER IS :"<<n<<endl; cout<<"FIRST FLOAT IS :"<<f<<endl; cout<<"SECOND FLOAT IS :"<<p<<endl; cout<<"FIRST LONG IS :"<<l<<endl; cout<<"SECOND LONG IS :"<<r<<endl; cout<<"SUM OF INTEGERS IS :"<<add(m,n)<<endl; cout<<"SUM OF FLOATS IS :"<<add(f,p)<<endl; cout<<"SUM OF LONGS IS :"<<add(l,r)<<endl; getch();}Example Program to Template Functions with Multiple Templates.# include <iostream.h># include <stdio.h># include <conio.h>template<class A,class B>A add (A x,B y){ return(x+y);}void main(){ int m; float f; long l; clrscr();
  76. 76. - 76 - cout<<"ENTER AN INTEGER :"<<endl; cin>>m; cout<<"ENTER A FLOAT VALUE :"<<endl; cin>>f; cout<<"ENTER A LONG VALUE :"<<endl; cin>>l; clrscr(); cout<<"INTEGER VALUE IS :"<<m<<endl; cout<<"FLOAT VALUE IS :"<<f<<endl; cout<<"LONG VALUE IS :"<<l<<endl; cout<<"SUM OF INTEGER AND FLOAT VALUE IS :"<<add(m,f)<<endl; cout<<"SUM OF FLOAT AND INTEGER VALUE IS :"<<add(f,m)<<endl; cout<<"SUM OF LONG AND FLOAT VALUE IS :"<<add(l,f)<<endl; cout<<"SUM OF LONG AND INTEGER VALUE IS :"<<add(l,m)<<endl; getch();}Example Program for Class Templates.# include <iostream.h># include <conio.h>template<class A>class sample{ A n,m,f; public: void input() { cout<<"ENTER FIRST VALUE :"; cin>>n; cout<<"ENTER SECOND VALUE :"; cin>>m;
  77. 77. - 77 - cout<<"ENTER THIRD VALUE :"; cin>>f; } A total() { return(n+m+f); } void output() { cout<<"FIRST VALUE IS :"<<n<<endl; cout<<"SECOND VALUE IS :"<<m<<endl; cout<<"THIRD VALUE IS :"<<f<<endl; }};void main(){ sample <int> T1; //object declared with integer members sample <float> T2; //object declared with float members sample <long> T3; //object declared with long members clrscr(); cout<<"ENTER INTEGER VALUES :"<<endl; T1.input(); cout<<"ENTER FLOAT VALUES :"<<endl; T2.input(); cout<<"ENTER LONG VALUES :"<<endl; T3.input(); clrscr(); cout<<endl<<"INTEGER VALUES ARE :"<<endl; T1.output(); cout<<"TOTAL VALUE IS :"<<T1.total()<<endl;
  78. 78. - 78 - cout<<endl<<"FLOAT VALUES ARE :"<<endl; T2.output(); cout<<"TOTAL VALUE IS :"<<T2.total()<<endl; cout<<endl<<"LONG VALUES ARE :"<<endl; T3.output(); cout<<"TOTAL VALUE IS :"<<T3.total()<<endl; getch();}

×