Google News
logo
CPP Interview Questions
As an extension of the C language, C++ is an object-oriented programming language created by Bjarne Stroustrup. It was released in 1985. C++ is a superset of C with the major addition of classes in C language.
 
Initially, Stroustrup called the new language "C with classes". However, after sometime the name was changed to C++. The idea of C++ comes from the C increment operator ++.
The class is a user-defined data type. The class is declared with the keyword class. The class contains the data members, and member functions whose access is defined by the three modifiers are private, public and protected. The class defines the type definition of the category of things. It defines a datatype, but it does not define the data it just specifies the structure of data.
 
You can create N number of objects from a class.
By using the keyword class followed by identifier (name of class) you can specify the class in C++. Inside curly brackets, body of the class is defined. It is terminated by semi-colon in the end.
class name{
// some data
// some functions
};
The main difference between C and C++ are provided in the table below :

C C++
* C language was developed by Dennis Ritchie. * C++ language was developed by Bjarne Stroustrup.
* C is a structured programming language. * C++ supports both structural and object-oriented programming language.
* C is a subset of C++. * C++ is a superset of C.
* In C language, data and functions are the free entities. * In the C++ language, both data and functions are encapsulated together in the form of a project.
* C does not support the data hiding. Therefore, the data can be used by the outside world. * C++ supports data hiding. Therefore, the data cannot be accessed by the outside world.
* Namespace features are not present in C * Namespace is used by C++, which avoids name collisions.
* Functions can not be defined inside structures. * Functions can be defined inside structures.
* calloc() and malloc() functions are used for memory allocation and free() function is used for memory deallocation. * new operator is used for memory allocation and deletes operator is used for memory deallocation.
* In C, scanf() and printf() are mainly used for input/output. * C++ mainly uses stream cin and cout to perform input and output operations.
Virtual functions are used with inheritance, they are called according to the type of object pointed or referred, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at runtime. Virtual keyword is used to make a function virtual.
 
Following things are necessary to write a C++ program with runtime polymorphism (use of virtual functions) :

a) A base class and a derived class.
b) A function with same name in base class and derived class.
c) A pointer or reference of base class type pointing or referring to an object of derived class.

In the following program bp is a pointer of type Base, but a call to bp->show() calls show() function of Derived class, because bp points to an object of Derived class.
#include<iostream>
using namespace std;

class Base {
public:
	virtual void show() { cout<<" In Base \n"; }
};

class Derived: public Base {
public:
	void show() { cout<<"In Derived \n"; }
};

int main(void) {
	Base *bp = new Derived;	
	bp->show(); // RUN-TIME POLYMORPHISM
	return 0;
}​

Output : In Derived
The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. ‘this’ pointer is a constant pointer that holds the memory address of the current object. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name).

#include <iostream>
#include <string>
using namespace std;

int main() {
  string education = "Free Time Learning";

  cout << education << "\n";
  cout << &education << "\n";
  return 0;
}​
Output : 

Free Time Learning
0x7ffecd166cb0
In C++ a structure is the same as a class except for a few differences like security. The difference between struct and class are given below :

Structure Class
Members of the structure are public by default. Members of the class are private by default.
When deriving a struct from a class/struct, default access specifiers for base class/struct are public. When deriving a class, default access specifiers are private.
An object is a run-time entity. An object is the instance of the class. An object can represent a person, place or any other item. An object can operate on both data members and member functions. The class does not occupy any memory space. When an object is created using a new keyword, then space is allocated for the variable in a heap, and the starting address is stored in the stack memory. When an object is created without a new keyword, then space is not allocated in the heap memory, and the object contains the null value in the stack.
class Student  
{  
//data members;  
//Member functions  
}  

 

The syntax for declaring the object :
Student s = new Student();  
One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.
 
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.
 
Syntax :
class derived-class: access-specifier base-class
A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object.
Comments in C++ are simply a piece of source code ignored by the compiler. They are only helpful for a programmer to add a description or additional information about their source code.
 
In C++ there are two ways to add comments :
//single-line comment
/* block comment */
The first type will discard everything after the compiler encounters “//”. In the second type, the compiler discards everything between “/*” and “*/”.
Encapsulation is the process of binding together the data and functions in a class. It is applied to prevent direct access to the data for security reasons. The functions of a class are applied for this purpose. For example, the customers' net banking facility allows only the authorized person with the required login id and password to get access. That is too only for his/her part of the information in the bank data source.

In C++ encapsulation can be implemented using Class and access modifiers. Look at the below program :
#include <iostream>
using namespace std;

class Encapsulation
{
	private:
		// data hidden from outside world
		int x;
		
	public:
		// function to set value of
		// variable x
		void set(int a)
		{
			x =a;
		}
		
		// function to return value of
		// variable x
		int get()
		{
			return x;
		}
};

// main function
int main()
{
	Encapsulation obj;
	
	obj.set(5);
	
	cout<<obj.get();
	return 0;
}


Output : 5

Even though it is possible to call an inline function from within itself in C++, the compiler may not generate the inline code. This is so because the compiler won’t determine the depth of the recursion at the compile time.
 
Nonetheless, a compiler with a good optimizer is able to inline recursive calls until some depth is fixed at compile-time and insert non-recursive calls at compile time for the cases when the actual depth exceeds run time.
In order to reduce the function call overhead, C++ offers inline functions. As the name suggests, an inline function is expanded in line when it is called.
 
As soon as the inline function is called, the whole code of the same gets either inserted or substituted at the particular point of the inline function call. The substitution is complete by the C++ compiler at compile time. Small inline functions might increase program efficiency.
 
The syntax of a typical inline function is :
Inline return-type function-name(parameters)
{
// Function code goes here
}
As the inlining is a request, not a command, the compiler can ignore it.
The declaration of a variable is merely specifying the data type of a variable and the variable name. As a result of the declaration, we tell the compiler to reserve the space for a variable in the memory according to the data type specified.
 
Example :
int Result;
char c;
int a,b,c;
All the above are valid declarations. Also, note that as a result of the declaration, the value of the variable is undetermined.
 
Whereas, a definition is an implementation/instantiation of the declared variable where we tie up appropriate value to the declared variable so that the linker will be able to link references to the appropriate entities.
 
From above Example,
Result = 10;

C = ‘A’;
These are valid definitions.
The scope of a variable is defined as the extent of the program code within which the variable remains active i.e. it can be declared, defined or worked with.
 
There are two types of scope in C++ :
 
Local Scope : A variable is said to have a local scope or is local when it is declared inside a code block. The variable remains active only inside the block and is not accessible outside the code block.

Global Scope : A variable has a global scope when it is accessible throughout the program. A global variable is declared on top of the program before all the function definitions.

Example :
#include <iostream.h>
Int globalResult=0; //global variable
int main()
{
Int localVar = 10; //local variable.
….. 
}
Data abstraction is a technique to provide essential information to the outside world while hiding the background details. Here in below example you don’t have to understand how cout display the text “Hello guru99” on the user screen and at the same time implementation of cout is free to change
 
For example :
#include <iostream>
using namespace std;

int main() {
   cout << "Hello C++" <<endl;
   return 0;
}

Output : Hello C++

When there are two variables with the same name but different scope, i.e. one is a local variable and the other is a global variable, the compiler will give preference to a local variable.
 
In order to access the global variable, we make use of a “scope resolution operator (::)”. Using this operator, we can access the value of the global variable.
 
Example:
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main () {
   // Local variable declaration:
   int g = 10;

   cout << g;   // Local
   cout << ::g; // Global
   return 0;
}​

 

Output :
10
20
Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special meaning to the user-defined data type. Operator overloading is used to overload or redefines most of the operators available in C++. It is used to perform the operation on the user-defined data type. For example, C++ provides the ability to add the variables of the user-defined data type that is applied to the built-in data types.

Syntax of Operator Overloading : 
return_type class_name  : : operator op(argument_list)  
{  
     // body of the function.  
}  ​
* Where the return_type is the type of value returned by the function.
* class_name is the name of the class.
* operator op is an operator function where op is the operator being overloaded, and the operator is the keyword.

C++ Operators Overloading Example : 
#include <iostream>    
using namespace std;    
class Test    
{    
   private:    
      int num;    
   public:    
       Test(): num(8){}    
       void operator ++()         {     
          num = num+2;     
       }    
       void Print() {     
           cout<<"The Count is: "<<num;     
       }    
};    
int main()    
{    
    Test tt;    
    ++tt;  // calling of a function "void operator ++()"    
    tt.Print();    
    return 0;    
}
Output :
The Count is: 10
Polymorphism in simple means having many forms. Its behavior is different in different situations. And this occurs when we have multiple classes that are related to each other by inheritance.
 
For example, think of a base class called a car that has a method called car brand(). Derived classes of cars could be Mercedes, BMW, Audi - And they also have their own implementation of a cars
 
The two types of polymorphism in c++ are :
* Compile-time Polymorphism
* Run-time Polymorphism

(i) Compile-time Polymorphism :
In compile-time polymorphism, we achieve many forms by overloading. Hence, we have an Operator overloading and function overloading. (We have already covered this above)
 
(ii) Run-time Polymorphism :
This is the polymorphism for classes and objects. General idea is that a base class can be inherited by several classes. A base class pointer can point to its child class and a base class array can store different child class objects.
In C++ there are the following access specifiers :
 
* Public : All data members and member functions are accessible outside the class.
* Protected : All data members and member functions are accessible inside the class and to the derived class.
* Private : All data members and member functions are not accessible outside the class.
If there are two or more functions with the same name defined in different libraries then how will the compiler know which one to refer to? Thus namespace came to picture. A namespace defines a scope and differentiates functions, classes, variables etc. with the same name available in different libraries. The namespace starts with the keyword “namespace”.

The syntax for the same is as follows :
namespace namespace_name {
   // code declarations
}
Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.
 
A destructor is a member function with the same name as its class prefixed by a ~ (tilde).

For example :
class X{
public:
  // Constructor for class X
  X();
  // Destructor for class X
  ~X();
};
Function overloading is a C++ programming feature that allows us to have more than one function having same name but different parameter list, when I say parameter list, it means the data type and sequence of the parameters, for example the parameters list of a function myfuncn(int a, float b) is (int, float) which is different from the function myfuncn(float a, int b) parameter list (float, int). Function overloading is a compile-time polymorphism.
Now that we know what is parameter list lets see the rules of overloading: we can have following functions in the same scope.
sum(int num1, int num2)
sum(int num1, int num2, int num3)
sum(int num1, double num2)

Function overloading example program : 

#include <iostream>
using namespace std;
class Addition {
public:
    int sum(int num1,int num2) {
        return num1+num2;
    }
    int sum(int num1,int num2, int num3) {
       return num1+num2+num3;
    }
};
int main(void) {
    Addition obj;
    cout<<obj.sum(27, 18)<<endl;
    cout<<obj.sum(81, 108, 9);
    return 0;
}

Output : 
45
198

A string is a sequence of characters. In C++, string is a data type as well as a header file. This header file consists of powerful functions of string manipulation. A variable of string is declared as follows :
string str= "Hello"; 
 
And to use string one needs to include the header file.
// Include the string library
#include <string>
 
// Create a string variable
string str= "Hello";​
In call by value method, we pass a copy of the parameter is passed to the functions. For these copied values a new memory is assigned and changes made to these values do not reflect the variable in the main function.
 
In call by reference method, we pass the address of the variable and the address is used to access the actual argument used in the function call. So changes made in the parameter alter the passing argument.
A Copy constructor is an overloaded constructor used to declare and initialize an object from another object.
 
Copy Constructor is of two types :

Default Copy constructor : The compiler defines the default copy constructor. If the user defines no copy constructor, compiler supplies its constructor.
User Defined constructor : The programmer defines the user-defined constructor.
 
Syntax Of User-defined Copy Constructor :
 
Class_name(const class_name &old_object);  

Consider the following situation :
class A  
{  
    A(A &x) //  copy constructor.  
   {  
       // copyconstructor.  
   }  
}
   
There are two important distinctions between a class and a structure in C++. These are :
 
* When deriving a structure from a class or some other structure, the default access specifier for the base class or structure is public. On the contrary, default access specifier is private when deriving a class.

* While the members of a structure are public by default, the members of a class are private by default
Denoted by the static keyword, a static member is allocated storage, in the static storage area, only once during the program lifetime. Some important facts pertaining to the static members are :
 
* Any static member function can’t be virtual
* Static member functions don’t have ‘this’ pointer
* The const, const volatile, and volatile declaration aren’t available for static member functions
The reference variable in C++ is the name given to the existing variables. The variable name and reference variable point share the same memory location in C++, which helps in updating the original variable using the reference variable. The code can be displayed in the following example.
#include<iostream>
using namespace std;
int main()
{
  int x = 10;
  // ref is a reference to x.
  int& ref = x;
  // Value of x is now changed to 20
  ref = 20;
  cout << "x = " << x << endl ;
  // Value of x is now changed to 30
  x = 30;
  cout << "ref = " << ref << endl ;
  return 0;
} 

Output :
x = 20
ref = 30

Following are the differences between reference and pointer :

Reference
Pointer
Reference behaves like an alias for an existing variable, i.e., it is a temporary variable. The pointer is a variable which stores the address of a variable.
Reference variable does not require any indirection operator to access the value. A reference variable can be used directly to access the value. Pointer variable requires an indirection operator to access the value of a variable.
Once the reference variable is assigned, then it cannot be reassigned with different address values. The pointer variable is an independent variable means that it can be reassigned to point to different objects.
A null value cannot be assigned to the reference variable. A null value can be assigned to the reference variable.
It is necessary to initialize the variable at the time of declaration. It is not necessary to initialize the variable at the time of declaration.
* An Array is a collection of homogeneous elements while a list is a collection of heterogeneous elements.
* Array memory allocation is static and continuous while List memory allocation is dynamic and random.
* In Array, users don't need to keep in track of next memory allocation while In the list, the user has to keep in track of next location where memory is allocated.
* new() is a preprocessor while malloc() is a function.

* There is no need to allocate the memory while using "new" but in malloc() you have to use sizeof().

* "new" initializes the new memory to 0 while malloc() gives random value in the newly allotted memory location.

* The new() operator allocates the memory and calls the constructor for the object initialization and malloc() function allocates the memory but does not call the constructor for the object initialization.

* The new() operator is faster than the malloc() function as operator is faster than the function.
* A virtual function is used to replace the implementation provided by the base class. The replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer.

* A virtual function is a member function which is present in the base class and redefined by the derived class.

* When we use the same function name in both base and derived class, the function in base class is declared with a keyword virtual.

* When the function is made virtual, then C++ determines at run-time which function is to be called based on the type of the object pointed by the base class pointer. Thus, by making the base class pointer to point different objects, we can execute different versions of the virtual functions.
 
Rules of a virtual function :
 
* The virtual functions should be a member of some class.
* The virtual function cannot be a static member.
* Virtual functions are called by using the object pointer.
* It can be a friend of another class.
* C++ does not contain virtual constructors but can have a virtual destructor.
Stack Unwinding happens during exception handling. During an exception occurrence, the destructor is called to destroy all local objects for the place where the exception was thrown and where it was caught. An exception causes the control to pass on from a try block to the respective exception handler.  The destructors for all constructed automatic objects are called at run time which where created since the beginning of the try block. The automatic objects are destroyed in reverse order of their construction.
 
Note : The corresponding objects must be created before destruction of the same which takes place during Stack Unwinding.
 
The terminate() function is invoked during Stack Unwinding on a destructor for a unhandled exception.
 
 
Deep copy involves using the contents of one object to create another instance of the same class. In a deep copy, the two objects may contain ht same information but the target object will have its own buffers and resources. the destruction of either object will not affect the remaining object. The overloaded assignment operator would create a deep copy of objects.
 
Shallow copy involves copying the contents of one object into another instance of the same class thus creating a mirror image. Owing to straight copying of references and pointers, the two objects will share the same externally contained contents of the other object to be unpredictable.
 
Using a copy constructor we simply copy the data values member by member. This method of copying is called shallow copy. If the object is a simple class, comprised of built in types and no pointers this would be acceptable. This function would use the values and the objects and its behavior would not be altered with a shallow copy, only the addresses of pointers that are members are copied and not the value the address is pointing to. The data values of the object would then be inadvertently altered by the function. When the function goes out of scope, the copy of the object with all its data is popped off the stack.
 
If the object has any pointers a deep copy needs to be executed. With the deep copy of an object, memory is allocated for the object in free store and the elements pointed to are copied. A deep copy is used for objects that are returned from a function.
The local scope of a variable allows the variable to work inside a restricted block of code. For instance, if it is declared inside a function, you cannot access it from the main function without calling the function whereas the global scope of a variable allows the variable to be accessible throughout the entire program.
 
It is a well-established fact that whenever a program has a local and global variable, precedence is given to the local variable within that program.
In object-oriented programming, the entire program is divided into smaller units called objects and works on the bottom-up approach. Whereas, in procedural programming, the entire program is divided into smaller units called functions and works on the top-down approach.
 
In a nutshell, procedural programming does not provide any data security whereas, in contrast to it, object-oriented programming ensures data security with the help of access specifiers, proving to be more secure and efficient.
 
C++ supports object-oriented programming whereas C supports procedural programming.
Inline Function is nothing but simply a function for which the C++ compiler produces a copy of it every time the function is called during compilation. It is an important feature that rose out from classes and objects in C++. 
 
If any changes are made to an inline function, the section of the code containing the function is again compiled and necessary changes in the copies of the code are made, otherwise, it would continue to work according to the old code.
 
In order to indicate that a function is inline, we use the keyword “inline” in C++.
 
The general syntax for declaring an inline function in C++ is :
inline return_type function_name( arguments )
{
// BODY OF THE FUNCTION
}
While creating and allocating memory to a variable with the help of the “new” keyword, we can deallocate the memory associated with it by the help of the “delete[]” operator whereas, while creating and allocating memory to a non-array object with new, we can deallocate the memory with the help of the “delete” operator.
There are two types of scope in C++, local and global. A variable has a local scope when it is declared inside a code block. The variable remains active only inside the block and is not accessible outside the code block. Conversely, a variable has a global scope when it is accessible by the entire program. A global variable needs to be declared at the top of a program before all the function definitions.
In the context of a C++ program, a constant is a type of expression that has a fixed value. Constants can be divided into integer, decimal, floating-point, character, or string, depending on the type of data. C++ also supports octal and hexadecimal constants.
No!. This is because even if we provide the default arguments to the parameters of the overloaded operator function we would end up using the binary operator incorrectly. This is explained in the following example :
sample operator + ( sample a, sample b = sample (2, 3.5f ) ){
 }
void main( )
{
   sample s1, s2, s3 ;
   s3 = s1 + ; // error
   }​
Vectors and Lists are defined under C++ Standard Template Library (STL). These data structures are basically sequential containers implemented using STLs.
 
* A Vector is a contiguous block of memory locations similar to Arrays in “C” programming while a List stores non-contiguous blocks and uses a double linked list.

* Inserting and Deleting elements in a List is easier compared to Vector as in the latter, shifting of elements is required and it is a tedious process.

* However sorting and searching are much faster in Vector compared to List and in former no traversal is required unlike List.

* Lists support no numeric index like Array while Vector supports the same.

      * Insertion and Deletion of elements in List has no iterator validation unlike Vector where the same is possible.
Upcasting is converting a derived class reference or pointer to a base class. In other words, upcasting allows us to treat a derived type as though it were its base type. It is always allowed for public inheritance, without an explicit type cast. This is a result of the is-a relationship between the base and derived classes. Upcasting allows us to treat a derived type as though it were its base type.
 
When a derived class object is passed by value as a base class object, the specific behaviors of a derived class object are sliced off. We're left with a base class object. In other words, if we upcast (Upcasting and Down Casting) to an object instead of a pointer or reference, the object is sliced. As a result, all that remains is the sub object that corresponds to the destination type of our cast and which is only a part of the actual derived class.
 
Converting a base-class pointer (reference) to a derived-class pointer (reference) is called downcasting. Downcasting is not allowed without an explicit typecast. The reason for this restriction is that the is-a relationship is not, in most of the cases, symmetric. 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.
In C++, RTTI (Run-time type information) is a mechanism that exposes information about an object’s data type at runtime and is available only for the classes which have at least one virtual function. It allows the type of an object to be determined during program execution
 
For example, dynamic_cast uses RTTI and following program fails with error “cannot dynamic_cast `b’ (of type `class B*’) to type `class D*’ (source type is not polymorphic) ” because there is no virtual function in the base class B.
 
// CPP program to illustrate 
// Run Time Type Identification 
#include<iostream>
using namespace std;
class B { };
class D: public B {};
  
int main()
{
    B *b = new D;
    D *d = dynamic_cast<D*>(b);
    if(d != NULL)
        cout<<"works";
    else
        cout<<"cannot cast B* to D*";
    getchar();
    return 0;
}
Adding a virtual function to the base class B makes it working.
// CPP program to illustrate 
// Run Time Type Identification 
#include<iostream>
using namespace std;
class B { virtual void fun() {} };
class D: public B { };
  
int main()
{
    B *b = new D;
    D *d = dynamic_cast<D*>(b);
    if(d != NULL)
        cout << "works";
    else
        cout << "cannot cast B* to D*";
    getchar();
    return 0;
}
Output :
works
In C++, equal to (==) and assignment operator (=) are two completely different operators.
 
* Equal to (==) is an equality relational operator that evaluates two expressions to see if they are equal and returns true if they are equal and false if they are not.
 
* The assignment operator (=) is used to assign a value to a variable. Hence, we can have a complex assignment operation inside the equality relational operator for evaluation.
C++ supports the following arithmetic operators :
 
+ addition
subtraction
* multiplication
/ division
% module

Let’s demonstrate the various arithmetic operators with the following piece of code.
 
Example :
#include <iostream>
using namespace std;

int main() {
    int a, b;
    a = 4;
    b = 5;

    // printing the sum of a and b
    cout << "a + b = " << (a + b) << endl;

    // printing the difference of a and b
    cout << "a - b = " << (a - b) << endl;

    // printing the product of a and b
    cout << "a * b = " << (a * b) << endl;

    // printing the division of a by b
    cout << "a / b = " << (a / b) << endl;

    // printing the modulo of a by b
    cout << "a % b = " << (a % b) << endl;

    return 0;
}
Output :
a + b = 9
a - b = -1
a * b = 20
a / b = 0
a % b = 4
Array uses the index to traverse each of its elements.
 
If A is an array then each of its elements is accessed as A[i]. Programmatically, all that is required for this to work is an iterative block with a loop variable i that serves as an index (counter) incrementing from 0 to A.length-1.
 
This is exactly what a loop does and this is the reason why we process arrays using for loops.
There are several methods by which one can allocate memory to 2D array dynamically one of which is as follows.
#include <iostream> 
int main() 
{ 
    int row = 2, col = 2; 
    int* a =  new int[row * col];
   
    int i, j, count = 0; 
    for (i = 0; i <  row; i++) 
      for (j = 0; j < col; j++) 
         *(a+ i*col + j) = count++; 
   
    for (i = 0; i <  row; i++) 
      for (j = 0; j < col; j++) 
         printf("%d ", *(a + i*col + j)); 
   
    delete[ ] a;
    return 0; 
} 

Output : 
0 1 2 3 

Some of the operators that cannot be overloaded are as follows :
 
* Dot operator- “.
* Scope resolution operator- “::
* “sizeof” operator
* Pointer to member operator- “.*
Bool is a data type in C++ which takes two values- True and False. Syntax is as follows:
bool b1 = true;
 
A sample code is as follows :
#include<iostream> 
using namespace std; 
int main() 
{ 
    int a= 4, b= 5; 
    bool c, d; 
    c= a== b; // false 
       
    c= a< b; // true 
       
    cout <<b1; 
    cout << b2 ; 
           
    return 0; 
}
* C++ supports goto statements whereas Java does not.
* C++ uses a compiler only whereas Java uses both compiler and interpreter.
* C++ supports multiple inheritance whereas Java does not support multiple inheritance
* Java supports unsigned right shift operator (>>>) whereas C++ does not.
* C++ is majorly used in system programming whereas Java is majorly used in application programming.
* C++ supports operator overloading whereas Java does not support operator overloading.
* C++ has pointers which can be used in the program whereas Java has pointers but internally.
* C++ has both call by value and call by reference whereas Java supports only call by value.
* C++ supports structures and joins whereas Java does not support structure and joins
* C++ is interactive with hardware whereas Java is not that interactive with hardware.
The strings in C++ can be concatenated in two ways- one considering them string objects and second concatenating them C style strings.
#include <iostream>
using namespace std;
int main()
{
    string s_1, s_2, fin;
    cout << "Enter string";
    getline (cin, s_1);
    cout << "Enter string ";
    getline (cin, s_2);
    fin= s_1 + s_2;
    cout << fin;
 
    char str1[50], str2[50], fin[100];
 
    cout << "Enter string";
    cin.getline(str1, 50);
 
    cout << "Enter string";
    cin.getline(str2, 50);
 
    strcat(str1, str2); 
 
    cout << "str1 = " << str1 << endl;
    cout << "str2 = " << str2;
 
    return 0;
}
To find the absolute value in c++, we can use abs() function. The abs() function in C++ returns the absolute value of an integer number.
#include <iostream>
#include <cstdlib>
using namespace std;
 
int main()
{
        int a=5.42;
        int x = abs(a);
        cout << x;
            return 0;
}

Output : 5

An expression is a combination of operators, constants and variables. There seven types of expressions for examples :
 
* Constant expressions: 89 +10/4.0
* Integral expressions: x * y
* Floating expressions: 17.89
* Relational expressions: a<=b
* Logical expressions: a > b && a == 7
* Pointer expressions: *ptr
* Bitwise expressions: p << 5
The length of a string can be calculated by using in-built functions such as length(), size(), strlen() and also by loops (while and for).
#include<iostream>
#include<cstring>
using namespace std;
main() {
   string s = "Free Time Learn";
   char arr[] = "Free Time Learn";
   cout << s.length();
   cout << s.size();
   cout <<strlen(arr);
 
   char *c = arr;
   int count = 0;
   while(*c != '\0'){
      count++;
      c++;
   }
   cout << count;
   count = 0;
   for(int i = 0; arr[i] != '\0'; i++){
      count++;
   }
   cout << count;
}

Output : 

1515151515

A friend function in C++ is defined as a function that can access private, protected and public members of a class.
 
The friend function is declared using the friend keyword inside the body of the class.
 
Friend Function Syntax :
class className {
    ... .. ...
    friend returnType functionName(arguments);
    ... .. ...
}
By using the keyword, the ‘friend’ compiler knows that the given function is a friend function.
 
We declare friend function inside the body of a class, starting with the keyword friend to access the data. We use them when we need to operate between two different classes at the same time.
C++ compiler encodes the parameter types with function/method into a unique name. This process is called name mangling. The inverse process is called as demangling.
 
Example :
 
A::b(int, long) const is mangled as b__C3Ail’.
For a constructor, the method name is left out.
That is A:: A(int, long) const is mangled as C3Ail’.
Class is a blueprint of a project or problem to be solved and consists of variables and methods. These are called the members of the class. We cannot access methods or variables of the class on its own unless they are declared static.
 
In order to access the class members and put them to use, we should create an instance of a class which is called an Object. The class has an unlimited lifetime whereas an object has a limited lifespan only.
Method overloading is having functions with the same name but different argument lists. This is a form of compile-time polymorphism.
 
Method overriding comes into picture when we rewrite the method that is derived from a base class. Method overriding is used while dealing with run-time polymorphism or virtual functions.
“ISA” relationship usually exhibits inheritance as it implies that a class “ISA” specialized version of another class. For Example, An employee ISA person. That means an Employee class is inherited from the Person class.
 
Contrary to “ISA”, “HASA” relationship depicts that an entity may have another entity as its member or a class has another object embedded inside it.
 
So taking the same example of an Employee class, the way in which we associate the Salary class with the employee is not by inheriting it but by including or containing the Salary object inside the Employee class. “HASA” relationship is best exhibited by containment or aggregation.
* An internal iterator is implemented by the member functions of the class which has the iteration logic.
* An external iterator is implemented by a separate class which can be attached to the object which has iteration logic.
* The advantage of external iterator is that, many iterators can be made active simultaneously on the existing or same object.
1. Const : This variable means that if the memory is initialised once, it should not be altered by a program.

2. Volatile : This variable means that the value in the memory location can be altered even though nothing in the program code modifies the contents.

3. Mutable : This variable means that a particular member of a structure or class can be altered even if a particular structure variable, class or class member function is constant.
Deep copy : It involves using the contents of one object to create another instance of the same class. Here, the two objects may contain the same information but the target object will have its own buffers and resources. The destruction of either object will not affect the remaining objects.
 
Shallow copy : It involves copying the contents of one object into another instance of the same class. This creates a mirror image. The two objects share the same externally contained contents of the other object to be unpredictable.This happens because of the straight copying of references and pointers.
(a) Stack Area : This part of memory is used to store formal parameters, local variables, return addresses of function call etc.

(b) Program Code Area : This part of memory is used to store the object code of the program.

(c) Global Variable Section : This part of memory is used to store global variables defined in the program.

(d) Heap Area or Free Storage Pool : It consists of unallocated memory locations which are allocated dynamically during program execution using new operator.
Finding the location of a given element in a given data structure is called searching.
 
There are two types of search :
 
1. Linear Search : In this, the element to be searched is compared one by one with each element of given list, starting with first element. The process of comparisons remain continue until the element is not found or list gets exhausted.
 
2. Binary Search : It is another technique of searching an element in a given list in minimum possible comparisons. But for applying binary search on a list, there are two pre-conditions :

     (i)  The elements of list must be arranged either in ascending or descending order.
     (ii) The list must be of finite size and should be in form of linear array.
The Standard template library is used as a container to the templates which have been approved by the ANSI. It includes the standard C++ specification. It helps to construct programming in object oriented manner. It allows the use of pre-defined libraries for generic programming model. It allows faster execution of the programs and allow the user to use functions without even writing them.
We organize our C++ programs into different source files (.cpp, .cxx etc). When you consider a source file, at the preprocessing stage, some extra content may get added to the source code ( for example, the contents of header files included) and some content may get removed ( for example, the part of the code in the #ifdef of #ifndef block which resolve to false/0 based on the symbols defined). This effective content is called a translation unit. 
 
* Contents of source file
* Plus contents of files included directly or indirectly
* Minus source code lines ignored by any conditional pre processing directives ( the lines ignored by #ifdef,#ifndef etc)
The goto statement is used to alter the program execution sequence by transferring the control to some other part of the program.
 
The unconditional goto statement is used just to transfer the control from one part of the program to the other part without checking any condition. Normally, a good programmer will not prefer to use the unconditional goto statement in his program as it may lead to a very complicated problem like a never ending process.