Read more

FRIEND FUNCTION

A non member function may not possess an access to the private data of a class . But , there could possibly be a scenario in which we want two classes to share a specific function . To illustrate , take into account a case where two classes , supervisor and Warden , are defined . We want to use a function Salary( ) to work on the object of both these classes . In this kind of situations , C++ enables the common function to be created friendly with the two the classes , thus enabling the function to have accessibility to the private data of these classes . This kind of a function will not need to be member of any of these classes .

Syntax:

class ABC
{
.....
.....
public:
.....
.....
friend void xyz(void);
};


STATIC MEMBER FUNCTION

Similar to static member variable , you can have static member function . When we declare a member of a class as static it implies regardless of how many objects of the class are built ,there is certainly just one copy of the static member . 

A static member is shared by all objects of the class . Almost all static data is initialized to zero whenever the first object is created , in the event that no other initialization exists. We can't place it in the class definition however it can be initialized outside the class. A member function which is declared static possesses the following characteristics : 



  • A static function will surely have access to just static members declared in the class . 
  • Syntax- class-name : : function-name ; 
Example:


#include <iostream>

using namespace std;

class Cuboid
{
   public:
      static int objectCount;
      // Constructor definition
      Cuboid(float a=2.0, float b=2.0, float c=2.0)
      {
         cout <<"Constructor called." << endl;
         length = a;
         breadth = b;
         height = c;
         // Increase every time object is created
         objectCount++;
      }
      float Volume()
      {
         return length * breadth * height;
      }
   private:
      float length;     // Length of a Cuboid
      float breadth;    // Breadth of a Cuboid
      float height;     // Height of a Cuboid
};

// Initialize static member of class Cuboid
int Cuboid::objectCount = 0;

int main(void)
{
   Cuboid Cuboid1(3.3, 1.2, 1.5);    // Declare Cuboid1
   Cuboid Cuboid2(8.5, 6.0, 2.0);    // Declare Cuboid2

   // Print total number of objects.
   cout << "Total objects: " << Cuboid::objectCount << endl;

   return 0;
}

Read more

One among the objectives of OOP is to standalone the details of execution from the class definition . It can be therefore a good idea to define the member functions outside the class . 

You can easliy define a member function outside the class definition yet still allow it to be inline just by making use of the qualifier inline in the header line of the function definition .For eg.


class box
{
......
......
public:
void abc(int a,float b);
};
inline void box :: abc(int a,float b)
{
number=a;
cost=b;
}

Read more

OBJECTS

When the class is formed , a number of objects may be created from the class as objects are illustration of the class .Objects are the physical entity to represent classes .A class gives you the blueprints for objects , thus generally an object is formed from a class . We declare objects of a class with precisely the same kind of declaration that we declare variables of fundamental types .


Syntax for declaring an object:


class_name object_name;


Let us assume we have created a class aman, ankit. Then creating objects for these two classes will be like:

aman a;         //object a is created
ankit b;          //object b is created

Note that you can only access the members of a class just after creating an object for that class.


Accessing data members of a class after creating an object:


The public data members of objects of a class can be accessed using the direct member access operator (.).

However,private and protected members can not be accessed directly using direct member access operator (.). 
For eg.


#include <iostream>

using namespace std;


// Program for finding the volume of a cuboid

class Cuboid
{
   public:
      double l;   // length of a Cuboid
      double b;  // Breadth of a Cuboid
      double h;   // Height of a Cuboid
};

int main( )

{
   Cuboid Cuboid1;        // Declare Cuboid1 of type Cuboid
   Cuboid Cuboid2;        // Declare Cuboid2 of type Cuboid
   double vol = 0.0;     // Store the volume of a Cuboid here

   // Cuboid 1 specification

   Cuboid1.h = 5.0; 
   Cuboid1.l = 6.0; 
   Cuboid1.b = 7.0;

   // Cuboid 2 specification

   Cuboid2.h = 10.0;
   Cuboid2.l = 12.0;
   Cuboid2.b = 13.0;
   // volume of Cuboid 1
   vol = Cuboid1.h * Cuboid1.l * Cuboid1.b;
   cout << "vol of Cuboid1 : " << vol <<endl;

   // volume of Cuboid 2

   vol = Cuboid2.h * Cuboid2.l * Cuboid2.b;
   cout << "vol of Cuboid2 : " << vol <<endl;
   return 0;
}

As all the data mebers are public hence these are accessed directly in the program.If we have used private for that then there will be error while using them in the main program.In case of protected, we can access those data members within the same package


Example using private access identifier:



#include <iostream>

using namespace std;


// Program for finding the volume of a cuboid

class Cuboid
{
   private:
      double l;   // length of a Cuboid
      double b;  // Breadth of a Cuboid
      double h;   // Height of a Cuboid

public:

    float vol(l,b,h)
    {
   double vol;
    vol = l*b*h;
   return 0;
   }
};

int main( )

{
   Cuboid Cuboid1;        // Declare Cuboid1 of type Cuboid
   Cuboid Cuboid2;        // Declare Cuboid2 of type Cuboid
   double m,n;
   m=Cuboid1.vol(20,10,12);
   n=Cuboid2.vol(10,10,13);
   cout << "vol of Cuboid1 : " <<m<<endl;
   cout << "vol of Cuboid2 : " <<n <<endl;
   return 0;
}


Read more

Concept of classes and objects run side by side.Hence,its beneficial if we discuss the duo together.

A class is an extended prospect of a data structure : rather than keeping just data , it may possess both data and functions .
An object is an instantiation of a class . When it comes to variables , a class can be the type , as well as an object would be the variable . 


Format for declaring a class:

class class_name {
  access_specifier_1:
    member1;
  access_specifier_2:
    member2;
  ...
  } object_names;

Where class_name is a valid identifier for the class, object_names is an optional list of names for objects of this class. The body of the declaration can contain members, that can be either data or function declarations, and optionally access specifiers.
An access specifier is one among the following three keywords : private , public or protected . All these specifiers alter the access rights that the members following them acquire :
  • private members of a class are accessible just from within other members of the similar class or from their friends . 
  • protected members are accessible from members of their similar class and from their friends , as well as from members of their derived classes . 
  • Finally , public members are accessible everywhere where the object is visible .

By default, all members of a class declared with the class keyword have private access for all its members. 

Simple example showing classses:



#include <iostream>
#include<conio.h>
using namespace std;

// Class Declaration
class abc
{
//Access - Specifier
public:

//Varibale Declaration
  string a;
  int n;
};

//Main Function
int main()
{
    // Object Creation For Class
    abc obj;

    //Get Input Values For Object Varibales
    cout<<"Enter a :";
    cin>>obj.a;

    cout<<"Enter  n :";
    cin>>obj.n;

    //Show the Output
    cout << obj.a << ": " << obj.n << endl;

    getch();
    return 0;
}

Static storage classes:

The static storage class guides the compiler to retain a local variable in existence throughout the duration of the program in place of generating and eliminating it every time itarrives into and dies of scope . Thus , producing local variables static enables them to sustain their values between function calls . The static modifier are often applied to universal variables . If this is done , it will cause that variable's scope to be limited to the file wherein it is declared . 

In C++ , whenever static is employed on a class data member , it leads to only one copy of this member to be shared by all objects of its class .

Simple program showing static classes:


#include <iostream>
using namespace std;

class Yummy {

  public:
    static int a;
    Yummy () { a++; };
    ~Yummy () { a--; };
};

int Yummy::a=0;


int main () {

  Yummy m;
  Yummy n[5];
  Yummy * f = new Yummy;
  cout << m.a << endl;
  delete f;
  cout << Yummy::a << endl;
  return 0;
}

Extern Storage classes:

The extern storage class is employed to provide a reference of a global variable which is visible to ALL the program files . By using 'extern' the variable simply cannot beinitialized since all it does is aim the variable name at a storage area location which has been previously defined .

If you have numerous files and you define a global variable or function which can be used in additional files also , then extern will be utilized in another file to offer reference of defined variable or function . Only for understanding extern is employed to declare a global variable or function in additional files . The extern modifier is most typically used whenever there are two or more records sharing the identical global variables or functions.

Read more

INLINE FUNCTIONS

C++ inline function is an effective concept which is commonly used with classes. If a function is inline, the compiler stores a copy of the code of the function at every point exactly where the function is called at compile time.Any kind of change to an inline function might require all clients of the function to be recompiled simply because compiler might need to change all the code once again elsewhere it will continue with old functionality.
To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function. The compiler may neglect the inline qualifier in case defined function is a lot more than a line.A function definition in a class definition is an inline function definition, possibly without using the inline specifier.

So how exactly does this make the program execute quicker? Simple, function calls are merely much more time taking than writing all of the code without functions. To go through your program and exchange a function you have implemented 100 times with the code from the function would be time consuming not too bright. Obviously, by using the inline function to switch the function calls with code you will additionally increase the size of your program.

Simple example of inline function:



#include <iostream>

using namespace std;

inline void hello()
  cout<<"hello";
}
int main()
{
  hello(); //Call it like a normal function...
  cin.get();
}


FUNCTION OVERLOADING


An overloaded declaration is a declaration which had been declared with similar initials just as a earlier declared declaration in a similar scope , except for that the two declarations include distinct arguments as well as undoubtedly distinct definition ( implementation ) .Function overloading means two or more functions can have the same name but either the number of arguments or the data type of arguments has to be different, also note that return value has no role because function will return a value when it is called and at compile time we will not be able to determine which function to call.

Whenever you call up an overloaded function or operator , the compiler signifies the preferred definition to utilize by comparing the argument categories you employed to call the function or even operator with the parameter kinds specified in the definitions . The method of selecting the most appropriate overloaded function or operator is called overload resolution .



Simple example showing function overloading:



#include <iostream>

using namespace std;


/* Number of arguments are different */


void display(char []);  // print the string passed as argument

void display(char [], char []);

int main()

{
   char one[] = "C programming";
   char second[] = "C++ programming";

   display(one);

   display(one, second);

   return 0;

}

void display(char v[])

{
   cout << v << endl;
}

void display(char v[], char m[])

{
   cout << v << endl << m << endl;
}

Read more

Functions can be called in two ways:-

1)Call by reference
2)Call by value

1)Call by value
Call by value is just calling a function simply.Call by value simply copies the values of the arguments in the formal parameters.For eg.

#include <iostream.h>

int ADD(int m);

int main(void)

{

int n= 50;

cout<<"%d %d"<< ADD (n), n);

return 0;
}

int ADD (int n)
{

n = n + n;

return n;
}

2)Call by refrence

Whenever you declare a variable in a program, the compiler reserves an amount of space for this variable. If you want to utilize that variable anywhere in your program, you call it thereby making use of its value. There are basically two biggest issues related to a variable: its value and its location in the memory.
The location of a variable in memory is referred to as its address.

If you supply the argument using its name, the compiler merely makes a backup of the argument’s value and provides it to the calling function. Although the calling function obtains the argument’s value and can use by any means, it cannot (permanently) modify it. C++ enables a calling function to modify the value of a passed argument if you think it necessary. If you want the calling function to modify the value of a supplied argument and return the customized value, you should pass the argument utilizing its reference.

To pass an argument as a reference, while declaring the function, precede the argument name with an ampersand “&”. You can pass 0, one, or higher arguments as reference in the program or perhaps pass all arguments as reference. The decision as to which argument(s) should be passed by value or by reference is based on whether or not you would like the called function to change the argument and permanently modify its value.

SWAPPING OF TWO NUMBERS(CALL BY REFERENCE)


#include <stdio.h>

void swaping (int *a, int *b);

int main(void)
{

int a = 10, b = 20;
  
cout<<"Before swapping: %d %d\n"<< a<<b;

swaping (&a, &b);

cout<<" after swapping: %d %d\n"<< a<< b;

return 0;
}

void swaping(int *a, int *b)
{
int temp;
temp = *a; /* save the value at address a */

*a = *b; /* put b into a */

*b = temp; /* put a into b */
}

Read more


A function is a collection of statements that collectively operate a task. Every single C++ program includes a minimum of one function that is main(), and all the the majority of small programs can define other functions.
You may split up your code into different functions. A function name employs the similar rules that have been employed on our variables until now .Further to this,make use of a name that specifies exactly what the function |is predicted to do.

FUNCTION DECLARATION

In an effort to construct and apply a function, you need to let the compiler know. Allowing the compiler know about your function implies you “declare” it. The syntax of declaring a function is:

Return_type Function_name(parameter_list);

An activity, considered a function, is made of 3 parts: its purpose, its needs, and the expectation. Based on this formula, the expectation you have from a function is the ReturnType factor.ReturnType can be void or int,float etc.Using void as a returntype keyword signifies that a function does not return a value.But using keywords like int,float we have to return the result at the end of the function.More about this will be discussed later.Parameter list refers to the values that you want to include in your function from the program or from the user's side.Parameter list can be empty if you don't want to use any parameters.

Say, If you have an addition of two numbers function and you want that this function can accept values entered by the user at the run time then you should have two parameters. For eg.

void/int add(int a,int b);

FUNCTION DEFINITION

In an effort to use a function you need to allow the compiler to know what the function basically do,how the function will be executed.This is referred to as defining a function.Its syntax is as followed:

Return_type Function_name(parameter_list)
{
statements;
}
Statements include the code which is used for the implementation of the function.For eg.

Function for the addition of two numbers:

void add(int a,int b)
{
int c;
c=a+b;
cout<<"addition of two numbers is %d"<<c;
}

FUNCTION CALLING

After defining and declaring a function you definitely want to use the function in your program.Using function in a program is referred to as Function calling.Wherever you want to use a function in a program just call that function by the following syntax:

function_name(parameter_list);

SIMPLE C++ PROGRAM USING FUNCTION


#include <iostream>
using namespace std;
 
// function declaration
int max(int a, int b);
 
int main ()
{
   // local variable declaration:
   int m = 100;
   int n = 200;
   int res;
 
   // calling a function to get max value.
   res = max(m, n);
 
   cout << "Max value is : " << res << endl;
 
   return 0;
}
 
// function returning the max between two numbers
int max(int a, int b) 
{
   // local variable declaration
   int result;
 
   if (a > b)
      result = a;
   else
      result = b;
 
   return result; 
}




Read more

Powered by Blogger.