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

Object oriented programming deals with partitioning the entire programs into groups using data structures called 'objects' and assigning attributes and methods to them.Object oriented programming consists of two things:
1) classes
2) objects

CLASSES:
A class is a group of attributes of the same kind. it is used to impart object orientedness to a program. for example,pen, pencil, rubber etc belongs to a class stationary.A class is a blueprint for a data type. it cant be implemented itself, we always need an object to implement a class in a program.simple example using classes :

class abc
{
   public:
      double length;   // Length of a box
      double breadth;  // Breadth of a box
      double height;   // Height of a box
};
 
A class can be used with 3 keywords:
1) public-This means the attributed included in that class can be used even outside that class
2) private-This means attributes of a class are used within that class only 
3) protected-used basically in inheritance
 
OBJECTS:
Objects are the physical representation of classes. Classes cant be implemented without the help of the 
objects.Classes are the blueprints for objects.
Syntax for creating object:
 
classname objectname;
 
for example:
box box1;
here box is a classname whereas box1 is an objectname.
 
PRINCIPLES OF OOPS:
 
1)Encapsulation
Encapsulation is the process of hiding of data implementation by restricting access to accessors and 
mutators. Mutators are open ways that are used to update the state of an object, whereas concealing 
the implementation of exactly how the data gets revised. 
An accessor is a technique which is used to request an object about itself. In
OOP, they are generally in the form of properties, that have, under standard conditions, a get method, 
that is an accessor method.However, accessor methods are not confined to properties and can be any
kind of public method that offers information about the state of the object. 

2)Abstraction
Data abstraction is the easiest of principles to figure out. Data
abstraction and encapsulation are directly tied together, because a
plain definition of data abstraction is the growth and development of classes,
objects, types in terms of their interfaces and functionality, instead
of their implementation details. Abstraction denotes a model, a view,
or various other focused representation for an actual item. Its the
development of a software object to symbolize an object we can find in
the real world. Encapsulation hides the details of that implementation.

Abstraction is employed to manage complexity. Software developers use abstraction to
decompose complex models into smaller elements. As development
progress, software engineers know the overall performance they can expect from as
yet undeveloped subsystems. Thus, programmers are not burdened by
thinking about the ways in which the execution of later on subsystem
will influence the model of previous development.
 
3)Inheritance
Inheritance as the name suggests implies inheriting properties from one class to another.Let us take an
example,In a family child inherits properties/genes of his parents,his/her parents inherits properties/genes 
of their parents and so on.The same happens in the case of classes.A class can inherit certain properties 
from some other class.The class which inherits the properties  from some other class is referred to as 
child and the class from which the properties are inherited is referred to as base class or super-class.
 
4)Polymorphism
Polymorphism means a single name, numerous types. Polymorphism
manifests itself by having multiple ways all with similar name, but
slightly dissimilar functionality.

There are actually two basic types of polymorphism. Overriding, additionally
known as run-time polymorphism, and overloading, that is referred to as
compile-time polymorphism. This dissimilarity is, for method
overloading, the compiler decides which method will be
executed, and this choice is done when the code gets compiled.
Which method is going to be used for method overriding is determined at
run-time depending on the dynamic nature of an object.    
 
 





Read more

Variables are certain data types which can store values during execution of the program.The values stored in variables can be changed during the program execution.For eg. a,b,d etc.

Declaration of Variables

In order to create use of a variable in C++, they need to first declare it specifying which data type they need it to be. The syntax to declare a new variable is to write the specifier of the specified data type (like int, bool, float...) followed by a valid  variable identifier.Various data types are as followed:

Name                       Description                                               Size*           Range* 


char                          Character or small integer.               1byte           signed: -128 to 127                                                                                                                                     unsigned:0 to 255 
short int(short)       Short Integer.                                    2bytes         signed: -32768 to 32767  
                                                                                                                     unsigned: 0 to 65535 
int                              Integer.                                              4bytes         signed: -2147483648                                                                                                                        to 2147483647      
long int (long)          Long integer.                                   4bytes          signed: -2147483648 to                                                                                                                       2147483647 
                                                                                                                     unsigned: 0 to 4294967295 
bool                          Boolean value.                                  1byte true 
                                  It can take one of two                       or false 
                                  values: true  or false.                                                               
                                                   
float                         Floating point number.                 4bytes           +/- 3.4e +/- 38 (~7 digits)
double                    Double precision floating              8bytes            +/- 1.7e +/- 308 (15 digits)
                                     point number.
long double           Long double precision                   8bytes             +/- 1.7e +/- 308 (15 digits) 
                                   floating point number.


Read more


SAMPLE PROGRAM FOR BEGINNERS

// sample program

#include <iostream>

using namespace std; 
int main () 

 cout << "This is my first program"; 
return 0; 


// sample program


This is a comment line. All lines starting with slash signs (//) are  comments and don't 
have any impact on the behavior of the program. The computer programmer will use them to incorporate short explanations or observations among the ASCII text file itself. In the above Example the line may be a temporary description of  what our program is or what is it all about.This is used in very large programs in order to avoid any confusion.


#include <iostream>


Lines starting with a hash sign (#) are directives for the preprocessor. They're not regular code lines 
with expressions however indications for the compiler's preprocessor.In the above example, the directive #include  tells the preprocessor to incorporate the iostream customary file. This specific file (iostream) includes the declarations of the essential customary input-output library in C++, & it is enclosed because its  functionality is going to be used later within the program.Various other standard library header files are as followed:


Utilities library

<cstdlib>               General purpose utilities: program control, dynamic memory allocation                                                    
<csignal>              Functions and macro constants for signal management
<csetjmp>              Macro (and function) that saves (and jumps) to an execution context
<cstdarg>              Handling of variable length argument lists
<typeinfo>              Runtime type information utilities
<typeindex>           std::type_index
<type_traits>       Compile-time type information
<bitset>              std::bitset class template
<functional>      Function objects, designed for use with the standard algorithms
<utility>              Various utility components
<ctime>              C-style time/date utilites
<chrono>               C++ time utilites
<cstddef>              typedefs for types such as size_t, NULL and others
<initializer_list>       std::initializer_list class template
<tuple>)              std::tuple class template


using namespace std; 


All the elements of the quality C++ library are declared inside what's known as a namespace, the 
namespace with the name std.This line is frequent in C++ programs that use the  library functions, 
and actually it'll be enclosed in most of the source codes.
Namespaces in C++ are used to define a scope and allows us to group global classes, functions and/or objects into one group.

When you use using namespace std; you are instructing C++ compiler to use the standard C++ library. If you don't give this instruction, then you will have to use std::, each time you use a standard C++ function/entity.

int main () 


This line corresponds to the beginning of the definition of function operate. The main function is with which all C++ programs begin their execution, severally of its location among the ASCII text file. It 
does not matter whether or not there is different functions with different names outlined before or when it - the instructions contained among this function's definition can continuously be the primary ones to execute in any  C++ program. For that very same reason, it is essential that each one C++ programs have a main operate
The word main is followed within the code by a combine of parentheses (()).That is because it is a function  declaration:  In C++, what differentiates a main  declaration from different kinds of expressions are these  parentheses that follow its name. Optionally, these parentheses might enclose an inventory of parameters among  them. Right after these parentheses you can find the body of the main function enclosed in braces {}. What is  contained within these braces is what the function does when it is executed.


cout << "This is my first program"; 


This line is a C++ statement. A statement may be a straightforward or compound expression which will actually turn out some result. In fact, this statement performs the sole action that generates an understandable result in our initial program. 
cout represents the quality output stream in C++,  which means  to insert a sequence of characters (in this case the 'This is my first' program sequence of characters) in to the quality output stream (which is usually the output screen). 
Notice that the statement ends with a punctuation mark character (;). This character is employed to mark the end of the statement &  it should be enclosed at the end of all expression statements.


return 0;


The return statement causes the main function to finish. return may be followed by a return code (in our 
example is followed by the return code 0). A return code of 0 for the main function is generally interpreted 
as the program worked as expected without any errors during its execution. This is the most usual way to 
end a C++ console program.


Read more

Powered by Blogger.