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: