Sunday 21 October 2012



Difference between procedure oriented language & object oriented language.

Procedure oriented language
object oriented language.
1.Large program are devided into smaller programs know as function. 
1.programs are devided  into objects.

2.It follows top to down approach in program designing .
2.It follows bottom up approach in program
designing.
3.Most of the function other global data.
3.The data is hidden and Can not be access by external classes.

4.Procedure oriented have more code .
4.objete originated has less code .
5.in procedure oriented language the main emphasis is on procedure .
5.in object oriented language main part is data.
6.procedure oriented   language is fully concentrates on procedures function/methods  .
6.object oriented language is fully concentrates on classes, object ,abstraction,encapsulation, data-hiding , inheritance, polymorphism
7.for example:Cobol, pascal ,c,fortram ,etc.           
7.for example :c++ jawa,vb.net,c#,etc.

8.in procedure oriented language data has no security.                                         
8.in object oriented language data has a security.

** Basic data types
                                   
                                                            C++ Data type
↓                                                                      ↓                                                          ↓         
User defined type                              built in type                                        derived type

1.      Structure                                 1.integer                                              1.array
2.      Union                                      2.char                                                  2.function
3.      Class                                        3.void                                                  3.pointer
4.      Enumeration                            4.float
                                                5.double

Operators in c++
           
׃ ׃   Scope resolution operator.
→ ( ) [ ] postfix ++ postfix - -
Prefix ++ prefix- - ~ ! unary + unary – unary * unary & (type) size of new

→ **                           pointer to member
/ * %                            division, multiplication and modules.
+  -                               addition   substraction.
<<  >>                         left shift , right shift.
<< =>>=                      less than, less then equal to
= = ! =                         equality ,inequality.
  &                               bitwise AND
  ^                                bitwise XOR
  !                                 bitwise OR
  &&                            bitwise AND
!!                                  bitwise OR
? :                                condition statement
=*=/=%=+=       assignment
=<<= >>=&=    operator
^=/=      
    ,                               comma operator
→ *                             pointer to member
.*                                 pointer to member
delete                          memory release op
end                              line feed op
new                             memory allocation op
setw                             field  width op

<<Insertion operator:

<< is insertion or put to operator .
If inserts the contents of variable on it’s right to the object on its left
            Cout<< string ;
→ This statement will display the content of string .
→ It is predefined object which represents standard output stream in c++ .
Extraction operator :­( >>):

→ It is also called as get form operator .
→ Extraction operator is used  when we take the value form the keyboord  and assign to the variable .
→This is similar to scant ( ) operation
                        cin >> number ;
→It is predefined object which represent standard input  stream in c++ .

 Scope resolution operator :-

                        : : S.R operator can be used to        a hidden variable .
                                    : : variable – name .
   This operator allows access to global version of variable .

Memory management operator :-
            C++ defines two unary operators new & delete to perform task of allocation memory dynamicalls at runtime and freeing memory .
→ new operator is used to create object .
           
Syntax ;
                        Pointer – variable = new datatype .
eg :- int *p = new int (   )
→ new operator allocates the memory to hold  a data object of 
type and returns the address of the object .   
→ delete op destroyed or release memory space for reuse .
→ deallocate the memory
                        delete pointer –variable;
                        eg :-  delete p ;

         
 Manipulator :-
            Most commonly used manipulator setw and endl .
 endl is similar to “ \n” i.e. Next line . 
                                    Cout<<“m=” <<m << endl ; 
                                    Cout << “n=”<<n<< endl ;
                                                           
                                                o/p
                        m =  12
                        n  =   14

Setw :-
                        Set the width specifies fieldwidth.
                        eg :- cout << setw (5)<< sum <<endl.

Declaration of variables :-

→variable must be declared before they are us in executable statements .
→ They can be declared anywhere in the program .
            Syntax :-  datatype variable name;
            eg :- float x ;
                        float sum = 0;
                         sum = sum + x;
                        float avg ;
                        avg = sum/; ;

Dynamic initialization of the variable

             c++ permits initialization of the variable at runtime. This is called as dynamic initialization .
            For ex :-
                                    float area = 3.14 * r *r ;
                                    float avg  = sum /; ;


Reference variable :-
-          A  reference variable provides on alternative name ( alias ) for a previously defined variable .
Syntax :- datatype & ref . name = variable name
ex :-  float total = 100
            float & sum = total ;

Local variable :-
local variables are declared in function and can be accessed only within the function.
            ex. Main ( )
            {
                        int i = 4 ;
                         i ++ ;
            }

Global variable :-
Global variables are declared outside the function and can be accessed anywhere in the program.

            int i = 4;
            Main ( )
            {
            i ++ ;
            }
Actual parameters :-
            Actual parameters are parameters as they appear in function calls .
Formal parameters : -
            Formal parameters are parameter as they appear in function declaration .

Array :-
            Array is a grope of similar datatype .
→ declaration of one dimentional array →
Syntax :-
            Storage class data type array name [exp];
            int marks [100];
            Static char page [8];
int values [7] ={1,2,3,4,5,6,7};
Two dimension array.
            int × [2] [2]  = {1,2,3,4};
Adventages of array

(1)               You can use one name for similar objects and save then with the same name but different index .
(2)               Arrays are vary useful when you are work with sequence of same kind of data .
(3)               Arrays use reference type & so on .
 

Pointer :-

      Pointer is a variable that holds the memory address of another variable .

Pointer and function :
      The use of pointer in a function definition may be classified into two groups.
   І) call by value 
   ІI) call by reference .

I)                   Call by value :
                              When a portion of the program invokes a function,control will be transfered form main function  .
                              This  is call by value .
                  main ( )
{
Void fun  ( int x , int y );

}
Void fun ( int a, int b)
{

}

 II) Call by reference :-
                  In when the function is called by a program the address of  the actual argument are copied onto the formal arguments  i,e formal & actual argument are referencing to same memory
location therefore change in value of formal argument affects the value of actual argument . the call by reference is used when function  produces more then one value provide these values to the caller .
e.g :-  main ( )
                  {
                  Void fun ( int * x, int * y );
                 

                  fun (&x ,&y); //call by reference

                  }
                  Void fun ( int *a,int *b)
                  {

                  }

Pointers & arrays
                              In c++ there is close correspondence between array datatype & pointer .
-          The only difference is that pointer variable appears on left side of assignment operator while array name appears on right side consider ,
                             int value [20];
                                          int  * ptr ;
-          The address of first element of array is value [0];
-           The pointer variable ptr is also an address .
-          We can writer ptr = & value [0]
-          The address of o th element is assigned to ptr .
                        * ptr = = & value [0]
Value [i] is same as * ((value) +(i))
             
// pointer and array
#   include < iostream.h>
#   include <conio .h>
Void main ( )
{
Satic int a [4] = {11,12,13,14};
int  i  , n ,temp;
n=4;
Cout << “content of array”<< endl;
for ( i=0; i<=n-1;++i)
{
temp = * ((a) +(i));
Cout << “ value =”<<temp<<endl;
  }
}

Principles of object oriented language:
Some of the important object oriented features are namely:
v  Emphasis is data rather than procedure.
v  Programs are divided into objects.
v  Every object has its own data & functions.
v  The data of object can be accessed by the functions associated with that object.
v  Data is hidden and can not be accessed by external functions.
v  New data & functions can be easily added whenever necessary.
v  Follows bottom up approach in program design.
Basic concepts of OOPS and Structure of C++ program
Some of the important object oriented features are namely:
  • Objects
  • Classes
  • Inheritance
  • Data Abstraction
  • Data Encapsulation
  • Polymorphism
  • Overloading
  • Reusability

Objects:
Object is the basic unit of object-oriented programming. Objects are identified by its unique name. An object represents a particular instance of a class. There can be more than one instance of a class. Each instance of a class can hold its own relevant data.

An Object is a collection of data members and associated member functions also known as methods.
Classes:
Classes are data types based on which objects are created. Objects with similar properties and methods are grouped together to form a Class. Thus a Class represents a set of individual objects. Characteristics of an object are represented in a class as Properties. The actions that can be performed by objects become functions of the class and are referred to as Methods.
For example consider we have a Class of Cars under which Santro Xing, Alto and WaganR represents individual Objects. In this context each Car Object will have its own, Model, Year of Manufacture, Color, Top Speed, Engine Power etc., which form Properties of the Car class and the associated actions i.e., object functions like Start, Move, and Stop form the Methods of Car Class.
No memory is allocated when a class is created. Memory is allocated only when an object is created, i.e., when an instance of a class is created.
Inheritance:
Inheritance is the process of forming a new class from an existing class or base class. The base class is also known as parent class or super class. The new class that is formed is called derived class. Derived class is also known as a child class or sub class. Inheritance helps in reducing the overall code size of the program, which is an important concept in object-oriented programming.
Data Abstraction:
Data Abstraction increases the power of programming language by creating user defined data types. Data Abstraction also represents the needed information in the program without presenting the details.
Data Encapsulation:
Data Encapsulation combines data and functions into a single unit called Class. When using Data Encapsulation, data is not accessed directly; it is only accessible through the functions present inside the class. Data Encapsulation enables the important concept of data hiding possible.
Polymorphism:
Ability to take more than one form means polymorphism. An operator or function can be given different meanings or functions. Polymorphism refers to a single function or multi-functioning operator performing in different ways.
Overloading:
Overloading is one type of Polymorphism. It allows an object to have different meanings, depending on its context. When an existing operator or function begins to operate on new data type, or class, it is understood to be overloaded.
Classes and Objects:
A class is a way to bind data and function together. It allows data to be hidden, fro external use. When defining a class we are creating a new abstract datatype that can be treated like any other built in type. Generally, a class specification has two parts:
1.      Class declaration
2.      Class function definition

Syntax:
Class class_name
{
Private:
            Variable declaration;
            Function declaration;
Public:
            Variable declaration;
            Function declaration;
};
The function & variables are the members of the class.They are usually grouped into two sections,private & public.These are visibility modes.
The members that have been declared as a private can be accessed only from within the class.Public members can be accessed from outside the class.
Use of keyword private is optional.By default all members are private.
Eg
Class item
{
Private:
            Int number;
Float cost;
            Public:
                        Void getdata(int a,float b);
                        Void putdata ();
};
Here item is name of class. It contains two data members and two member functions. Data members are private and both the function members are public.
The declaration of item as above, does not defined any objects of item but only specifies  what it will contain. Once class is declared ,we can create variable of that class.
Eg.item x;
Creates a variable of x type item. The class variables are known as objects ie.x is object of type item.At declaration, the necessary memory space is allocated to the object.
We can create more than one object.
item x,y,z;
The private data of class can be accessed only through the functions of that class. main() can not contain any statement that access number and cost directly.
The general form for calling a member function is:
Object_name.function name(actual arguments);
Eg.       X.getdat(200,125.5);
x.putdata();
The class method definition :

Member function in the class can be defined under the different access specifiers.

User can specify the code for the members in two different ways :


·                     Inside the class definition
·                     Outside the class definition

Outside the class definition

The member function can be declared outside the class definition with the help of
Scope resolution operator.

Note that if the definition of the member function(method) is large then it is better to declare
it outside the class definition. This is achieved by using the scope resolution operator.



Syntax :

return-type class-name :: function name
{
body of function
}

Here '::' is the scope resolution operator.

Note :


·                     Scope resolution operator specifies that the scope of the function is restricted to the
class name. We will discuss about 'scope' later.
·                     Class name:: is called as membership label. It tells to compiler that the function belong to that class.
·                     By using this operator, different classes can use the same function name.
For example:
Void item::getdata(int a,float b)
{
number=a;
Cost=b;
}
Void item::putdata()
{
Cout<<”Number=”<<number<<endl;
Cout<<”cost=”<<cost;
}


Inside the class definition :

In this way the member function processes all the operations just as the simple function declaration.
The functions defined inside the class are inline functions. The functions defined in a class specification are automatically inline.
Class item
{
Private:
            Int number;
Float cost;
            Public:

Void getdata(int a,float b)
{
number=a;
Cost=b;
}
Void putdata()
{
Cout<<”Number=”<<number<<endl;
Cout<<”cost=”<<cost;
}
};

Static data members:
The static is a keyword and are used to retain value of a variable.
Characteristics of static data member:
    1. When a variable is declared as static it is initialized to zero. No other initialization as permitted.
    2. Only one copy of that member is created for the entire class is shared by all the objects of class, no matter how many objects are created.
    3. It is visible only within the class,but its lifttime is entire the class.
For example:

#include<iostream.h>
#include<conio.h>
class stat
{
    int code;
    static int count;

   public:
    stat()
    {
      code=++count;
    }
    void showcode()
    {
      cout<<"\n\tObject number is :"<<code;
    }
    static void showcount()
    {
              cout<<"\n\tCount Objects :"<<count;
    }
};
int stat::count;

void main()
{
   clrscr();
   stat obj1,obj2;

   obj1.showcount();
   obj1.showcode();
   obj2.showcount();
   obj2.showcode();
   getch();
}

Output: 
Count Objects: 2
Object Number is: 1
Count Objects: 2
Object Number is: 2

Static Member Function:

A member function which is declared as a static has the following properties:
i.                    A static function can have access to only other static members(functions or variables) declared in same class.
ii.                  A static member function can be called using the class name(instead of its objects).
Class_name::function_name;

For example:               class test
                                    {
                                    Static void showcount(void)
{
----------
}
}
Test::showcount();
----------

Friend function:
friend function for a class is used in object-oriented programming to allow access to private data in the class from the outside. Normally, a function that is not a member of a class cannot access such information; neither can an external class. Occasionally, such access will be advantageous for the programmer. Under these circumstances, the function or external class can be declared as a friend of the class using the friend keyword.
A friend function is declared by the class that is granting access. Friend declaration can be placed anywhere in the class declaration. It is not affected by the access control keywords.
A similar concept is that of friend class.
A friend function of a class is not a member function of the class, but a friend function has access to the private members.
A friend function of a class is an ordinary function except that it access to the private members of objects of that class. For this we just made a function friend by using a keyword "friend" before the function declaration.
Syntax:
Class ABC
{
……………
Public:
…………..
Friend void xyz(void);
};
characteristics of friend functions: 
i.              A friend function is not in the scope of the class n which it has been declared as friend.
ii.             It cannot be called using the object of that class.
iii.            It can be invoked like a normal function without any object.
iv.            Unlike member functions, it cannot use the member names directly.
v.             It can be declared in public or private part without affecting its meaning.

#include<iostream.h>
class  base
{
    int val1,val2;
   public:
    void get()
    {
       cout<<"Enter two values:";
       cin>>val1>>val2;
    }
    friend float mean(base ob);
};
float mean(base ob)
{
   return float(ob.val1+ob.val2)/2;
}
void main()
{
    clrscr();
    base obj;
    obj.get();
    cout<<"\n Mean value is : "<<mean(obj);
    getch();
}          

Output:

Enter two values: 10, 20
Mean Value is: 15

Array of Object:
We can have array of variables that are of type class.such variables are called array of objects.
For example:
Class employee
{
………………
};
Employee manager[5];//array of manager
Employee worker[50];//array of worker;
Constructor:-
     A constructor is a special member function whose task is to initialize the Object of its class.
  • It is special because its name is the same as class name.
  • The constructor is involved object of its associated class is created.
  • It is called constructor because it constructs the values of data members of the class.
Characteristics or Rules :-
  1. Constructor name is must be same as that of its class name.
  2. It is declared with no return type.
  3. It may not be static or virtual.
  4. It should be public only in rare circumstances it can be private.
  5. They have default arguments.
  6. They can not be inherited from derived.

Syntax :-
           Class user
                 {
                 Private :
                 ---------
                 ---------
                 Public :
                         User ( ) ;         //  constructor  declared
                          -----------
                          --------------
                 };
                 User ; ; user ( ) //  constructor defined
                 {
                 ----------
                -----------
                 }

e.g.
                class employee
                {
                Private ;
                      Char name [ 20 ];
                      Int  ecode ;
                      Char  address [20];
               Public;
                      Employee ( )  // constructor declared
                      Void getdata ();
                      Void display();
              };
Employee ; ; employee (); // constructor defined
-----------
----------
}


Types of constructor :-
 Parameterised Constructor  :-
It is possible in c++ to pass arguments to the constructor function when  the objects are created . These constructor are called as parameterized constructor.
The constructor integer () may be modified to take arguments as shown below :-
                             Class integer
                             {    int m, n;
                                   Public;
                                        Integer (int x , int y);  // Parameterised constructor
                                 -----------
                              ------------------
                               };
                             Integer ;; integer ( int x, int y)
                           }
We must pass the initial values as arguments to the constructors function when object is created.   Integer ob = integer (0,100);        // explicit call.
 Default constructors :-
A constructors that accept no parameter is called default constructors.
The default constructors ia a special member functions which is invoked by c++ compiler without any arguments for initializing object of class.
Copy constructor:-
Copy constructor are always used when compiler has to create temporary object of same class object.
Initialization of object by other object of same class.
State object as by value parameter of function.
Syntax
   Class_name ;;class_name (class_name &ptr)
Multiple constructor in a class:-
C++  permits to use more than one constructor in same class.
e.g ;                 class intger
                        {
                           Int m, n;
                        Public;
                            Integer()   // default constructor
                            {  m=0;
                                 n=0;
                            }
                            Integer(int a, int b)  // parameterized constructor
                             {
                             m=i.m;
                              n =i.n;
                              }
                       };
Destructor  :-
As name implies  destructor is used to destroy  the have been created by the constructor
Like constructor the destructor is a member function whose name is same as class name but it is proceeded by (~) filed.
e.g;       destructor for the class integer can be defined as
         ~ integer ()
         {
          }
A destructor never takes any arguments
 It is good practice to declare destructor in a program since it release memory space for future use.
New is used for allocate memory in constructor &
Delete is used for free memory.
#include<iostream.h>
#include<conio.h>

Class ratio
{
Public;  ratio()
{
cout<<”now x is alive’;
{     
cout<<”program end “;
Cout<<”obj. is born”;
}
~ratio()
{
Cout<<”object  dies”;
}
};

void main ()
{
ratio x;
cout<<”now x is alive”;
cout<<”program end”;
getch();
}

Type Conversion:
When Constants & variables of different types are mixed in an expression,compiler applies rules of automatic type conversion.
The assignment operator also causes automatic type conversion.
The type of data on right of an assignment operator is automatically converted to the type of variable on left.
Eg.       int m;
            float x=3.14;
            m=x;
Convert x to an integer before it is assigned to m.The fractional part is truncated.
Type conversion is automatically for built in data type.
Consider,         obj=obj1+obj2;
Where ob.ob1,ob2 are objects of type class.
When objects are same class type then operations are carried out.But if one of the operand is object & other is built in data type variable,compiler gives error.
Compiler does not support automatic type conversion,for user defined datatypes.
  1. Built in type to class type
  2. Class type to Built in type
  3. Conversion from one class type to another class type.

1)    Built in type to class type
The constructor can be used for default type conversion from argument type to the constructors class type.
Example:
Let us consider example of converting int type to a class type
      Class itoc
      {
                  int no;
      pubic:
                  itoc(int x)
                  {
                  no=x;
                  }
Void putdata()
{
Cout<<”Number=”<<no;
}
      };
Void main()
{
Int n;
Cout<<”Enter value of n”;
Cin>>n;
Itoc obj=n;
Obj.putdata();
}

this conversion is accomplish by using overloaded = operator.


2)    Class to Basic type:
C++ allows us to define overloaded casting operator that could be used to convert class type data to basic type.
The  general form of an overloaded casting operator function is:
Syntax:
      Operator type name()
      {
      --------(function statement)
      }
This function converts a class type data to type name.
For example:
Class ctoi
{
Int no;
Public:
      Ctoi (){
no=0;
}
Operator int ()
{
Return no*no;
}
Void getdata()
{
Cout<<”Enter number=”;
Cin>>no;
}
};
Void main()
{
Ctoi obj
Obj.getdata();
Int sq=obj;
Cout<<”square=”<<sq;
}
The conversion function must satisfy following conditions.
a)      It must be a class member
b)      It must not specify a return value
c)     It must not have any argument

3)    One class to another class type:
Consider, objx = objy;
Objx is an object of class x& objy  is a n object of class y.class y type data is converted to class x type data & converted value is assigned to the objx. Here y is source class & x is destination class.
Such conversions can be carried out by constructor or a conversion function.
The function
                              Operator type name()
It converts the class object of which it is a member to type name.

For ex.
class one
{
int x1;
public:
      one(){}
      one(int x)
      {
      x1=x;
      }
      int getval()
      {return x1;
      }
      void putval()
      {cout<<"x1="<<x1<<endl;
      }
};
class two
{
int x2;
public:
      two(){}
      two(int y)
      {
      x2=y;
      }
      operator one(){
      one temp;
      temp.getval()=x2*x2;
      return temp;
      }
      void putdata()
      {cout<<"x2="<<x2<<endl;
      }
};
void main()
{
one obj1(30);
two(obj2(40);
cout<<"Before conversion";
obj1.putval();
obj2.putdata();
obj1=obj2;
cout<<"After conversion";
obj1.putval();
obj2.putdata();
}




Inheritance :-
1.      Reusability is another important feature.
2.      It is always nice if we would reuse something that already exist.
3.      Inheritance is another most imp feature of oop.
4.      Inheritance support reusability of existing code.
5.      This is done by creating new classes reusing properties of existing one.

Def :- The mechanism of deriving a new class from old class is called inheritance.
Old class is base class .
New class is derived class.

Single inheritance
    A derived class with only one base is called as single inheritance
. Multiple inheritance :-
A derived class with several base class is called as multiple inheritance.
Hierarchical inheritance:-
When more than one class is derived from one base it is called as hierarchical inheritance.
Multilevel  inheritance :-
The mechanism of deriving a class from another  derived class is  known multiple inheritance
Hybrid inheritance:-
As the name suggest we need to apply more than one inheritance is known as hybrid inheritance.
Defining derived  class:-
  A derived class can be defined specifying its relation with base in addition to its own details.


 Syntax:-
                Class derived_class_name: visibility_mode   base_class_name
                {
                 ------------     // member of derived class.
                 };
The colon indicates that derived class name is derived from base class name.
The visibility mode is optional & it present may be either private or public.
Default visibility mode is private.
Example;
               Class abc ; private   xyz      //  private  derivation
                {
                Members of abc
                 };
                 Class abc       :public xyz      // public  derivation
                  {
                 Members of abc
                };
                  Class abc :  xyz           // private derivation by default.
                {
                  Members of abc
                }
When a base class is privately inherited by derived class public member of base class become private members of derived class, therefore public member of base class can only be accessed by member function of derived class.No member of base class accessible to the object of derived class.
When base class is publicly inherited, ‘public members ‘ of base class become public member of derived class& therefore they are accessible to the object of derived class.
In both the cases, private members of base class will never become members of its derived class.

Single inheritance:- 

#include1<iostream.h>
#include<conio.h>
class student
{
public:
int m1,rollno;
void get();
void display();
};
class stud:public student
{
int m2,m3;
int total;
float avg;
public:
void get1();
void grade();
void show();
};

void student::get()
{
cout<<"Enter Roll No=";
cin>>rollno;
cout<<"Enter Marks in Subject 1=";
cin>>m1;
}
void student::display()
{
cout<<"\nRoll No="<<rollno;
cout<<"\nMarks in Subject 1="<<m1;
}
void stud::get1()
{
get();
//int m1=get_m1();
cout<<"Enter Marks in Subject 2=";
cin>>m2;
cout<<"Enter Marks in Subject 3=";
cin>>m3;
total=m1+m2+m3;
avg=(total)/3;
}
void stud::show()
{
display();
cout<<"\nMarks in Subject 2="<<m2;
cout<<"\nMarks in Subject 3="<<m3;
cout<<"\nTotal=" <<total;
cout<<"\nAverage="<<avg;
cout<<"\n Grade=";
}

void stud::grade()
{
if(avg>70)
cout<<"Distinction";
else if((avg>60)&&(avg<70))
cout<<"First Class";
else if((avg>50)&&(avg<60))
cout<<"Second Class";
else if((avg>35)&&(avg<50))
cout<<"Pass Class";
else
cout<<"Fail";
}
void main()
{
clrscr();
stud s;
s.get1();
s.show();
s.grade();
getch();
}
OUTPUT:
Enter Roll No=11
Enter Marks in Subject 1=55
Enter Marks in Subject 2=66
Enter Marks in Subject 3=88
Roll No=11
Marks in Subject 1=55
Marks in Subject 2=66
Marks in Subject 3=88
Total=209
Average=69
                                        
Multiple inheritance:-

  A class can inherit the attributes of two or more classes as shown 


Syntax of derived class  with multiple base class is as follows :-
           Class C :  visibility A , visibility B, ……….
            {
             ----------------
            ( body of C)
           --------------
            };
 Multiple inheritance allows us to combine several features of existing classes as a starting  point for defining new classes.                                                                                                                                                  
It is like child inheriting physical appearance of features of one parent & intelligence of another.

Multilevel inheritance :-When a class is derived from another derived class is called multilevel inheritance

A CLASS WITH MULTILEVEL INHERITANCE IC DECLARED AS FOLLOWS :-
                     class A                 //base class
                     {
                      -----
                     }
                 Class B; public A      // Derived from A
                     {
                     ----------
                     }
                 Class C; public B          // derived from B
                     {
                      ----------
                     }
 
     THIS PROCESS CAN BE EXTENDED BY ANY NUMBER OF LEVELS.

Virtual Base class:
In some situation all the three kinds of inheritance,namely multiple ,multilevel  & hierarchical inheritance are involved.the ‘child’ has two direct base ‘parent 1’and ‘parent2’ which themselves has a common base class ‘grand parent’.
Here child would have duplicate sets of the member inherited from ‘grand parent’ via parent1 & again parent2. This introduces ambiguity. It can be avoided.
The duplication of inherited members due to these multiple paths can be avoided by making the common base class as virtual base class.
Class A
{
------
------
};
Class B1:virtual public A              //Parent 1
{
------
------
};
Class B2:public virtual A              //Parent 2
{
------
------
};
Class C:public B1,public B2
{
------
------
};


Polymorphism:
Polymorphism  is another feature of O.O.P.
Polymorphism stands for many forms.
Ability to take more than one form is called Polymorphism.
The concept of Polymorphism is already implemented by
  • Function overloading
  • Operator overloading
Function overloading means same function name with different parameter list.
Function would perform different operation depending on argument list in the function call.
Eg.overloaded add() function handle different type of data.
Void add(int a,int b);
Void add(int a,int b,int c);
This information is known to compiler at compile time & therefore compiler is able to select appropriate function for a particular call at compile time.This is called early binding or static binding or static linking.
This is also known as compile time Polymorphism.
Early binding means that an object is bound to its function call at compile time.
Now consider a situation where the function name & prototype is the same in both the base derived class.
                   Class A
                        {
                        int x;
                        Public:
                        Void show()
                        {----}
                        };
                        Class B:public A
                        {
                        int y;
                        Public:
                        Void show()
                        {----}
                        };
Here show() function is used to print values of object of both the classes A & B.The prototype of show() is same in both the places,the function is not overloaded & therefore static binding does not apply.


Run time Polymorphism:

The appropriate member function can be selected at run time & it is known as Run time Polymorphism.
C++ supports a mechanism known as virtual function to achieve Run time Polymorphism.
Pointer To Object:

A pointer can point to an object created by class .
Eg.item x;
Where item is class & x is object defined to be of type item.
item *ptr;
ptr is pointer of type item.
Object pointer are useful in creating objects at run time.
We can also used object pointer to access the public members of an object.
item *ptr=&x;
we can refer to member functions of item in two ways,one by using dot operator & the object pointer.
Eg.       x.getdata(100,75.5);
            x.show();
are equivalent to
            ptr-> getdata(100,75.5);
            ptr-> show();
Also,*ptr is an alias of x,we can write,
            (*ptr).show();
The parenthesis are necessary because the dot operator has higher precedence that *.
We can create array of objects using pointer & new operator as:
item *ptr=new item;
We can create array of objects using pointers:
item *ptr=new item[10];         //array of 10 objects
here memory space for an array of 10 objects of item is created.
This pointer:
Keywors this represent a pointer that points to the object for which this function was called.
Eg.A.max();
Will set the pointer this to address of obj A.

Pointer to derived class:
If B is base class & D is derived class from B,then a pointer declared as a pointer to B can also be a pointer to D.
            B *ptr;
            B b;
            D d;
            Ptr=&b;
            Ptr=&d;
Using ptr we can access only those members inherited from B & not those members that originally belongs to D.

Virtual Function:
When we use same function name in both base class & derived class,the function in base class is declared as virtual preceding its normal declaration.
When a function is made virtual,C++ determines which function to use at run time based on type of object pointed to by base pointer.
By making base pointer to point different objects,we can execute different versions of the virtual function.
Program for virtual function
#include<iostream.h>
#include<conio.h>
class person // base class
{
public:
virtual void print() //virtaual function
{
cout<<"\n name of the person:"<<"Bob"<<endl;
}
};
class student :public person //derived class
{
public:
void print()
{
cout<<"\n name of student:"<<"Tom"<<endl;
}
};
void main()
{
clrscr();
person X;
person *p;
cout<<"\np points to instance X"<<endl;
p=&X; //pointer to base
p->print();
cout<<"\np points to instance Y"<<endl;
student Y;
p=&Y;
p->print();
getch();
}
OUTPUT:
p points to instance X
name of the person:Bob
p points to instance Y
name of student:Tom
RULES:
1.      The virtual function must be member of a class
2.      They can not be static members
3.      They are accessed by using object pointers
4.      A virtual function can be a friend of another class .
5.      A virtual function in base class must be defined even though it may not be used.
6.      The prototype of the base class version of virtual function & all derived class version must be identical.If two functions have different prototypes,then C++ considers them as overloaded functions.
7.      We can not have virtual constructor but we can have virtual destructor.
8.      We can not use pointer to derived class to access an object of base class.
9.      When base pointer points to derived class.the incrementation & decrementation is only relative to its base type.
10.  Virtual function are defined in base class,then need not be redeined in derived class.
11.  Virtual function supports runtime polymorphism.
12.  Empty virtual function defined in the base class is called as pure virtual function.
Eg.virtual void display(void)=0;

Pure virtual function:
Empty virtual function defined in the base class is called as pure virtual function. A virtual function declared in a base class that has no definition relative to the base class is pure virtual function.In such cases,the compiler requires each derived class to either define the function or redeclare it as pure virtual function.
Eg.virtual void display(void)=0;
Is pure virtual function.
A class containing pure virtual function called an abstract base class.


DATA FILE HANDLING IN C++
Files (Streams)
Files are used to store data in a relatively permanent form, on floppy disk, hard disk, tape or other form of secondary storage. Files can hold huge amounts of data if need be. Ordinary variables (even records and arrays) are kept in main memory which is temporary and rather limited in size. The following is a comparison of the two types of storage:
C++ STREAMS
v  A Stream is a general name given to flow of data.
v  Different streams are used to represent different kinds of  data flow.
Each stream is associated with a particular class, which contains member functions and definitions for dealing with that particular kind of data flow

The following classes in C++ have access to file input and output functions:
    • ifstream
    • ofstream
    • fstream

DIFFERENT FILE OPERATIONS
v  OPENING A FILE
v  CLOSING A FILE
v  READING FROM A FILE
v  WRITING ON A FILE
v  CHECKING FOR END OF FILE
OPENING A FILE
1. By using the  CONSTRUCTOR of the                            stream class.
            ifstream transaction(“sales.dly”);
            ofstream result(“result.02”);
2. By using the open() function of the stream class
            ifstream transaction;
            transaction.open(“sales.dly”);
File Mode Parameters
PARAMETER                              MEANING
*      Ios::app                       Append to end-of file
*      Ios::ate                        goto end of file on opening
*      Ios::binary                  binary file
*      Ios::in                          Open existing file for reading
*      Ios::nocreate                open fails if file doesn’t exist
*      Ios::noreplace  open fails if file already exists
*      Ios::out                        creates new file for writing on
*      Ios::trunc                     Deletes contents if it exists
The mode can combine two or more modes using bit wise or ( | )
Checking For Successful File Opening
ifstream transaction(“sales.dly”);
      if (transcation == NULL)
      {
                  cout<<“unable to open sales.dly”;
                  cin.get(); // waits for the operator to press any key
                  exit(1);
      }
Closing of File
Stream_name.close();
      e.g., transaction.close();
Types of Files
*      The two basic types are
                    text and
        binary.
*      A text file consists of readable characters separated into lines by newline characters. (On most PCs, the newline character is actually represented by the two-character sequence of carriage return (ASCII 13), line feed (ASCII 10).
*      A binary file stores data to disk in the same form in which it is represented in main memory.
*       If you ever try to edit a binary file containing numbers you will see that the numbers appear as nonsense characters. Not having to translate numbers into a readable form makes binary files somewhat more efficient.
*      Binary files also do not normally use anything to separate the data into lines. Such a file is just a stream of data with nothing in particular to separate components.
*      When using a binary file we write whole record data to the file at once. When using a text file, we write out separately each of the pieces of data about a given record.
*      The text file will be readable by an editor, but the numbers in the binary file will not be readable in this way.
*      The programs to create the data files will differ in how they open the file and in how they write to the file.
Types of File Access
Sequential access. With this type of file access one must read the data in order, much like with a tape, whether the data is really stored on tape or not.
 
Random access
(or direct access). This type of file access lets you jump to any location in the file, then to any other, etc., all in a reasonable amount of time.
File pointers:
*      By default reading pointer is set at  the beginning and writing pointer is set at the end (when you open file in ios::app mode)
*      There are times when you must take control of the file pointers yourself so that you can read from and write to an arbitrary location in the file.
Functions associated with file pointers :
  • The seekg() and tellg() functions allow you to set and examine the get pointer.
  • The seekp() and tellp() functions allow you to set and examine the put pointer.

Question Bank
C++:

1.      Enlist the basic data types in c++ with  size of data in terms of bytes for each.
2.      Write any six main advantages & features of object oriented language.
3.      Explain following terms:
a)      Insertion operator  b) Extraction operator c) Scope resolution operator
4.      Write a declaration of each of the following.
a)      An array ‘a’ of 6 doubles
b)      An array ‘a’ of 6 pointers to double
c)      A pointer ‘a’ to an array of 6 doubles
d)     An array ‘a’ of 2*2 matrix with index size 20 and 30 respectively.
5.      What is pointer? Explain two methods of pointer call as call-by-value and call-by-value and call-by-reference?
  1. Differentiate between Traditional Procedural Programming Approach and Object Oriented Programming Approach.
  2. Basic concepts of object oriented programming.
  3. Features of OOPs.
  4. Advantages of OOPs.
10.  What is Class? Explain general form of class declaration.
  1. Write a note on following with example?
a. Outside the class definition            b. Inside the class definition
12.  What is Operator function? Describe syntax of an Operator Function. Explain difference between Operation Function as a Member function and as a Friend function.
13.  What is friend function? Explain with their characteristics & suitable example.
14.  What is operator overloading? Explain with its characteristics.
15.  Explain in brief the three special characteristics of static Data Member in a class.
16.  What is pointer? What are advantages of pointer in C++?
17.  What is constructor and destructor? State difference between them? State six characteristics of Constructor.
18.  Define the terms:
      a. Default constructor b. Parameterized constructor  c. Copy constructor
19.  What is Virtual function? Explain different rules for the virtual function.
20.  What is operator overloading? State three steps involved in the process of overloading.
21.  What is polymorphism? How to achieve compile time & runtime polymorphism? Explain in brief.
22.  Explain following oops concepts:
                                            i.            Inheritance
                                          ii.            Polymorphism
                                        iii.            Data Abstraction
23.  What is inheritance? Explain in brief the following types of inheritance.
a)Single Inheritance                            b)Multiple Inheritance           
c)Multilevel Inheritance                      d)Hybrid Inheritance 
e)Hierarchical Inheritance.

24.   What are classes in C++ for file stream operation? How do you open & close files in C++? Explain any four file modes in C++.

C++ Programs:
1.      Write a C++ program to accept a number and test whether it is prime or not.
2.      Write a C++ program to read a set of 10 nos & store it as an one dimensional array; again read a number ‘d’ ans check whether the number ‘d’ is present in array, if it is so, print out how many times the number ‘d’ is repeated in the array.
  1. Write a C++ program to find Greatest common deviser(GCD)of two natural numbers..
  2. Write a C++ program for sum of digits of given integers.
                                                              i.      (For eg.n=123=1+2+3=6)
5.      Write a C++ program to accept a set of 10 numbers & print the numbers using pointers.
6.      WAP in C++ that Will read a line of text & count the number of words in a text.
7.      Write the following power() function in C++ that returns x raised to the power n, where n can be any integer,double power (double x,int p);use algorithm that would compute x20 by multiplying 1 by x20 times.
8.      WAP in C++ to sort of 10 float numbers in descending order by using Bubble sort method.
9.      Implement a class convert to convert degree from Celsius to Fahrenheit.
10.  Write a C++ program to find factorial of given number inputed during program execution.
11.  Write a C++ program to find a smallest of four given numbers using min() function to return the smallest of four given integer, int min(int, int, int, int).















No comments:

Post a Comment