Tuesday, 23 December 2014

Character arrays and String arrays in C++ with examples

Character arrays and String arrays in Cpp with examples:

Creation of the character array syntax:

See the bleow sample that we can declare the names or words in the character array
char szExample[] = {‘F’, ‘i’, ‘r’, ‘s’, ‘t’, ‘s’, ‘m’, ‘p’, ‘l’, ‘e’};


Storing Sequences in Arrays

#include <iostream>
using namespace std;
void ShowArray(char stringArray[], int iSize);
int main(int nArg, char* pszArgs[])
{
  char szExample[] = {'F', 'i', 'r', 's', 't', 's', 'm', 'p', 'l', 'e'};
  ShowArray(szExample, 10);
  cout << "\n";
  return 0;
}
// ShowArray - display an array of characters
// by outputing one character at
// a time
void ShowArray(char stringArray[],int iSize) {
for(int i = 0; i< iSize; i++)
{
cout << stringArray[i];
}
}

Wednesday, 10 December 2014

Macros in c++ with example

Macros in C++ with Examples: 

Macros can be implemented using #define. When the call to the macro occurs, the code of the macro will substitute in the source code before compilation.
Syntax of the macro is
#define macroname(arg1, arg2…) expression

NOTE: Do not leave the space between the function and the parenthesis. The parenthesis should start immediately after the macro name.
Below is the small example:
#define MIN(i,j) (i < j ? i : j)


Wednesday, 3 December 2014

Calculate the time taken by a function in C and explain with example

How to calculate the time taken by a function in C? Please give examples for the same.

We can calculate the time taken by the process using the clock () function. This function is available in
 time.h
header.

By calling the clock function at the function start and the end of the code.
And t be follow the below steps to calculate the time taken by the process, please find the pseudo code.

What is name mangling in C++ and explain with example?

What is name mangling in Cpp?

C++ compilers differentiates the functions when it generates the object code. It adds the additional information to the function names called as name mangling. Name mangling is compiler dependent.

Why name mangling is required in c++?

As we know C++ supports function overloading, i.e., there can be more than one functions with same name and differences in parameters. To differentiate the functions name mangling should be used.
Let us see consider following declarations of function fun()

Possibility to overload main function in C++

Is it possible to overload main function in Cpp?

Yes, it is possible by declaring the main function as the member function in a class.
See the below example
#include <iostream>
using namespace std;
class MyTestClass

{

public:
    int main(int iVal)
    {
        cout << iVal << endl;
        return 0;
    }
    int main(char *pcCh)
    {
        cout << pcCh << endl;
        return 0;
    }
    int main(int iVal ,int iVal2)
    {
        cout << iVal << " " << iVal2 << endl;
        return 0;
    }
};
int main()
{
    MyTestClass obj;
    obj.main (12);
    obj.main ("Testin main function");
    obj.main (30, 300);
    getchar ();
    return 0;
}

How is it possible to restrict dynamic allocation of objects in C++?

How is it possible to restrict dynamic allocation of objects in C++?

Yes, it is possible only when we implement the new operator function in the private section.
See the below example
  #include <iostream>
using namespace std;
class MyTestClass
{
private:
    void* operator new(size_t size);
    int iVal;
public:
    MyTestClass ()          { iVal = 100; cout << "Constructor of the class is called\n"; }
    void display ()  { cout << "value is  = " << iVal << "\n";  }
    ~MyTestClass ()         { cout << "Destructor of the class is called\n"; }
};
int main()
{
 //  MyTestClass *ptr = new MyTestClass;
    MyTestClass ocTestCls;     
    ocTestCls.display();
    return 0;
} 


What are the functions that don’t automatically inherited from the base class?

What are the functions that don’t automatically inherited from the base class?

The functions that are not inherited from the base class to the derived class are constructors & destructors. These two are deals with the object creation and deletion, so they have the knowledge about their particular class.

There is another function operator=, which also not inherited by the derived class. Because it is also behaves like constructor to create the object.

Let us see the below example that the functions that are synthesized by the compiler.

Friday, 28 November 2014

Why is the size of an empty class not zero in C++? Explain with example.

Why is the size of an empty class not zero in C++? Please explain the same with examples.

The size of an empty class is not zero. It is 1 byte generally.
See the following example.
#include<iostream>
using namespace std;
class EmptyCls {};
int main ()
{
  cout <<”Size of Pointer”<< sizeof (EmptyCls);
  return 0;
}


What are default arguments in C++ with example

What are default arguments in C++:

The value that is provided in the declaration of the function itself is called as default argument.
These default values are assigned automatically to the function by the compiler.
We will look into the sample program below.

Thursday, 27 November 2014

Multiple Inheritance with examples in C++

Multiple Inheritance with examples in C++:

In C++ we have another great feature called inheritance. Inheritance is the derived class can acquire the features of base class.

Multiple inheritance:

A class that can inherit from more than one class is called as multiple inheritance.

In multiple inheritance the order of constructor calling is the order that they are inherited.

Let us see the below example that helps us to understand the order of constructors.

Object Slicing in C++ with examples

What is Object Slicing in C++?

Object Slicing is occurred when a derived class object is passed by value as a BaseCls  class object, the base class copy constructor is called. We know that using virtual functions concept.

Here the derived class object are sliced off.  if we upcast (Upcasting and downcasting) to  an object instead of a pointer or reference, the object is sliced.

See the below example how the object is sliced off:

Write overloading function using operator [] in C++ with examples

How to write overloading function using operator [] in C++:

The overloading of [] is useful to to check for index out of bound.
we need to return by reference in function because an expression like “arr[i]” can be used an lvalue.

Let us see how the implementation of the operator [] in the below program

Header files of the class.

Does the virtual functions be inlined?

Is the virtual functions be inlined? Please explain with examples.

As of we know the functions that are available n the class are treated as inline functions. What about the virtual functions???????

The compiler will not consider the virtual functions as inline functions, the functions that are considered as inline or not is purely compiler dependent.

Let us have a look into that:

First we need know about, What are virtual functions & how these are useful?
Virtual functions are used to achieve the late binding or dynamic binding. The virtual functions are used to achieve the runtime polymorphism.

Delete “this” operator works in C++ with examples

How delete “this” operator works in C++:

As we learned earlier the delete operator should works only with the objects that are allocated memory using the operator new. The delete is used to de-allocate the memory.
As of we know the delete operator should not be used for this pointer.
See the below example, to understand how delete works.

Wednesday, 26 November 2014

Upcasting and Downcasting in C++ with examples

What is Upcasting and Downcasting in c++?

Upcasting:

First we will look into the upcasting. Converting the derived class pointer to the base class pointer or converting the derived class reference to the base class reference is called as upcasting. It allows public inheritance without the need for an explicit type cast.

A Derived object is-a relationship with the base class. The derived class can get the properties of base class, nothing but it can inherit the data members and member function of the base class.

Means, anything that we can do to a Base object, we can do to a Derived class object.

Downcasting:

Downcasting is exactly opposite to the upcasting the opposite of upcasting. is a process converting a base-class pointer or reference to a derived-class pointer or reference.

It should possible with the explicit type conversion. Because a derived class could add new data members, and the class member functions that used these data members wouldn't apply to the base class.

What is a Memory leak? How the memory leaks occur in C++?

What is a Memory leak? How the memory leaks occur in C++? 

Memory leak:

When we allocate a piece of memory and forgot to de-allocate it, or it is not de-allocated properly. If the program does not use that memory further, it is still reserved and other program cannot use allocated memory until it is de-allocated, this situation is called memory leak.

How the memory leaks occur in C++?
Memory Leaks:

As we said earlier memory leaks occur when data that are allocated at runtime but not de-allocated once they are no longer needed. When an allocation has no matching de-allocation, that's a leak, and the heap debugger can help us find them.

Tuesday, 25 November 2014

Memory allocation, de-allocation using new and delete with examples and syntax


New and Delete in C++:

Memory allocation, de-allocation using new and delete:

The new operator is used to create the object dynamically. Using the new operator the memory is allocated and the constructor of the class gets called for that memory.

Using the delete the destructor of the class gets called and the memory is released which is allocated by new.

Syntax for the new operator:
MyCls *pcClass = new MyCls;

Allocating the memory for the array of class objects:

MyCls *pcClass = new MyCls[10];

Syntax for the delete:
delete pcClass;
delete []pcClass;
delete pcClass - frees the memory for an individual object allocated by new.
delete []pcClass - frees the memory for an array of objects allocated by new.

Monday, 24 November 2014

Memory Management functions malloc(), calloc(), and realloc() with examples

Memory Management functions malloc(), calloc(), and realloc():

The compiler allocates memory for the local variables on the stack. And there is a possibility that we can allocate memory on the heap using the memory allocation fucntions
malloc, calloc & realloc

Stack memory allocation:

The stack memory is allocated when the local variable found by the compiler and freed when the variable goes out of the scope
void myFun () {
int i; // memory is allocated on the stack
}

Sunday, 23 November 2014

Common mistakes while dealing with the heap memory in C++


What are the common mistakes while dealing with the heap memory in C++?

Most programmers do the mistakes while dealing with the pointers and references; if we misuse them, they will eat our time and mind.
Here some of the possible mistakes done by developer while doing the code using pointers:

Null dereferencing:

When we try to use the NULL pointers and trying to do some operations on that. See the below example, here the application gets crashed because we are trying to access the NULL dereferencing.
using namespace std;
/*This is my base class */
class MyBaseClass
{
  int i;
       public:
          MyBaseClass();
          virtual ~MyBaseClass();
          void MyFun ();
};
MyBaseClass::MyBaseClass ()
{
   i = 10;
   cout << "Constructor of MyBaseClass" << endl;
}
void MyBaseClass::MyFun ()
{
   cout << "I am in the Function" << i << endl;
}
MyBaseClass::~MyBaseClass ()
{
   cout << "Destructor of MyBaseClass" << endl;
}
int _tmain (int argc, _TCHAR* argv[])
{
 MyBaseClass *pcPtr = NULL;
  pcPtr->MyFun ();
    getchar ();
    return 0;
}

Thursday, 20 November 2014

New vs malloc in C++ with examples

New vs malloc in Cpp:

The new and the malloc both are used to allocate the memory in the heap. These are used to allocate the dynamic memory at the runtime of the application.

The main advantage of new over malloc() is that new can allocate memory and  it also constructs objects for the classes.
See the below syntaxes for malloc and new.
MyClass* objMalloc = (MyClass*)malloc(sizeof(MyClass));
MyClass* objNew = new MyClass();

After a run, both objMalloc and objNew will point to areas of memory in the heap that are big enough for a MyClass object.

Wednesday, 19 November 2014

What is the diamond problem and what is the virtual base class in C++?

What is the diamond problem and what is the virtual base class in Cpp?

Let us see at below diagram, which helps us in explaining the diamond problem.



In the above picture we have 2 classes B and C that derive from the class – A.  We also have class D that derives from both B and C by using multiple inheritance.
The compiler will gets confused that from which base it need to take.

Is it possible the destructor be pure virtual in C++?

Is it possible the destructor be pure virtual in C++?

Yes, pure virtual destructors are possible in C++.  When we declare the destructors are pure virtual destructor in the base class we need to provide the empty body for that. Why??? because, we know that the destructor calling sequence is from the most derived class to the base.so, the  derived class destructor will be invoked first and later base class destructor will be called.
 If definition for the pure virtual destructor is not provided then what function body will be called during object destruction?
C++ compiler & linker enforce existence of function body for pure virtual destructor.
Let us see the below program with the pure virtual function in the base calss with out the body for that and observe the results.

Virtual destructor in C++ with examples

Virtual destructor in C++:

First we need to know about the destructor of the class: the destructor is the member function that is used to destroy the memory of the object, when it is goes out of scope. That means the heap memory allocated by the member variables of the class can gets cleanup in the destructor of the class.

The order of execution of the destructors are in the below fashion.

First the derived class memory gets cleaned and then the base class destructor gets called and deletes the base class objects memory.
The order of execution of destructor in an inherited class during a cleanup is like this.

Tuesday, 18 November 2014

Smart Pointers implementation in C++ with examples

Smart Pointers implementation in C++ with examples:

A smart pointer is a pointer that is used to handle the problems that are caused by using the normal pointers.

class MyStudentCLs
{
    int iAge;
    char* pName;
    public:
        MyStudentCLs(): pName(0),iAge(0)
        {
        }
        MyStudentCLs (char* pName, int age): pName(pName), iAge(age)
        {
        }
        ~MyStudentCLs ()
        {
        }
        void Display ()
        {
            printf("Name of the student= %s Age of the student = %d \n", pName, iAge);
        }
        void Shout ()
        {
            printf("I am at the shout function");
        }
};
int _tmain (int argc, _TCHAR* argv[])
{
  MyStudentCLs* pMyStudentCLs  = new MyStudentCLs ("Suve", 15);
  pMyStudentCLs->Display ();
  delete pMyStudentCLs;
  getchar ();
  return 0;
}

Monday, 17 November 2014

Difference between delete and free() in C++ with example

What is the difference between delete and free() in C++ ? 

delete operator:

delete operator is used to delete the dynamic memory allocated using new operator or for the NULL pointer.
free () is used to free the dynamic memory allocated using the function malloc or for a NULL pointer.
Below example clarifies the differences between the free and delete.

C++ mutable keyword with example scenarios

C++ mutable keyword

Mutable is also one of the storage class specifier in C++, along the mutable there are auto, register, static and extern are the storage class specifiers in C++. There is another storage class specifier in C is typedef.

Why we need mutable keyword? What is the use of Mutable Keyword?

Sometimes there is requirement to modify one or more data members of class / struct through const function even though you don’t want the function to update other members of class / struct.
Mutable keyword is used to perform the modifications on the const variables.

Below is the example where use of mutable can be useful. Suppose we have the vehicle class, the features of the vehicle are same where ever you go. Suppose we want to sell the vehicle, we need to change the owner name and the price. At this scenario, we have to create the variable with the storage class mutable.

How is it possible to call constructor and destructor explicitly? Why we need to call them explicitly?

How is it possible to call constructor and destructor explicitly? Why we need to call them explicitly?

Introduction to Constructor:
Constructor is also a member function in the class, If we forgot to declare the constructor the C++ compiler will automatically provide on default constructor for us. The constructor is called when the object is created for the class.

Introduction to Destructor:
Destructor is also a member function in the class, If we forgot to declare the destructor the C++ compiler will automatically provide on default destructor for us. The constructor is called when the object is goes out of the class scope. The destructor is used to destroy the heap memory that is used for the member variable of the class.

Is it possible to call constructor and destructor explicitly?

For this question, let us see the below example which will help us to understand more about the question.

Exception Handling in C++ with examples

Exception Handling in C++ with examples:

In C++ we have the great feature that is EXCEPTION HANDLING. The key words that are used to handle the exceptions is
 try, catch, throw

Description about each keyword is explained below
try – it holds the code that can throw an exception.

catch: This represents a block of code that is executed when a particular exception is thrown.

throw: This is used to throw an exception.



Why we need Exception Handling? 

There are three situations that we need to go for the exception handling over error handling.

a. Exceptions are used to handle the errors generated by our programs by transferring control to functions called handlers.
b. To catch exceptions we have to place our code on which we want exception handling in the try block. If an exception occurs the control is passed to the handler, otherwise the handlers are ignored.
c. The try block contains the code that can produce the exceptions and the catch block holds the error handlers are declared in the try block.

Wednesday, 12 November 2014

Jump statements in C++ with examples

Jump statements in C++ with examples:

The break statement:

There are statements built in C++ programming to alter the normal flow of program.
The for, while, do-while ate used to perform the repetitive task till the expression is not valid.
There are the cases that we need to avoid some statements or we need to terminate the loop immediately after the some results as per our expectations. In C++ we have the “break and continue” statements.
The break; statement is also used to terminate switch statement.
The “break” statement is used to come out of the loop even the loop is not fulfilled. This break statement is also used to terminate the infinite loops.

Control Structures - The for loop in C++ with example

Control Structures - The for loop in C++ with example:

The syntax of the for loop is shown below

for (initialization; condition; increase/decrease)
 {
statement 1;
statement 2;
statement N;
}

There are 3 prosions exists in the for loop.
1. Initialization
2. Condition
3. Increment / Decrement

The initialization statement is executed only once at the beginning of the for loop. Then the program verifies the expression. If the test expression is false, for loop is terminated. But if test expression is true then the code/s inside body of for loop is executed and then update expression is updated. This process repeats until test expression is false.

Control Structures – switch with the examples

Control Structures – switch with the examples:

The use of the switch statement is to check several possible values for the single expression.
This is similar to the nested if- else statement. The syntax for the switch statement is as follows.
switch (expression)
{
  case constant1:
     list of statements 1;
     break;
  case constant2:
     list of statements 2;
     break;
  case constant3:
     list of statements 3;
     break;
  .
  .
  .
  default:
     default list of statements
}

Control Structures – Conditional statements in C++ with the Examples

Control Structures – Conditional statements in C++ with the Examples:

As of we know that a program is not a linear sequence of instructions. While in the process there are situations that will take the decisions, it may split or it may use repeated code.

To handle this type of scenarios in C++ we have the control structures.
As we know that the program is a list of statements that are separated by semicolons (;).
 All the statements are enclosed with the curly brasses { }.
 Here is the syntax:
int _tmain (int argc, _TCHAR* argv[])

{  // start of the main body

 ClsFirst ocFirst;  // statment1

 ClsSecond ocSecond; // statement 2

 ocFirst.Dump ("Before"); // statment3

 ocSecond.Update (ocFirst, 5);  // statment4

 ocFirst.Dump ("After");  // statement 5

  getchar (); 

  return 0;

}// end of the main body


Tuesday, 11 November 2014

Friend classes in C++ with the examples

Friend classes in C++ with the examples:

In C++ like friend function we have the friend classes also. By using the keyword “friend” it is possible to make the class as friend to another class. If we make the class as friend class, the member functions that are available in the class will becomes the friends to the another class.
The below is the syntax of the friend class. Here is one condition that  the friend becoming class must be first declared or defined

Sunday, 9 November 2014

Friend functions and the usage in C++ with the examples

Friend functions and the usage in C++ with the examples:

Data hiding is one of the most important topic in C++, The private data is not accessed to the outside world. That is a nonmember function cannot access the private data of the particular class. This rule does not affect friend function and friend classes.
To declare the function as a friend of another class, there is a keyword called friend.

friend Function in C++:

If any function that we defined as a friend function then, the private and protected data of class can be accessed from that function.  The compiler can easily found that the given function is friend, when it founds the keyword friend.
The below is the syntax of the friend function:

Wednesday, 5 November 2014

Storage classes available in C++

Storage classes available in C++: 

The storage classes are useful to us to specify the scope of the variables.
In C++ we have five different types available:
Automatic/Local Variables, keyword is auto

Mutable variables, keyword is mutable

Static Variables, keyword is static

Register Variables, keyword is register

Extern Variables, keyword is extern


Access specifiers / Access Modifiers/ Access controls of classes in C++

Access specifiers / Access Modifiers/ Access controls of classes in C++:

In C++ we have three access specifiers available.

Public
Private
protected
Based on the access modifiers the members and member functions accessed by outside the class.
 The access modifiers are followed by colon. We can use three modifiers in the same class to set the boundaries on the members and members function of the class.

Tuesday, 4 November 2014

Copy Constructor, Shallow and Deep Copying in C++ with examples

Copy Constructor, Shallow and Deep Copying in C++ with examples:

The copy constructor is the constructor, which is used to copy the data from existing object to the newly created object. In C++ the compiler creates the default copy constructor, it also copies all the data of the passed object to the object which is being created.

Here is the sample program that will help us to understand the usage of the copy constructor:

Wednesday, 29 October 2014

Class declarations and usage in C++ with examples

Class declarations and usage in C++ with examples:

Classes are the user defined data types. The default specifier of the class is private.
A class is blue print of the data type. The memory is not allocated for the class till you declare the object for that.
The definition of the class is defined using the keyword “class” and enclosed with the {};, it should ends with the semicolon as shown above.

Members of the class
The variables which are defined in the class are called as members
Methods of the class
The functions inside the class is called as methods / member functions
Access specifiers
 The class will support three access specifiers “public, private, protected”, the default access specifier is “private”
 Constructor
A constructor is a special function in a class that is called when a new object of the class is created.
Destructors
A destructor is also a special function, which is called when created object is deleted.
The Copy Constructor
This is also a type of the constructor that is used to create a copy of an existing object of the same class type.
Friend functions
It is one of the key features in c++. Friend functions are used to access the private and protected data of class. When the complier found the keyword friend, it knows the given function is friend function, the complier automatically recognizes that the given function is a friend function.
Inline functions
 These are also functions, but the code is replaced at the compile time which reduces the function calling overhead.

Tuesday, 28 October 2014

C++ Programming examples for beginners

Your First C++ program Structure:

The program is a collection of variables and function calls. The starting point of the program is main (). The primary code for the program starts from the main.

The function definition consist of return type and the list of arguments enclosed with the parenthesis.
In C++ the main function must have the return type of int.

The below is the sample function definition

Monday, 27 October 2014

Basics of C++ with examples

Basics of C++ :

Before going into the programming, You must know almost enough of the basics to create and compile a Program.  The programs that written in C++ will use iostream classes.
These read from and write to files and “standard” input and output.   In this simple program, a stream
object will be used to print a message on the screen.

Escape Sequence:

1. The “\” is an escape character.
2. The “\n” is used to change to a new line
3. The “\t” is used for horizontal tab.
4. The “\r” is used to carriage return – return the cursor to the beginning of current line.
5. The “\a” is an alert. It Sound the system bell.
6. The ‘\\” is used to print out a “\”.
7. The “\”” is used to print out a double quote.

Wednesday, 22 October 2014

Compilers and Interpreters

Compilers:

Compiler is actually a program that reads the code written in high level language and produces a executable that the CPU can understand. To run the executable you will not require the compiler. The below is the way how the compiler processes your high level code into the machine level language  

Introduction to CPP

The Cpptutorials.com is very useful to all the Cpp folks to learn more about C++ programming.
It is not a problem if you do not have the experience in the programming, this Cpp tutorials site will help you to become the master in the CPP. This site will help you to learn more about design in C++ and good programming style.