Saturday, 31 March 2018

Static Member Function

Member function may also be declared static by prefixing the static keyword in the function definition header.

A static member function can have access to only other static members declared in the same class.

A static member function can be called by using its class name.
  class_name::function_name( );

A static member function can not be virtual.

There should not be member function does not have 'this' pointer.

Write a program to demonstrate static member function.

#include<iostream.h>
#include<conio.h>
class test
{
int code;
static int count;
public:
void setdata( )
{
 code=++count;
}
void show( )
{
 cout<<"\n\n\tObject Number--->"<<code<<endl;
}
static void showcount( )
{
 cout<<"\n\n\tCount is--->"<<count<<endl;
}
};
int test::count;
void main( )
{
test t1,t2,t3;
clrscr( );
t1.setdata( );
t2.setdata( );
test::showcount( );
t3.setdata( );
test::showcount( );
t1.show( );
t2.show( );
t3.show( );
getch( );


Output:-
    Count is--->2
    Count is--->3
    Object Number--->1
    Object Number--->2
    Object Number--->3

Program Documentation

What is Documentation ?
  
Documentation consists of instructions for using a computer device of program.
  
Documentation can appear in a variety of forms, the most common being manuals.
  
When you buy a computer product (hardware or software), it almost always comes with one or more manuals that describe how to install and operate the product.
  
In addition, many software products include an online version of the documentation that you can display on your screen or print out on a printer.
  
A special type of online documentation is a help system, which has the documentation embedded into the program.

Documentation is often divided into the following categories

1) Installation : Describes how to install a program or device but not now to use it.
2) Reference : Detailed descriptions of particular items presented in alphabetical order. Reference documentation is designed for people who are already somewhat familiar with the product but need remainders or very specific information about a particular topic.
3) Tutorial : teaches a user how to use the product. Tutorials move at a slower pace than reference manuals and generally contain less detail.

Need for Documentation
  A software cannot be considered to be complete until it is properly documented. So proper documentation of software is necessary due to the following reasons.

More documentation means easier usage. As soon as a user gets stuck trying to get a program feature to work, he or she starts to read that program's documentation. Therefore, creating well-structured and well-written documentation will make it easy for the user to get that feature to work.

It makes program or software is easy to maintenance.

A well documented software is easy ti modify and maintain in the future.

It is easier to understand the logic of a program  from the documented records rather than its code.

Flowcharts or comments used within the programs are very helpful in understanding the functionality of the whole program. 

Documented records are quite helpful in restarting a software project that was postponed due to some reason or the other.

The job need not be started from scratch and the old ideas may still be easily recapitulated which saves lot of time and avoids duplication of work.(Reusability).

In general the following aspects of a program or project should be documented

1) Basic usage is mostly covered in a man page.
2) More advanced usage can be achieved by giving options in the documentation and giving examples on how to use them (take the very good Apache documentation for example).
3) Source code, of course, because somebody may want to add features to the program.
4) Example of usage (what input to give and expected output) to supply a working basic configuration file and document it heavily.
5) Installation of the program, because not all program work with easy ways.

Forms of Documentation
  The three commonly used forms for documenting software are-
Comments
  Comments can be useful for
  1. Describing an element
  2. Adding remarks and lists
  3. Describing parameters
  4. Describing methods/properties
  5. Providing examples
  6. Compiling the code.

System Manual
  A document which is used to maintain all the system details and its usage is a system manual. It consist of 

 1. The objectives of developing the software and its usefulness to various categories of users.
 2. Specifies program names along with their description and purpose.
 3. Detailed system flow charts cross-referenced to the listing.
 4. A source listing of all programs together with full details of any modifications made since.
 5. Specimen of all input forms and printed output records.

User Manual

 A document which is used by the user for understanding easy use(how to use) of any product is a user manual. It consists of-

 1. Operational details of each program.
 2. Loading and unloading procedures.
 3. Starting, running, and terminating procedures.
 4. A description and example of any control statement that may be used.
 5. List of errors condition with explanations for their re-entry into the system.
 6. List of program to be executed before and after execution of each program.

Friday, 30 March 2018

Static Data Members

To create a static data member only you have to proceed a member variables declaration with static keyword.

All static variables are automatically to zero value , when the first object of the class is created. No other initialization is permitted.

Only one copy of static data member is created for the entire class and is shared by the objects of that class.

Since static variables are associated with the class itself rather than object called as class variables.

static data member is visible only within the class but lifetime is entire program.

The type and scope of each static data member must be redefined outside the class definition because static data member are stored separately rather than as a part of object.


Syntax:

Data_type classname :: static_variable_name;
            The static variable must be declared in a class with a keyword static.

Write a Program to count the no of objects using static data member.

#include<iostream.h>
#include<conio.h>
class item
{
static int count;
public:
void getdata( )
{
count++;
}
void display( )
{
cout<<"\n\n\tNo of object count is--->"<<count;
}
};
int item::count;
void main( )
{
item x1,y1,z1;
x1.getdata( );
y1.getdata( );
z1.getdata( );
cout<<"\n\n\tAfter Reading Data is--->";
x1.display( );
y1.display( );
z1.display( );
getch( );
}


Output:-
    After Reading Data is--->
    No of object count is--->3
    No of object count is--->3
    No of object count is--->3

Destructor

A destructor is a special member function which is used to destroy the objects which has been created by constructor.

Name of the constructor is same as the class name.
Destructor is preceded by tilde symbol(~)

Ex. For the class Integer , Destructor is
   ~Integer( )
      {
      
     }


Destructor should be declared in a public section only.

It is good practice to declare destructor in a program since it releases memory for future use.

Destructor is invoked implicitly by compiler when exit from the scope of the object to clean up the storage that is no longer accessible.

Destructor neither take any argument nor return any value.

#include<conio.h>
#include<iostream.h>
int count=0;
class alpha
{
public:
alpha( )
{
   count++;
   cout<<"\n\tNo of object created--->"<<count;
}
~alpha( )
{
   cout<<"No of object destroyed --->"<<count;
   count--;
 }
};
void main( )
{
 clrscr( );
  {
  cout<<"\n\tEnter into main function";
  alpha a1,a2,a3,a4;
 }
{
 cout<<"\n\tEnter Block 1";
 alpha a5;
}
{
cout<<"\n\tEnter Block 2";
 alpha a6;
}
cout<<"\n\tRe Enter main";
}
getch( );
}


Output:-
  Enter into main function
  No of object created--->1
  No of object created--->2
  No of object created--->3
  No of object created--->4
  Enter Block 1
  No of object created--->5
  No of object destroyed --->5
  Enter Block2
  No of object created--->5
  No of object destroyed --->5
  Re Enter main
  No of object destroyed --->4
  No of object destroyed --->3
  No of object destroyed --->2
  No of object destroyed --->1

Constructor with default arguments

It is possible to define constructor with default arguments.

Default argument must be trailing arguments.

Default argument of the constructor can be overrides by sending the values from calling function.

Let consider 
      Complex(float real, float imag=0);
  The Default value of the argument imag is zero.

The Statement Complex c(2.0);
  Will assign 2.0 to real and 0(zero) to imag.

The Statement Complex c(2.0,3.0);
  Assigns 2.0 to real and 3.0 to imag.

In Such a way when actual parameters if specified overrides the default values.

Ex:-   Declare a class 's1' having data members principle, rate_of_int and no_of_yrs. The constructor will have default values for rate_of_int as 11.5%. Accept the data for two objects and display simple interest for each object.

#include<conio.h>
#include<iostream.h>
class S1
{
float principle,si,rate_of_int,no_of_yrs;
public:
S1(float p, float n_o_y,float r_o_i=11.5)
{
   principle=p;
   no_of_yrs=n_o_y;
   rate_of_int=r_o_i;
}
void calculate( )
{
si=(principle*rate_of_int*no_of_yrs)/100;
}
void display( )
{
cout<<"\n\tSimple INterest is --->"<<si;
}
};
void main( )
{
S1 s1(7800.0f,5.0f);
S1 s2(8500.0f,8.0f);
S1 s3(5000.0f,6,12.2f);
clrscr( );
s1.calculate( );
s2.calculate( );
s3.calculate( );
s1.display( );
s2.display( );
s3.display( );
getch( );
}

Output:-
     Simple INterest is --->4485
     Simple INterest is --->7820
     Simple INterest is --->3660

Constructor Overloading

Cpp permits to use the constructor like default, copy or parameterized constructor in the same class.

Constructor overloading means using multiple constructor in the class having different no og arguments and different types of argument.

Ex:

class abc
{
int m,n;
public:
abc( )
{
 m=0;
 n=0;
}
abc(int a, int b)
 {
  m=1;
  n=b;
 }
abc(abc &k)
 {
  m=k.m;
  n=k.n;
 }
};


Above class declares three constructor for the abc object.
→ The Statement abc a1;

Invokes the first constructor and set both m and n of a1 to zero.
→ The Statement abc a2(20,40);

Invokes the second constructor and set both m and n of a2 to 20 and 40 respectively.
→ The Statement abc a3(a2);

Invokes the third constructor and copies the value of data member of a2 to data member of a3.

#include<conio.h>
#include<iostream.h>
class abc
{
int m,n;
public:
abc( )
{
   m=0;
   n=0;
}
abc(int a, int b)
{
   m=a;
   n=b;
}
abc(abc &k)
{
m=k.m;
n=k.n;
}
void display( )
{
  cout<<"\n\tValue of m is--->"<<m;
  cout<<"\n\tValue of n is--->"<<n;
 }
};
void main( )
{
abc a1;
abc a2(20,40);
abc a3(a2);
clrscr( );
a1.display( );
a2.display( );
a3.display( );
getch( );
}


Output:-
    Value of m is--->0
    Value of n is--->0
    Value of m is--->20
    Value of n is--->40
    Value of m is--->20
    Value of n is--->40

Constructor

A constructor is a member function whose task is to allocate the memory and initialize the object of the class.

It's special member function because its name and class name is name.

The constructor in invoked whenever an object of its associated class is created.

It is called as constructor because its construct the value of data member of the class.

Constructor function should be declared in public section.

Constructor do not have return , not even void so it can not return any type of value.

Constructor function can not be inherited but derived class can the base class constructor.

Constructor can not have default argument.

Constructor can not be virtual.

Constructor make implicit calls to the operators new and delete when memory allocation is required.




When you declare the object as follows
time t1;

Then object will get initialized automatically that is data members hours and minutes will be initialized to a value zero.

Therefore there is no need to write any statement to invoke the constructor function.

Different Types of Constructor
  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
  4. Dynamic Constructor

Default Constructor :-
 A constructor that accepts no arguments is called as default constructor.

The default constructor for class Emp is
   Emp::Emp( )

 If no such a constructor is defined then compiler supplies a default constructor.

Statement Emp x;
 Invokes default constructor while creating object 'x';

Ex:
 #include<conio.h>
 #include<iosteam.h>
 class sample
 {
 int k;
 public:
 sample( )
 {
  k=0;
  }
  void display( )
  {
  cout<<"\n\tValue of k is --->"<<k;
   }
  };
  void main( )
   {
    sample obj1;
    clrscr( );
    obj1.display( );
     getch( );
    }

Output:-
   Value of k is --->0

Parameterized Constructor :

 A constructor with arguments / parameters is called as parameterized constructor.
 As we know that each object has separate memory for data members sometime.It becomes necessary to initialize each object with different values when they are created.

Then these arguments help to initialize an object when it is created.
 To create parameterized constructor, simply add parameters to it as you add to any function.

Write a program to declare class student having data members name and percentage. Write a constructor to initialize these data members and display them.

#include<iostream.h>
#include<conio.h>
#include<string.h>
class student
{
 private:
 char name[20];
 float per;
 public:
 student(char n[20],float p)
 {
  strcpy(name,n)
  per=p;
  }
  void display( )
  {
   cout<<"\n\tName is --->"<<name;
   cout<<"\n\tPercentage is --->"<<per;
   }
  };
 void main( )
  {
   student s1("Irawen",99.92);
   s1.display( );
   getch( );
 }

Output:-
   Name is --->Irawen
   Percentage is --->99.92

Copy Constructor 
   A constructor can accept a reference to its own class as a parameter which is called as copy constructor.
   A copy constructor takes a reference to an object of the same class as itself as an argument.
   A copy constructor can be used to declare and initialize an object of another object.

Ex:
 Class Time
 {
 ..........
 public:
 Time(Time &t)  //Copy Constructor
  {
   }
 };
→ Time T2(T1);
      It define the object t2 and at the same time initialize it to have of t1.
→ Statements T2=T1;
      This will not invoke copy constructor.If T1 and T2 are the objects,this statement is legal and simply assigns the value of T1 and T2 member by member.

Write a program to implement copy constructor

#include<iostream.h>
#include<conio.h>
class code
{
 int id;
 public:
 code(int a)
 {
  id=a;
  }
  code(code &x)
  {
   id=x.id;
   }
   void display( )
   {
    cout<<"\t"<<id;
    }
   };
  void main( )
   {
    code A(100);
    code B(A);
    code C=A;
    clrscr( );
    cout<<"\n\t ID of A is --->";
    A.display( );
    cout<<"\n\t ID of B is --->";
    B.display( );
    cout<<\n\t ID of C is --->";
    C.display( );
     getch( );
   }

Output:-
   ID of A is --->100
   ID of B is --->100
   ID of C is --->100

Access Control In Classes OR Access Modifiers

Access specifiers in C++ class defines the access control rules. C++ has 3 new keywords introduced, namely,

1. public
2. private
3. protected

These access specifiers are used to set boundaries for availability of members of class be it data members of  members or member functions

Access specifiers in the program, are followed by a colon. You can use either one, two or all 3 specifiers in the same class to set different boundaries for different class members. They change the boundary for all the declarations that follow them.

Public
 Public, means all the class members declared under public will be available to everyone. The data members functions declared public can be accessed by other classes too.
  Hence there are chances that they might change them. So the key members must not be declared public.

Private
  Private keyword, means that no one can access the class members declared private outside that class. If someone tries to access the private member , they will get a compile time error. By default class variables and member functions are private.

  class PrivateAccess
  {
   private:    // private access specifier
   int x;       // Data Member Declaration
   void display( );  //Member Function declaration
   }

Protected
  Protected, is the last access specifier, and it is similar to private, it makes class member inaccessible outside the class. But they can be accessed by any subclass of that class.

 class ProtectedAccess
 {
   protected:    // protected access specifier
   int x;           // Data Member Declaration
   void display( );   // Member Function declaration
   }
  

Memory Allocation for objects

Memory for the object is allocated when they are declared and not when class is specified.Since all the objects belonging to the same class use the same member function, no separate space is allocated for functions when objects are created.

 But the space for data member are allocated for each object because separate memory locations for the objects are essential and each object can hold different values.



Thursday, 29 March 2018

Concept of API / Libraries

Application Programming Interface (API) is an interface in computer science that defines the ways by which an application program may request services from libraries and/ or operating system.It is a set of routines, protocols and tool for building software applications.
  
A good API makes it easier to develop a program by providing all the building blocks.
   
Although APIs are designed for programmers, they are ultimately good for users because they guarantee that all program using a common API will have similar interface. This makes it easier for users to learn new programs.

Concept of  'C' Library
   The C standard library consists of a set of sections of the ISO C standard which describe a collection of header files and library routines used to implement common operations, such as input/output and string handling, in the C programming language.

Following are some important header files :

   Stdio.h, which stands for "standard input/output header" , is the header in the C standard library that contains macro definitions, constant and declarations of functions and types used for various standard input and output operation.
   
   String.h is the header in the C standard library for the C programming language which contains macro definition, constant and declarations of functions and types used not only for string handling but also various memory handling functions; the name is thus something of a misnomer.

    Function declared in string.h are extremely popular, since as a part of the standard library, they are guaranteed to work on any platform which supports C.
  
    Math.h is a header files in the standard library of C programming language designed for basic mathematical operation. Most of the functions involve the use floating point numbers. C++ also implements these functions for compatibility reasons and declares them in the header cmath.

Debugging a Program for Syntax Errors and Logical Errors


Debugging a Program for Syntax Errors
As compared to logical errors, syntax errors are much easier to locate and correct because almost all language processor are designed to detect syntax errors automatically.

A single syntax error often cause multiple error messages to be generated by the language processor.

Removal of the syntax error will result in the removal of all associated error messages.

Debugging a Program for Logical Errors
  Logical errors are much more difficult to detect the syntax errors as computer does not produce any error message for such errors.
  
One or more following methods are commonly used to detect the logical errors :
      
Doing hand simulation of the program code :
 One approach is to take the printout of the source code of the program and go through its execution manually with the test data input that produced incorrect results.
       
Putting the print statement in the program code
Another approach is to put several print or write statements at appropriate locations in the program so that the values of different variables can be displayed to indicate intermediate computations results.

  Using a debugger :
    This is the most commonly used approach. Debugger is the software program the assist a programmer in following a program's execution step-by-step allowing him to display intermediate calculation results.
    
Using memory dump :
     This approach is used when the program "hang up" during a test run.

Testing a Program

For most programs, it is practically impossible to prove that the program is correct on all inputs.Instead, you must try to convince skeptics that it mostly works right, by testing the program on various inputs and documenting what you have done.

This documentation is called a test plan and you must provide one with each program.

The test plan describes how you intend to test your program, that is, which inputs you plan to test it on and why those are good choices.

The results of running a set of tests is a test log, which shows the results produced by the tests in the test plan. The log should demonstrate that each test produced the output predicted by the test plan.

Developing a Test Plan
  The programs written for this course will require you to test the execution of your programs on various sets of inputs to demonstrate program functionality. These input sets or test cases, will be of your own choosing, but the following guidelines should be followed :

        Input sets should be ordered logically, preferably in the same order as the code being tested.

        When there are only a few possible inputs, test them all.

        If your program does not handle certain inputs, the ASSUMPTIONS section of the program header must indicate precisely which inputs are not handled in the program.

Format for Program Test Document
  Test results must be submitted separately on paper, even if the program may be submitted on disk or electronically. The program test document should be organized as follows :
    1. Your name ( and the names of any people you work with).
    2. The name of the programming assignment (e.g., Program 1).
    3. Rationale behind chosen test cases(inputs). Note that you MUST include some justification for each test case, even if it is something as simple as testing the program on odd or even numbers.
    4. Printouts of output files for each separate input set (i.e., test logs).


Program Testing and Debugging

A software bug (or just "bug") is an error, flaw, mistake, failure, fault or "undocumented feature" in a computer program that prevents it from behaving as intended (e.g., producing an incorrect result).

Most bugs arise from mistakes and errors made by people in either a program's source code or its design and a few are caused by compilers producing incorrect code.

Formal Program Testing
                The software industry is primarily concern with logical errors and hidden run-time errors. Companies expend enormous effort to find the errors before the release. To fix a bug after the release cost a 100 times more; patches must be designed and ship out.Besides the customer are not very happy. So, there is the necessity of program testing before it goes to the end user.
   The industry is concerned with Verification and Validation :
               Validation or appropriate :
                  Techniques for insuring validation :
                         Inspection code at a high level
                         Have the user/customer test software
                         Requires good software specification

                Verification or correctness :
                         Is the program producing the correct answers ?
                         Techniques for insuring verification :
                              Code walk through of inspection
                              Testing

Testing
    Testing is the primary technique for the above two Vs :
        Testing uses input data and observes output.
             There may be additional output then in the final product.
             The evaluation may include more then just the correctness of the output.
             Testing can be at the component level or integrated level.

Debugging
   Debugging is a methodical process of finding and reducing the number of bugs or defects, in a computer program or a piece of electronic hardware thus making it behave as expected. Debugging tends to be harder when various subsystem are tightly coupled, as changes in one may cause bugs to emerge in another.

Difference between Testing and Debugging



Types of Program Errors
  There are three basic errors :
    1. Syntax/Compilation error
    2. Run-time exception error
    3. Logical error

Syntax / Compilation Error
   Error during compiling prevents getting a compiled code. Modern compilers indicate well the location of the error. Sometimes problems with delineators such as semicolons in C or brackets in C++.

Run-time Exception Error
  When you get an error message while running the compiled code. Java gives good error messages indicating the location of the error but that might not be the location of the actual error.Some languages, such as C seem to have only one type of error; segmentation fault or Fortran, index out of bounds.

Logical Error
  These errors are the hardest to correct or detect. The program "runs" but the output is not correct.
     
Tools for detecting and fixing logical error :
      1. Choose test cases well. Try to cover everything with small cases. Try one big case.
      2. Print intermediate value. Use a boolean variable to turn on and off debug printing.
      3. Walk though. Play computer in front of an audience (if you can) and suspect all code especially uncommitted code.

Logical errors generally occur at :
Loops : 
    Check the range of for loops and the boolean expression of while loop.
  
Ifs :
    Check complicated boolean expressions (more than one variables) and especially if you are using negation.

Defining Member Function

The Member function of the class can be defined in any one of the two places
 1. Inside the class definition
 2. Outside the class definition

Inside the class definition :
  Here actual function definition is included within class definition:

  Ex:
     Class class_name
  {
       Data Type datamember_1;
       Data Type datamember_2;
        .
        . 
        public:
        Return_type functionname_1(Actual Argument)
         {
          //Code of Function
         }
          .
          .
          .
          Return_type functionname_n(Actual Argument)
           {
             //Code of function
            }
     };

When a function defined inside the class, it is treated as an inline function.

Outside The class Definition :
    This is another way of defining member function. Here the member function declaration and definition is written separately i.e. function declaration is taken place inside the class and function definition is taken place outside the class.

Function definition outside the class uses scope resolution operator (::) which is used to tell the compiler the scope of the member function or tells that which function belongs to which class .


Syntax :

  class class_name
  {
     Datatype datamember_1;
     Datatype datamember_2;
     .
     .
     .
    Datatype datamember_n;
    public :
    returntype function (Argument list);    //Function Declaration
    .
    .
    .
};

returntype class_name :: function_name (Argument_list)
 {
   //Body of the Function
  }

Ex : Function Definition inside class
       
 WAP in cpp to create a class having name 'student' having members roll_no, name, age and display it on screen.

#include<iostream.h>
#include<conio.h>
class student
{
 private:
 int roll_no;
 char name[10];
 int age;
 public:
 void getdata( )
 {
  cout<<"\n\tEnter Roll no";
  cin>>roll_no;
  cout<<"\n\tEnter Name";
  cin>>name;
  cout<<"\n\tEnter Age";
  cin>>age;
  }
 void display( )
  {
    cout<<"\n\tRoll No is --->"<<roll_no;
    cout<<"\n\tName is --->"<<name;
    cout<<"\n\tAge is--->"<<age;
   }
};
void main( )
{
 student s1;
 clrscr( );
 s1.getdata( );
 s1.display( );
 getch( );
}

Output :-
 
Enter Roll no101  
  

  Enter NameIrawen
   
  Enter Age8

   Roll No is --->101
   Name is --->Irawen
   Age is--->8
      

Ex: Function definition outside class
     
#include<iostream.h>
#include<conio.h>
class student
{
 private:
 int roll_no;
 char name[10];
 int age;
 public:
 void getdata( );
 void display( );
};
  void student::getdata( )
 {
  cout<<"\n\tEnter Roll no";

  cin>>roll_no;
  cout<<"\n\tEnter Name";
  cin>>name;
  cout<<"\n\tEnter Age";
  cin>>age;
  }
  void student::display( ) 
{

    cout<<"\n\tRoll No is --->"<<roll_no;
    cout<<"\n\tName is --->"<<name;
    cout<<"\n\tAge is--->"<<age;
   }
};
void main( )
{
 student s1;
 clrscr( );
 s1.getdata( );
 s1.display( );
 getch( );
}


Output :-
  Enter Roll no101  
  

  Enter NameIrawen
   
  Enter Age8

   Roll No is --->101
   Name is --->Irawen
   Age is--->8
     

Wednesday, 28 March 2018

Classes and Objects

Class :

Class is a user defined data type which is a collection of data members and member function together.

Wrapping of data members and member function together in a single unit is called as class.

Data Members gives the information about object and member function gives the operation on the object or it describes the behavior of the object.

Class helps you for data abstraction as well as for the data encapsulation which gives the advantage of data hiding.

       Syntax of Class Definition:
       class classname
       {
              private:
              //variable declaration;
              public:
              // variable declaration;
              //function declaration;
         };
The keyword 'class' indicates the name of the class. The body of the class enclosed with curly braces followed by semicolon.

The Body of class contain declaration of variables and function collectively called as data members and member function

Class helps you to apply access specifies on data members and member functions.

Data members and member function specified by private access specifies are accessible only to their own class members and not to outsiders but on the other hand public members are accessed to their own members and also from outside class.

Members in the without access specifies are private by default.

Access Specifies public, private are followed by colon.


 
Creating Object :
Declaration of class does not define any objects but specifies what they will contain.Creating object of class called as creating variables of the class. Object of class can be created by using class name like any other variable.

The Syntax is :
 Class_name object_name;
OR
Class_name object_name1,object_name2,object_name3,.........object_name n;

The Memory for the object is created when it is created.

Ex.
       Student xyz;
OR  Student xyz, abc,......;

Objects can also be created when the class is defined by placing their names immediately after the closing brace.

class Student
{
   //Data Members
  // Member Functions
}xyz,abc;

Accessing Class Members :

Once an object of a class has been created , There must provision to access its members. This is achieved by using member access operator that is (.) dot.

The syntax for Accessing Data Members of a class :

Object_name.data_member;

Syntax for accessing Member Function of class :

Object_name.function_name(Actual Arguments);

Recursion

It is a special case of calling a function when a function calls itself again and again.It forms a chaining f calling a function.

For example:-
void main(void)
{
cout<<"Hello Dear";
main( );  /* recursive call  */
}

When executed, this program will display "Hello" on the screen indefinitely.

Another useful example of recursion is evaluation of factorial of a number. The factorial of number is expressed as a series of repetitive multiplications as,

For example:
factorial of 5 = factorial of 4 ⤫ 5 
factorial of 4 = factorial of 3 ⤫ 4
factorial of 3 = factorial of 2 ⤫ 3 
factorial of 2 = factorial of 1 ⤫ 2
factorial of 1 = 1

This statement will be transferred into recursive process in function as given below:
int factorial(int n)
{
int fact;
if(n==1)
return 1;
else
return(n*factorial(n-1));
}

Consider another example of finding value of Xy using recursion:

#include<iostream.h>
#include<conio.h>
int power(int x, int y)
{
if(y<1)
return(1);
else
return(x * power(x,--y));
}
void main( )
{
cout<<power(4,3);
getch( );
}

Function Overloading

Overloading refers to the use of same thing for different purposes.

Function overloading is given by cpp.

Function overloading means using the same function to create different functions that performs variety of different task.

In function overloading, we design family of functions with one function name with different arguments list.

Function would performs different operations depending upon the arguments list.

Declaration:-

                  int add(int a, int b);                  //Prototype 1
                 
                  int add(int a, int b, int c);         //Prototype 2
                 
                  double add(int a, double q);     //Prototype 3


Function call:-

                   add(5,10);                       //Uses Prototype 1
                  
                   add(5,10.5);                    // Uses Prototype 3
                  
                   add(5,10,15);                  //Uses Prototype 2


The correct function will be invoked by checking number and type of arguments but it is not depends upon the function type.

Function call matches the prototype having same number and type of arguments then calls the appropriate function for execution.

#include<iostream.h>
#include<conio.h>
double volume(double int);
int volume(long, int, int);
void main( )
{
clrscr( )
cout<<"\n\t"<<volume(5,10,15);
cout<<"\n\t"<<volume(2.5,8);
cout<<"\n\t"<<volume(100L,70,15);
getch( );
}
double volume(double r, int h)
{
return(3.14*r*h);
}
long volume(long l, int b, int h)
{
return(l*b*h);
}
int volume(int a, int b, int c)
{
return(a*b*c);
}

Output:-
              750
              62.8
              105000

Default Arguments

C++ allows us to call a function without specifying all its arguments.

Default values are specified when function is declared.

Compiler looks at the prototype to see how many arguments, a function uses and alerts the program for possible default values.

Declaration of function with default values
   float amt(float prin_amt, int period, float rate = 0.12)

A function call
 float value = amt(500,7);
Passes value 500 to prin_amt and 7 to perod and then function uses 0.12 for rate.

A function call
float value = amt(500,7,0.15);
Passes explicit value of 0.15 to rate.

Only the trailing argument can have default values i.e. We can add default values from right to left. We can not provide default values in the middle of argument list.

#include<conio.h>
#include<iostream.h>
int volume(int len = 1, int wdt = 1, int hgt = 1);
void main( )
{
clrscr( )
{
cout<<"\n\n\tDefault box volume is--->"<<volume( );
cout<<"\n\n\tThe Volume with length 10 is--->"<<volume(10);
cout<<"\n\n\tThe Volume of the length 10 and width 10 is--->"<<volume(10,10);
cout<<"\n\n\tThe Volume with length 10, width 10 and height 10 is--->"<<volume(10,10,10);
getch( );
}
int volume(int len, int wdt, int hgt)
{
return(len*wdt*hgt);
}

Output:-
Default box volume is--->1
 The Volume with length 10 is--->10
 The Volume of the length 10 and width 10 is--->100
The Volume with length 10, width 10 and height 10 is--->1000

Popular Posts

Categories

100 Python Programs for Beginner (49) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (929) Python Coding Challenge (351) Python Quiz (22) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses