C++ Basic Questions

PCBWay

1. what are C++ Modifier?How many types are there.

DRex Electronics

We have basic data types like int, char, double. A modifier is used to change the property of the base type.

There are four kinds of modifiers:

  • ​signed
  • ​unsigned ​
  • short
  • ​long

* All four modifiers can be applied to the int type

* char type allows only signed and unsigned modifiers

* double type can be used with the long modifier

2. How to call C functions from C++?

you can use ” extern “C” ” syntax.

Method 1:

extern “C” void foo(int);

Method 2:

extern “C”
{
void foo(int);

 

//more declarations…
}

3. What is the ellipsis catch handler in C++? Explain with an example.

Ellipsis catch handler is used to catch any unhandled exceptions. So it acts as a default handler when no other handlers are appropriate.

Example:

try
{
throw “Something”;
}

 

// the ellipsis catch handler:
catch(…)
{

​cout << “This is a default handler”;

}

4. Difference between reference and pointer in C++.

  • A pointer can be re-assigned any number of times while a reference cannot be re-assigned after binding.
  • Pointers can point nowhere (NULL), whereas a reference always refers to an object.
  • You can’t take the address of a reference like you can with pointers.
  • There’s no “reference arithmetic” (but you can take the address of an object pointed by a reference and do pointer arithmetic on it as in &obj + 5).
  • You can have pointers to pointers offering extra levels of indirection. Whereas references only offer one level of indirection.
  • References can be used in function parameters and return types.

5. Difference between exit abort and assert functions in C++

exit():

syntax:

void exit(int status_value);

exit() is used to terminate the calling function immediately without executing further processes.

exit() performs following operations.

* Flushes unwritten buffered data.
* Closes all open files.
* Removes temporary files.
* Returns an integer exit status to the operating system.

abort():

syntax:

void abort(void);

abort() may not close files that are open.

It may also not delete temporary files and may not flush stream buffer.

It does not call functions registered with atexit().

assert():

syntax :

void assert(int exp);

If expression evaluates to 0 (false), then the expression, source code filename, and line number are sent to the standard error, and then abort() function is called.

6. Difference between C Structure and C++ Structure?

C Structures

  • Structures in C cannot have member functions inside structure.
  • We cannot directly initialize structure data members in C but we can do it in C++.
  • In C, we need to use struct to declare a struct variable
  • C structures cannot have static members but is allowed in C++.
  • Structures in C cannot have constructor inside structure but Structures in C++ can have Constructor creation.
  • sizeof operator will generate 0 for an empty structure in C whereas 1 for an empty structure in C++.
  • C structures do not allow concept of Data hiding but is permitted in C++ as C++ is an object oriented language whereas C is not.
  • Structure in C can’t have static members, but C++ structure can have static members.

C++ Structures

  • Structures in C++ can have member functions along with data members.
  • Members of a class are private by default and members of a struct are public by default.
  • In C++, struct is not necessary.

7. Different types of linkages available in C++ explain.

There are 3 types of linkages in C++

extern linkage: variable is visible in all files

internal linkage: variable is visible in single file.

No linkage : identifiers can only be seen in the scope in which they are defined.

Additional Information

* global variable is external linkage
* const global variable is internal linkage
* extern const global variable is external linkage

8. What is stack unwinding in C++

  • As you create objects statically (on the stack as opposed to allocating them in the heap memory) and perform function calls, they are “stacked up”.
  • When a scope (anything delimited by { and }) is exited (by using return XXX;, reaching the end of the scope or throwing an exception) everything within that scope is destroyed (destructors are called for everything).
  • This process of destroying local objects and calling destructors is called stack unwinding.

9. Different ways to initialize a variable in C++

Method 1: Traditional Method using C notation.

int result = 10;

Method 2: Using the constructor notation.

int result (10);

10. Different parameter Passing Techniques in C/C++

1. Pass By Value :

#include <iostream>
using namespace std;

void func(int a, int b)
{
a += b;
printf(“In func, a = %d b = %d\n”, a, b);
}
int main(void)
{

int x = 5, y = 7;

// Passing parameters func(x, y);
printf(“In main, x = %d y = %d\n”, x, y);
return 0;

}

2. Pass by reference(aliasing)

#include <iostream>
using namespace std;

void swapnum(int* i, int* j)
{
int temp = *i;
*i = *j;
*j = temp;
}

int main(void)
{

int a = 10, b = 20;

// passing parameters swapnum(&a, &b);

printf(“a is %d and b is %d\n”, a, b);
return 0;

}

11. Is String primitive data type in C++?

No, it’s a class from STL (Standard template library).

12. We can have global and local variables with same name?

Yes, we can access with scope resolution operator i.e ::.

#include<iostream.h>
int num = 10;

int main()
{ ​
int num = 2; ​
cout<<”Global Variable num = “<<::num;
​cout<<”\nlocal Variable num = “<<num;
}

13. What is the difference between delete and delete[] in C++

“delete[]” is used to release the memory allocated to an array which was allocated using new[].

“delete” is used to release one chunk of memory which was allocated using new.

14. What is a Reference Variable in C++

A reference variable is an alias for already existing variable.

It means, the reference variable and the variable name, both point ot the same memory location.

Example:

int num1 =10;
int &num2 = num1;

15. what are default arguments in C++?

A default argument will be provided during the function declaration. If the caller function doesn’t provide the value for that argument, the compiler will automatically assign this default argument.

Example:

#include<iostream>
using namespace std;

int sum(int x, int y, int z=0)
{
return (x + y + z);
}

int main()
{
​// we did not assign 3rd argument, then compiler will take it as 0
cout << sum(101, 115) << endl;
cout << sum(101, 115, 25) << endl;
return 0;

}

16. what are storage class? List them .

Storage Class determines the life or scope of a variable.

There are 5 different storage class:

  1. Auto
  2. Static
  3. Extern
  4. Register
  5. Mutable

17. what is mutable storage class?

When you create an object of a class as constant, but you need to modify any one data member, then you need to declare that data member as mutable.

Example:

class A
{
public:
​A (int a, int b)
​{

​​x = a;
​​y = b;

​ ​} ​
mutable int x;
​int y;

};

int main()
{
​const A var1;
​var1.x = 35;

// var1.y = 25; // uncommenting this line will result in compiler error

}

18. What is Name Mangling in C++?

  • We know that C++ supports function overloading. It means, there can be more than one function with same name, but with different parameters.
  • But how does C++ distinguish between the functions when it generates the code?
  • It changes the name by additionally adding information about the arguments, this process is called as name mangling.

For example:

If the functions are declared as below:

int  fun (void) { return 1; }
int  fun (int)  { return 0; }

C++ can mangle the name as below:

int  __fun_v (void) { return 1; }
int  __fun_i (int)  { return 0; }

19. What is the difference between Method Overloading and Method Overriding in C++?

Method Overloading:

* Method overloading is having functions with the same name but different arguments

* This is a form of compile-time polymorphism.

Example:

void area(int a);
void area(int a, int b);

Method Overriding:

It is the redefinition of base class function in its derived class with same signature i.e return type and parameters.

It can only be done in derived class.

Example:

Class a
{
public:
virtual void display(){ cout << “hello”; }
}

Class b:public a
{
public:
void display(){ cout << “bye”;};

}

20. what operators cannot be overloaded?

?: (conditional)
. (member selection)
.* (member selection with pointer-to-member)
:: (scope resolution)
sizeof (object size information)
typeid (object type information)
static_cast (casting operator)

21. what are the uses of Scope resolution operator?

1) To access a global variable when there is a local variable with same name:

2) To define a function outside a class.

3) To access a class’s static variables.

4) In case of multiple Inheritance: If same variable name exists in two ancestor classes, we can use scope resolution operator to distinguish.

5) For namespace
std::cout << “Hello” << std::endl;

6) Refer to a class inside another class.

22. How can I modify my own C header files so it’s easier to #include them in C++ code?

  • If you are including a C header file that isn’t provided by the system, and if you are able to change the C header, you should strongly consider adding the extern “C” {…} logic inside the header to make it easier for C++ users to #include it into their C++ code.
  • Since a C compiler won’t understand the extern “C” construct, you must wrap the extern “C” { and } lines in an #ifdef so they won’t be seen by normal C compilers.

Example:

#ifdef __cplusplus
extern “C” {
#endif

//function prototype declarations

#ifdef __cplusplus
}
#endif

23. what kind of functions cannot be overloaded in C++?

1. Function declarations that differ only in the return type.

int foo()
{
return 10;
}

char foo()
{
return ‘a’;
}

2. Member function declarations with the same name and the name parameter-type-list cannot be overloaded if any of them is a static member function declaration.

class Test
{
static void fun(int i) {}
void fun(int i) {}
};

3. Two parameter declarations that differ only in their default arguments are equivalent.

int f ( int x, int y)
{
return x+10;
}

int f ( int x, int y = 10)
{
return x+y;
}

4.  Parameter declarations that differ only in the presence or absence of const and/or volatile are equivalent.

int f ( int x)
{
return x+10;
}

int f ( const int x)
{
return x+10;
}

5.  Parameter declarations that differ only in a pointer * versus an array [] are equivalent.

int fun(int *ptr);
int fun(int ptr[]); // redeclaration of fun(int *ptr)

24. Can main() be overloaded in C++?

Consider the below example:

#include <iostream>
using namespace std;
int main(int a)
{
cout << a << “\n”;
return 0;
}
int main(char *a)
{
cout << a << endl;
return 0;
}

int main(int a, int b)
{
cout << a << ” ” << b;
return 0;
}
int main()
{
main(3);
main(“C++”);
main(9, 6);
return 0;

}

If you compile it, it will throw an error.

To solve this, it is necessary to use class and declare the main as member function.

#include <iostream>
using namespace std;
class Test
{
public:
int main(int s)
{
cout << s << “\n”;
return 0;
}

int main(char *s)
{
cout << s << endl;
return 0;
}

int main(int s ,int m)
{
cout << s << ” ” << m;
return 0;
}
};

int main()
{
Test obj;
obj.main(3);
obj.main(“I love C++”);
obj.main(9, 6);
return 0;
}

This will work because, in C++ “main” is not a keyword.

25. Is it ok to write “void main()” or “main()” in C/C++?

void main() { /* … */ } is not there standard in C++

Only

int main() { /* … */ }
int main(int argc, char* argv[]) { /* … */ }

are valid standard in C++.

Point to be taken, that both of the functions return an int value.

The int returned by main() is a way for a program to return a value to “the system” that invokes it.

26. Difference between exit() and return() in C++

When you return from a function, destructor will be called.

When you exit from a function, destructors for locally scoped non-static objects are not called.

#include<iostream>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

class Test
{
public:
Test()
{
printf(“Inside Test’s Constructor\n”);
}

~Test()
{
printf(“Inside Test’s Destructor”);
}
};
int main()
{
Test t1;

 

// using exit(0) to exit from main
exit(0);
}

Output:

Inside Test’s Constructor

#include<iostream>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

class Test
{
public:
Test()
{
printf(“Inside Test’s Constructor\n”);
}

~Test()
{
printf(“Inside Test’s Destructor”);
}
};

int main()
{
Test t1;

return(0);
}

Output :

Inside Test’s Constructor
Inside Test’s Destructor

27 . How to print “Hello World” with empty or blank main in C++

Method 1:

By creating a global variable

#include <bits/stdc++.h>

int x = printf(“Hello World”);

int main()
{
// Blank
}

Method 2:

We can use Constructor in C++.

#include <iostream>
using namespace std;

class A {
public:
A() // Constructor
{
cout << “Hello World”;
}
};

A obj; // Create Object of class A

int main()
{
// Blank
}

28. Example for for_each loop

Syntax for for_each loop:

for_each (InputIterator first, InputIterator last, Function fn)

first : The beginning position from where function operations has to be executed.

last : This ending position till where function has to be executed.

fn : The 3rd argument is a function or an object function which operation would be applied to each element.

Example:

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

void myFun(int x)
{
cout << x << ” “;
}

struct myClass // object type function
{
void operator() (int x)
{
cout << x << ” “;
}
} obj1;

int main()
{
int arr[] = {1, 2, 4, 3};

// passing simple function for_each(arr, arr + 4, myFun);

cout << endl;

// passing object type function
​for_each(arr, arr + 4, obj1);
return 0;
}

Output:

1 2 4 3
1 2 4 3

29. Generate random numbers in C++

rand() is used to generate random numbers in C++.

srand() is used to set seed which is used by rand().

If we set the seed(1), then the output will be same on every program run.

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

int main()
{
srand(1);
for(int i=0; i<5; i++)
​​cout << rand() % 100 <<” “;
return 0;
}

Output:

83 6 74 23 65

To get different random number every time, then set srand(time(NULL)) should be used.

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;
int main()
{
srand(time(NULL));
for(int i=0; i<5; i++)
​​cout << rand() % 100 <<” “;
return 0;

}

Output:

34 62 53 67 98

Now for every run, we get different random number.

To get random number in specific range, then use below formula:

int min = 50;
int max = 150;
min + (rand() % (int)(max – min + 1))

30. Explain string class in C++

To use string class, include below header:
#include <string>

Below are the constructors available in C++ string class:
* string () : creates an empty string (“”)

* string ( other_string ) : creates a string identical to other_string * string ( other_string, position, count ) : creates a string that contains count characters from other_string, starting at position. If count is missing (only the first two arguments are given), all the characters from other_string, starting at position and going to the end of other_string, are included in the new string.

* string ( count, character ) : create a string containing character repeated count times

Constant Member Functions:

These functions do not modify the string.

unsigned int length () : returns the length of the string

unsigned int size () : returns the length of the string (i.e., same as the length function)

bool empty () : returns true if the string is empty, false otherwise

Operators Defined for string:

Assign =

————–

string s1;
string s2;

s1 = s2; // the contents of s2 is copied to s1

Append +=

————–

string s1( “abc” );
string s2( “def” );

s1 += s2; // s1 = “abcdef”

Concatenate +

————–

string s1( “abc” );
string s2( “def” );
string s3;

s3 = s1 + s2; // s3 = “abcdef”

Equality ==

————–

string s1( “abc” );
string s2( “def” );
string s3( “abc” );

bool flag1 = ( s1 == s2 ); // flag1 = false
bool flag2 = ( s1 == s3 ); // flag2 = true

Some of Member Functions available:

void swap ( other_string ) : swaps the contents of this string with the contents of other_string.

string & append ( other_string ) : appends other_string to this string, and returns a reference to the result string.

unsigned int find ( other_string, position ) : finds other_string inside this string and returns its position. If position is given, the search starts there in this string, otherwise it starts at the beginning of this string.

string substr ( position, count ) : returns the substring starting at position and of length count from this string

31. What are inline functions in C++?

If a function is made inline, the compiler places a copy of the code of that function at each point where the function is called at compile time.

If you make a function inline, you need to recompile the program, because compiler needs to all the code once again.

There are 2 ways to make a function inline.

Method 1:

Write the definition of member function inside the body of class declaration.

class MyClass
{
public:
​//an inline function
​string myCLassName()
​{
​​return “My Class”;
​}
};

Method 2:

Use “inline” keyword.

inline int Max(int a, int b)
{
return (a > b)? a : b;
}

32, Example program for enum in C++

Method 1: Declare enum variable while creating an enum.

#include<iostream>
using namespace std;

enum direction {
​​​East, ​​​
West,
​​​North,
​​​South ​​
}dir;
int main()
{
dir = East;
cout<<dir;
return 0;
}

Method 2: Declare enum variable.

#include<iostream>
using namespace std;

enum direction {
​​​East,
​​​West, ​​​
North,
​​​South
​​};

int main()
{
​direction dir;
dir = East;
cout<<dir;
return 0;
}

33. Example for Reference to Function

Consider you have a function as below:

int foo(double i)
{ ​
return 2;
}

To create a reference to a function you have to use the following syntax:

type (&identifier) (parameter list) = referenced function;

In our example, reference to a function can be created by:

int(&referenceToFunction)(double) = foo; and can be called by:

referenceToFunction(4.0);

34. Example for Reference as a Parameter of a Function

Consider the below function:

void negative(int& a)
{ ​

//make a as negative ​
a *= (-1);

}

Calling:

int k = 10;
cout << “k before function call ” << k << endl;
opposite(k);
cout << “k after function call ” << k << endl;

Output:

k before function call 10
k after function call -10

35. Explain Const function

A const or a constant member function can only read or retrieve the data members of the calling object without modifying them.

The syntax for defining a const member function is

return_type function_name (parameter_list) const
{

//body of the member function

}

Example:

#include<iostream>
using namespace std;

class Test
{
int value;
public:
Test(int v = 0) {value = v;}

int getValue() const {return value;}
};

int main()
{
Test t(20);
cout<<t.getValue();
return 0;
}

When a function is declared as const, it can be called on any type of object. Non-const functions can only be called by non-const objects.

36. Explain Static function

Static member functions are used to maintain a single copy of a class member function across various objects of the class.

Restrictions on static member functions are :

1. They can directly refer to other static members of the class.
2. Static member functions do not have this pointer.
3. Static member function cannot be virtual.

Example:

#include <iostream>
using namespace std;

class MyClass
{
static int i;
public:
static void init(int x)
{
i = x;
}
void show()
{
cout <<i; }
};

int MyClass::i;
int main()
{
MyClass::init(100); //initialize static variable i before creating object
MyClass x;
x.show();
return 0;

}

37. Guess the output of the program 1

#include<iostream>
using namespace std;

int &fun()
{
int x = 20;
return x;
}
int main()
{
fun() = 40;
cout << fun();
return 0;
}

Output:

Runtime error

Why?

Since we return reference to a local variable, the memory location becomes invalid after function call is over.

Might result in segmentation fault.

38. Guess the output of the program 2

#include<iostream>
using namespace std;
int &fun()
{
static int x = 110;
return x;
}
int main()
{
fun() = 130;
cout << fun();
return 0;
}

Output:

130

Why?

Notice that x is a static variable, the function call fun() = 130, modifies x to 130. Hence next call “cout << fun()” returns the modified value.

39. Guess the output of the program 3

#include<iostream>
using namespace std;
int main()
{
int x = 10;
int &ref = x;
ref = 120;
cout << “x = ” << x << endl ;
x = 130;
cout << “ref = ” << ref << endl;
return 0;
}

Output:

x = 120
ref = 130

Why?

ref is an alias of x. Hence changing one, will change other also.

40. Different ways to convert int to string in C++

1:

int a = 20;
char *intStr = itoa(a);
string str = string(intStr);

2:

int a = 12;
stringstream ss;
ss << a;
string str = ss.str();

operator << — add a string to the string stream object

3:

#include <string>

std::string s = std::to_string(452);

41. What is the “–>” operator in below code?

#include <stdio.h>
int main()
{
int x = 10;
while (x –> 0)
{
printf(“%d “, x);
}
}

–> is not an operator. It is in fact two separate operators, — and >.

The statement could be written as follows:

while( (x–) > 0 )

42. What is The Rule of Three?

If your class needs any of

a copy constructor,
an assignment operator,
or a destructor,

defined explicitly, then it is likely to need all three of them.

43. Why is “using namespace std;” considered bad practice?

Consider you are using two libraries called Foo and Bar:

using namespace foo;
using namespace bar;
You call Blah() from Foo and Qix() from Bar without problems.

Then you upgrade to a new version of Foo 2.0, and offer a function called Qix (). Now Both Foo 2.0 and Bar import Qix () into your global namespace.

This is going to take some effort to fix, especially if the function parameters happen to match.

But If you had used foo::Blah() and bar:: Qix (), then the introduction of foo:: Qix () would have been a non-event.

Constructor and Destructor Questions

44. What is the need for virtual destructors in C++

Deleting a derived class object using a pointer to a base class that has a non-virtual destructor results in undefined behaviour.

To correct this situation, the base class should be defined with a virtual destructor.

Example: Without virtual destructor

#include<iostream>

using namespace std;

class base
{
public:
​base()​
​{ ​​
cout<<“Constructor of base class \n”;
​}
​~base()
​{
​​cout<<“Destructor of base class \n”;
​}​
};

class derived: public base

{
public:
​derived()​ ​
{
​​cout<<“Constructor of derived class\n”;
​}
​~derived()
​{ ​​
cout<<“Destructor of derived class  \n”; ​
}
};
int main(void)
{
​derived *d = new derived();
​base *b = d;
​delete b;
​return 0;

}

Output:

Constructor of base class
Constructor of derived class
Destructor of base class

As you can see from the output above, destructor of derived class is not called. Hence making the base class destructor as “virtual” will make sure that object of derived class is destroyed properly.

Example: With virtual destructor

#include<iostream>

using namespace std;

class base
{
public:
​base()​
​{
​​cout<<“Constructor of base class \n”;
​} ​
virtual ~base()
​{ ​​
cout<<“Destructor of base class \n”;
​}​
};

class derived: public base
{
public:
​derived()​
​{ ​​
cout<<“Constructor of derived class\n”;
​}
​~derived() ​
{
​​cout<<“Destructor of derived class  \n”;
​}
};

int main(void)
{ ​
derived *d = new derived();
​base *b = d;
​delete b; ​
return 0;
}

Output:

Constructor of base class
Constructor of derived class
Destructor of derived class
Destructor of base class

45. What is a constructor, explain with an example

  • Constructor is a special type of member function whose name is same as class name.
  • Usually constructor is used to initialize a data member.
  • Constructors don’t have return type
  • A constructor is automatically called when an object is created.
  • If you don’t declare a constructor, compiler will automatically create one.

There are 2 type of constructor:

1. Default constructor:

These type of constructor will not accept any parameter. This constructor will be called automatically when an object is created.

#include <iostream>
using namespace std;

class construct
{
public:
int a;

// Default Constructor
construct()
{
a = 10;
}
};

int main()
{
construct c;
cout << “a: ” << c.a << endl
return 0;
}

2. Parameterized Constructors:

In these type of constructor, they will accept arguments.

These arguments will help in initializing the data members when objects are created.

Example:

#include <iostream>
using namespace std;

class Point {
private:
int x, y;

public:

// Parameterized Constructor
Point(int x1)
{
x = x1;
}

int getX()
{
return x;
}
};

int main()
{
// Constructor called
Point p1(10);

// Access values assigned by constructor
cout << “p1.x = ” << p1.getX();
return 0;

}

Whenever we define one or more Parameterized constructors for a class, a default constructor should also be explicitly defined as the compiler will not provide a default constructor in this case.

46. What is a copy constructor?

A copy constructor is a member function which initializes an object using another object of the same class.

Default constructor does only shallow copy.

Deep copy is possible only with user defined copy constructor.

Example:

#include <iostream>
using namespace std;

class A
{
public:
int x;

// parameterized constructor.
A(int a)
{
x=a;
}

// copy constructor
A(A &i)
{
x = i.x;
}
};

int main()
{ ​

// Calling the parameterized constructor.
​A a1(20);

​// Calling the copy constructor. ​
A a2(a1); ​
cout<<a2.x;
​return 0;
}

47. Can constructor be private in C++?

Yes, you can create a constructor a private.

But if you make a constructor of a class as private, that class cannot be instanciated.

But we have a workaround for it:

You can access it through friend class.

#include <iostream>
using namespace std;

// class A
class A
{
private:
A()
{
cout << “constructor of A\n”;
}
friend class B;
};

// class B, friend of class A
class B
{
public:
B()
{
A a1; cout << “constructor of B\n”;
}
};

int main(){
B b1;
return 0;
}

48. What is a destructor?

A destructor is a special member function that is used to delete the object.

When destructor will be called?

Destructor will be automatically called in below scenarios:

1. When object goes out of scope.
2. Delete operator is called
3. Program ends
4. block containing local variable is called.

Additional Points:

Destructors have same name as the class preceded by a tilde (~)
Destructors don’t take any argument and don’t return anything

Example:

#include <iostream>
using namespace std;
class HelloWorld
{
public:

//Constructor
HelloWorld()
{ cout<<“Constructor is called”<<endl;
}

//Destructor
~HelloWorld()
{
cout<<“Destructor is called”<<endl;
}

};

int main()
{
//Object created
HelloWorld obj;

return 0;
}

Output:

Constructor is called
Destructor is called

49. Can constructor be overloaded?

Yes constructor can be overloaded.

Overloaded constructor will have same name and different arguments.

Example:

#include <iostream>
using namespace std;

class construct
{
public:
​float area;
​// Constructor with no parameters ​
construct()
​{

​​area = 0;
​}

​// Constructor with two parameters
​construct(int a, int b)
​{
​​area = a * b;
​}
​void disp()
​{ ​​
cout<< area<< endl;
​}
};

int main()

{ ​

construct ctr1;
​construct ctr2( 20, 40);
​ctr1.disp();
​ctr2.disp(); ​
return 1;
}

Output:

0
800

50. Can destructor be overloaded? Give explanation.

  • No a destructor can never be overloaded in C++.
  • An overloaded destructor would mean that the destructor has taken arguments.
  • Since a destructor does not take arguments, it can never be overloaded.

51. What is shallow copy and deep copy?

  • Shallow Copy A shallow copy of an object copies all of the member field values.
  • This works well if the fields are values, but may not be what you want for fields that point to dynamically allocated memory.
  • The pointer will be copied. but the memory it points to will not be copied — the field in both the original object and the copy will then point to the same dynamically allocated memory.
  • The default copy constructor and assignment operator make shallow copies.

Deep Copy

  • A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields.
  • To make a deep copy, you must write a copy constructor and overload the assignment operator, otherwise the copy will point to the original, with disastrous consequences.
  • A class that requires deep copies generally needs:
  • A constructor to either make an initial allocation or set the pointer to NULL.
  • A destructor to delete the dynamically allocated memory.
  • A copy constructor to make a copy of the dynamically allocated memory.
  • An overloaded assignment operator to make a copy of the dynamically allocated memory.

52. Is it possible for a constructor to throw an error?

Throwing exceptions in the constructor is standard way of the error handling and is not an undefined behaviour.

If you throw in constructor it is assumed that an object was not initialized properly, so its destructor is not called.

53. What is a default constructor? Give an example

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.

Default constructors do not take any parameters.

If a default constructor is not provided by the programmer explicitly, then the compiler provides a implicit default constructor.

In that case, the default values of the variables are 0.

Example:

class X
{
public:
X();
// Default constructor with no arguments
X(int = 0);
// Default constructor with one default argument
X(int, int , int = 0);
// Constructor
};

54. When are copy constructor called?

A Copy Constructor may be called in following cases:

1. When an object of the class is returned by value.
2. When an object of the class is passed (to a function) by value as an argument. 3. When an object is constructed based on another object of the same class.

55. Is it possible to access private data members of a class without using a member or a friend function?

Yes, it is possible using pointers. See the following program as an example.

#include<iostream>
using namespace std;

class Test
{
private:
int data;
public:
Test()
{ ​
data = 0;
}

int getData()
{
​return data;
}

};

int main()
{
Test t;
int* ptr = (int*)&t;

*ptr = 20;

cout << t.getData();
return 0;
}

56. what is the order of constructor and destructor call during inheritance in C++

* Base class constructor will always be called in the derived class.

* Whenever you create a derived class object, base class constructor will be called first. * For multiple inheritance, base class constructor will be called in the order of inheritance.

* Destructor will be called in reverse order.

Example:

#include <iostream>
using namespace std;

// first base class
class Base_Class_1
{
public:

// first base class’s Constructor
Base_Class_1()
{
cout << “Inside first base class” << endl;
}
};

// second base class
class Base_Class_2
{
public:

// second base class’s Constructor
Base_Class_2()
{
cout << “Inside second base class” << endl;
}
};

// child class inherits Parent1 and Parent2
class Child : public Base_Class_1, public Base_Class_2
{
public:

// child class’s Constructor Child()
{
cout << “Inside child class” << endl;
}
};

int main()
{

// creating object of class Child Child obj1;
return 0;
}

Output:

Inside first base class
Inside second base class
Inside child class

57. Can a destructor be pure virtual in C++?

Yes, destructor can be virtual in C++.

Once you declare a destructor as pure virtual, the you must provide a function body for the pure virtual destructor.

Example:

#include <iostream>
using namespace std;
class Base
{
public:
virtual ~Base()=0;

// Pure virtual destructor
};

Base::~Base()
{
cout << “Pure virtual destructor from base class is called”;
}

class Derived : public Base
{
public:
~Derived()
{
cout << “~Derived() is executed\n”;

}
};

int main()
{
Base *b = new Derived();
delete b;
return 0;

}

Output:

~Derived() is executed
Pure virtual destructor from base class is called

58. Guess the output of the program 1

#include<iostream>
using namespace std;
class Point
{
public:
Point()
{ ​
cout << “Constructor called”;
}
};

int main()
{
Point p1, *p2;
return 0;
}

Output:

Constructor Called

Why?

Only one object p1 is constructed here. p2 is just a pointer variable, not an object

59. Guess the output of the program 2

#include<iostream>
using namespace std;
class myPoint
{
public:
myPoint()
{
cout << “Normal Constructor calledn”;
}

myPoint(const myPoint &t)
{
cout << “Copy constructor calledn”;
}
};

int main()
{
myPoint *t1, *t2;
t1 = new myPoint();
t2 = new myPoint(*t1);
myPoint t3 = *t1;
myPoint t4;
t4 = t3;
return 0;

}

Output:

Normal Constructor called
Copy Constructor called
Copy Constructor called
Normal Constructor called

60. Guess the output of the program 3

using namespace std;

class X
{
public:
int x;
};

int main()
{
X a = {20};
X b = a;
cout << a.x << ” ” << b.x; return 0;
}

Output:

20 20

Why?

If we don’t write our own copy constructor, then compiler creates a default copy constructor which assigns data members one object to other object.

61. Guess the output of the program 4

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

class Test
{
public:
Test()
{ cout << “Constructor called”;
}
};

int main()
{
Test *t = (Test *) malloc(sizeof(Test));
return 0;
}

Output

<EMPTY>

Why?

malloc() doesn’t call constructor. If replace malloc() with new, the constructor is called.

62. Guess the output of the program 5

#include <iostream>
using namespace std;

class Test
{
public:
Test()
{
cout << “Hello from Test() “;
}
}a;

int main()
{
cout << “Main Started “;
return 0;

}

Output:

Hello from Test() Main Started

Why?

There is global object ‘a’ which is constructed before the main functions starts. Hence the constructor for a is called first, then main()’ execution begins.

63. Guess the output of the program 6

#include<iostream>
using namespace std;

class Test
{
public:
Test();
};

Test::Test()

{
cout << ” Constructor Called. “;
}
void fun()
{
static Test t1;
}

int main()
{
cout << ” Before fun() called. “;
fun();
fun();
cout << ” After fun() called. “;
return 0;

}

Output:

Constructor Called.
Before fun() called.
After fun() called.

Why?

The object “t” is static in fun(), so constructor is called only once.

64. Copy constructor vs assignment operator in C++

Copy Constructor

  • The copy constructor is an overloaded constructor.
  • The copy constructor initializes the new object with an already existing object.

class_name(cont class_name &object_name)
{
//body of the constructor
}

  • Both the target object and the initializing object shares the different memory locations.
  • If you do not define any copy constructor in the program, C++ compiler implicitly provides one.

Assignment Operator

  • The assignment operator is a bitwise operator.
  • The assignment operator assigns the value of one object to another object both of which are already in existence.

class_name Ob1, Ob2;
Ob2=Ob1;

  • Both the target object and the initializing object shares same allocated memory.
  • If you do not overload the “=” operator, then a bitwise copy will be made.

65. What is conversion constructor in C++?

  • A class has a constructor which can be called with a single argument, then this constructor becomes conversion constructor.
  • Such a constructor allows automatic conversion to the class being constructed.

#include<iostream>

using namespace std;
class Test
{
private:
int a;
public:
Test(int i) {a = i;}
void show() { cout<<” a = “<<a<<endl; }
};

int main()
{
Test t(20);
t.show();
t = 30;
t.show();
return 0;

}

Output:

a = 20
a = 30

More example:

class MyClass
{
public:
int a, b;
MyClass( int i ) {}
MyClass( const char* n, int k = 0 ) {}
MyClass( MyClass& obj ) {}
}

int main()
{
MyClass M = 1 ;
// which is an alternative to
MyClass M = MyClass(1) ;

MyClass M = “super” ;
// which is an alternative to
MyClass M = MyClass(“super”, 0) ;
// or
MyClass M = MyClass(“super”) ;
}

66. Passing a vector to constructor in C++

When class member is a vector object, we can simply assign in constructor.

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

class MyClass
{
​vector<int> vec;
public: ​
MyClass(vector<int> v)
​{ ​ vec = v;
​} ​
void print() ​
{ ​​
for (int i = 0; i < vec.size(); i++) ​​​
cout << vec[i] << ” “;
​}
};

int main()
{
​vector<int> vec;
​for (int i = 1; i <= 5; i++) ​​
vec.push_back(i);

​MyClass obj(vec);

​obj.print();
​return 0;
}

67. Can destructor be private?

Yes. It can be private.

But if you create an object it will throw an error.

Example:

#include <iostream>
using namespace std;

class Test
{
private:
~Test() {}
};
int main()
{
Test t;//error
}

But if you create an object by using new operator, then compiler will not throw an error. As it will be programmers responsibility to delete the dynamically allocated object.

#include <iostream>
using namespace std;

class Test
{
private:
~Test() {}
};
int main()
{
Test* t = new Test; // No Error

}

68. Would destructor will be called in below program?

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

class a
{
public :
~a()
{
cout << “destructor”;
}
};
int main()
{
vector <a*> *v1  = new vector<a*>;
return 0;
}

Ans: No

Why?

Deleting dynamically allocated objects is not compiler’s job. If user doesn’t call “delete ptr” explicitly, the destructor wouldn’t be called.

69. what is explicit constructor in C++

We knew about conversion constructor.

But in some cases we don’t want implicit conversion to take place.

Consider the example below:

Suppose, you have a class String:

class String
{
public:
String(int n);
// allocate n bytes to the String object
String(const char *p); // initializes object with char *p
};

Now, if you try:

  • String mystring = ‘x’;
    The character ‘x’ will be implicitly converted to int and then the String(int) constructor will be called.
  • But, this is not what the user might have intended. So, to prevent such conditions, we shall define the constructor as explicit:

class String
{
public:
explicit String (int n);//allocate n bytes
String(const char *p); // initialize sobject with string p
};

Virtual Functions Questions

70. What are pure virtual functions?

Pure virtual functions are also called as abstract classes in C++.

Below shows how to create a pure virtual function:

// Pure Virtual Function
virtual void myFunc() = 0;

A pure virtual function is implemented by classes which are derived from a Abstract class.

Complete example:

#include<iostream>
using namespace std;

class Base
{
public:
​virtual void fun() = 0;
};

class Derived: public Base
{
public:
​void fun()
{ ​
cout << “fun() called”;
}
};

int main(void)
{
​Derived d;
​d.fun();
​return 0;
}

Output:

fun() called

Important points to remember for pure virtual functions:

1. A class is abstract if it has at least one pure virtual function.
2. You cannot create an object for abstract class.
3. If we do not override the pure virtual function in derived class, then derived class also becomes abstract class.
4. An abstract class can have constructors.

71. What are vtables and how they are created?

  • To implement virtual functions, C++ uses a special form of late binding known as the virtual table or vTable.
  • The virtual table is a lookup table of functions used to resolve function calls in a dynamic/late binding manner.
  • Every class that uses virtual functions (or is derived from a class that uses virtual functions) is given its own virtual table.
  • This table is simply a static array that the compiler creates at compile time. A virtual table contains one entry for each virtual function that can be called by objects of the class.
  • Each entry in this vTable is simply a Function Pointer that points to the most-derived function accessible by that class ie the most Base Class.
  • The compiler also adds a hidden pointer to the base class, which we will call *__vPtr.
  • __vPtr is set (automatically) when a class instance is created so that it points to the virtual table for that class. *__vPtr is inherited by derived classes

72. What are virtual functions?

Consider the example below:

#include<iostream>
using namespace std;

class base
{
public:
void print ()
{ ​
cout<< “In base class” <<endl;
}

};

class derived:public base
{
public:
void print ()
{
​cout<< “In derived class” <<endl;
}

};

int main()
{
base *bptr;
derived d;
bptr = &d;
bptr->print();
}

Output:

In base class

As you can see from the output, when we try to access derived class print function through base class pointer, base class print() will be called. This is not the expected result.

Why?

Because we have re-defined “print()” in the derived class, the compiler is binding the “print()” in compile time.

To make it as a runtime polymorphism, we need to declare the base class function as “virtual”, thus making the print() to work as a run time polymorphism.

Example:

#include<iostream>
using namespace std;

class base
{
public:
void print ()
{ ​cout<< “In base class” <<endl;
}

};

class derived:public base
{
public:
void print ()
{ ​
cout<< “In derived class” <<endl;
}

};

int main()
{
base *bptr;
derived d;
bptr = &d;
bptr->print();
}

Output:

In derived class

Below are some rules for virtual polymorphism:

Virtual functions cannot be static and also cannot be a friend function of another class.

Virtual functions should be accessed using pointer or reference of base class type to achieve run time polymorphism.

The prototype of virtual functions should be same in base as well as derived class.

73. what will be the output of the below program – 1 ?

#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();
Base &br = *bp;
br.show();
return 0;

}

Output:

In Derived
In Derived

Why?

As show() is made as virtual, hence while calling, it is called according to the type of object being pointed, rather than the type of pointer or reference.

74. what will be the output of the below program – 2 ?

#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, b;
Derived d;
bp = &d;
bp->show();
bp = &b;
bp->show();
return 0;
}

Output:

In Derived
In Base

75. what will be the output of the below program – 3 ?

#include<iostream>
using namespace std;

class MyClass
{
public:
virtual void show() = 0;
};

int main(void)
{
MyClass b;
MyClass *bp;
return 0;
}

Output:

Error at “MyClass b;”.

Why?

Since MyClass has a pure virtual function, it becomes an abstract class and hence an instance of it cannot be created.

Hence there is an error in line “MyClass b”.

Note that there is no error in line “MyClass *bp;”. We can have pointers or references of abstract classes.

76. what will be the output of the below program – 4 ?

#include<iostream>
using namespace std;

class Base
{
public:
virtual void show() = 0;
};

class Derived : public Base { };

int main(void)
{
Derived d;
return 0;
}

Output:

Error at the line “Derived d;”

77. what will be the output of the below program – 5 ?

#include<iostream>
using namespace std;

class Base
{
public: ​Base()
{ ​
cout<<“Constructor: Base”<<endl;
}
virtual ~Base()
{ ​
cout<<“Destructor : Base”<<endl;
}
};
class Derived: public Base
{
public: ​Derived()
{ ​
cout<<“Constructor: Derived”<<endl;
} ​
~Derived()
{
​cout<<“Destructor : Derived”<<endl;
}
};
int main()
{
​Base *base = new Derived();
​delete base; ​
return 0;
}

Output:

Constructor: Base
Constructor: Derived
Destructor : Derived
Destructor : Base

Why?

As we have made destructor as virtual, derived class destructor will call base class destructor.

78. what will be the output of the below program – 6 ?

#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->Base::show();
return 0;

}

Output:

In Base

Why?

Note the line “bp->Base::show();”. We can use base class show(), by using scopr resolution operator. “::”

79. Can static functions be virtual in C++?

No, static functions cannot be virtual.

#include<iostream>

using namespace std;

class MyCLass
{
public: // Error: Virtual member functions cannot be static
virtual static void myFun()
{

 

}

};

static member function cannot be const and volatile.

#include<iostream>

using namespace std;

class MyCLass
{
public:
// Error: Static member function cannot be const
static void myFun() const
{

 

}
};

80. Is it possible to call a virtual function inside a non-virtual function in C++?

Consider the example below:

#include <iostream>
using namespace std;

class Base
{
public:
virtual void print()
{
cout << “Base class print function \n”;
}
void invoke()
{
cout << “Base class invoke function \n”; this -> print();
}
};

class Derived: public Base
{
public:
void print()
{
cout << “Derived class print function \n” ;
}
void invoke()
{
cout << “Derived class invoke function \n”;
this -> print(); // called under non – virtual function
}
};

int main()
{
Base *b = new Derived;
b -> invoke();
return 0;

}

Output:

Base class invoke function
Derived class print function

From the above output we can infer that polymorphic behaviour works even when a virtual function is called inside a non-virtual function.

81. what are virtual base class in C++ ?

When a derived class has multiple copies of base class, compiler will throw an error because derived class could have duplicate sets of members inherited from a single base class.

To resolve this error, we need to use virtual base class.

Program with error:

#include<iostream.h>
#include<conio.h>

class ClassA
{
public:
int a;
};

class ClassB : public ClassA
{
public:
int b;
};

class ClassC : public ClassA
{
public: int c;
};

class ClassD : public ClassB, public ClassC
{
public:
int d;
};

void main()
{
ClassD obj;

obj.a = 10; //Statement 1, Error occur
obj.b = 20;
obj.c = 30;
obj.d = 40;

cout<< “\n A : “<< obj.a;
cout<< “\n B : “<< obj.b;
cout<< “\n C : “<< obj.c;
cout<< “\n D : “<< obj.d;

}

ClassB & ClassC inherit ClassA, they both have single copy of ClassA. But ClassD inherit both ClassB & ClassC, hence ClassD have two copies of ClassA, one from ClassB and another from ClassC.

To resolve this, we use virtual base class as below:

#include<iostream.h>
#include<conio.h>

class ClassA
{
public:
int a;
};

class ClassB : virtual public ClassA
{
public:
int b;
};

class ClassC : virtual public ClassA
{
public:
int c;
};

class ClassD : public ClassB, public ClassC
{
public:
int d;
};

void main()
{
ClassD obj;

obj.a = 10;
obj.b = 20;
obj.c = 30;
obj.d = 40;

cout<< “\n A : “<< obj.a;
cout<< “\n B : “<< obj.b;
cout<< “\n C : “<< obj.c;
cout<< “\n D : “<< obj.d;

}

82. Explain few points on Virtual Table.

  • All the classes that have a virtual function, or any class derived from the base class, will have its own virtual table.
  • The table will be setup by compiler at compile time.
  • Virtual table contains one entry as a function pointer for each virtual function that can be called by objects of the class.

83. Explain few points on _vptr

  • vtable pointer or _vptr, is a hidden pointer added by the Compiler to the base class.
  • This pointer is pointing to the virtual table of that particular class.
  • _vptr is inherited to all the derived classes.
  • Each object of a class with virtual functions stores this_vptr.

Object Oriented Programming Questions

84. What is diamond problem in C++ and how to solve it?

The diamond problem occurs when two super classes of a class have a common base class.

Consider below program:

class A
{

​void display()
​{

​​//some code

​}

}

class B : public A
{ ​

void display()
​{ ​​

//some code

​}

}

class C : public A
{ ​

void display()
​{ ​​

//some code

​}

}

class D : public B, public C{
​//contains two display() functions
}

If we call display() function using class D object then ambiguity occurs because compiler gets confused that whether it should call display() that came from class B or from class C.

How to Solve Diamond Problem in C++?

We can remove diamond problem by using virtual keyword.

class A
{
​void display()
​{ ​​

//some code ​

}

}

class B : virtual public A
{

​void display()
​{

​​//some code

​}

}

class C : virtual public A
{

​void display()
​{ ​​

//some code

​}

}

class D : public B, public C
{

​//contains one display() functions

}

85. What is the difference between Local Variables, Instance Variables and Static Variables in C++

Local Variables :

  • Variable defined within a block or method or constructor is called local variable.
  • These variable are created when the block in entered or the function is called and destroyed after exiting from the block or when the call returns from the function.
  • The scope of these variables exists only within the block in which the variable is declared.

Instance Variables :

  • Instance variables are non-static variables and are declared in a class outside any method, constructor or block.
  • As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.
  • Instance Variable can be accessed only by creating objects.

Static Variables

  • Static variables are also known as Class variables.
  • Static variable can only have one copy of a static variable per class irrespective of how many objects we create.
  • Initialization of Static Variable is not Mandatory. Its default value is 0
  • To access static variables, we can simply access the variable as class_name::variable_name;

86. Can a static function access non-static member variables of class?  Give reason.

  • No, Static function of a class in C++ cannot access non-static variables.
  • It can access static variable only.
  • Static function is not associated with class object, means without object using class name only it can be called.
  • whereas non-static variables are associated with objects.
  • Every object has its own copy of non-static variable.
  • Since, static function does not know about object, so, it is impossible for a static function to know on which class object or class instance it is being called.

87. Static function has “this” pointer?

  • No static function will not have this pointer.
  • Whenever we call a class non-static member function using class object then THIS pointer is also passed to the function as a parameter internally and this is why a non-static member function of a class know that on which class object it is being called in case of multiple objects creation of the class.
  • Static function of a class is not associated with class object. So, THIS pointer is not passed to a static function as an internal parameter. So, a static function does not understand THIS pointer inside its body.

88. what is inheritance? List different types of it. Does C++ support Multilevel and Multiple Inheritances?

  • Inheritance is a concept where a child class will acquire the properties [data members] and functionality [member functions] of a parent class.
  • Child Class: A class that inherits another class is called as child class.
  • Parent Class: The class that is being inherited is called as parent class.

Example:

#include <iostream>
using namespace std;
class Account
{
public:
float salary = 90000;
};
class Programmer: public Account
{
public:
float bonus = 40000;
};
int main(void)
{
Programmer p1;
cout<<“Salary: “<<p1.salary<<endl;
cout<<“Bonus: “<<p1.bonus<<endl;
return 0;
}

C++ supports five types of inheritance:

  • Single inheritance
  • Multiple inheritance
  • Hierarchical inheritance
  • Multilevel inheritance
  • Hybrid inheritance

Yes, C supports both support Multilevel and Multiple Inheritances.

89. what is Single inheritance ? Explain with an example

A derived class is inherited from only one base class is called as single inheritance.

Example:

#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout<<“Constructor of A class”<<endl;
}
};
class B: public A
{
public: B()
{
cout<<“Constructor of B class”;
}
};
int main()
{
//Creating object of class B
B obj;
return 0;
}

90.What is Multiple inheritance?

Explain with an example In this type of inheritance, a class can inherit more than one class. It means that in this type of inheritance a single child class can have multiple parent classes.

Example:

#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout<<“Constructor of A class”<<endl;
}
};
class B
{
public:
B()
{
cout<<“Constructor of B class”<<endl;
}
};
class C: public A, public B
{
public:
C()
{
cout<<“Constructor of C class”<<endl;
}
};
int main()
{
C obj;
return 0;
}

Output:

Constructor of A class
Constructor of B class
Constructor of C class

91. What is Hierarchical inheritance? Explain with an example

In this type of inheritance, one parent class has more than one child class.

Example:

#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout<<“Constructor of A class”<<endl;
}
};
class B: public A
{
public:
B()
{
cout<<“Constructor of B class”<<endl;
}
};
class C: public A
{
public:
C()
{
cout<<“Constructor of C class”<<endl;
}
};
int main()
{
C obj;
return 0;
}

Output:

Constructor of A class
Constructor of C class

92. What is Multilevel inheritance? Explain with an example

using namespace std;
class A
{
public:
A()
{
cout<<“Constructor of A class”<<endl;
}
};
class B: public A
{
public:
B()
{
cout<<“Constructor of B class”<<endl;
}
};
class C: public B
{
public:
C()
{
cout<<“Constructor of C class”<<endl;
}
};
int main()
{
//Creating object of class C
C obj;
return 0;
}

Output:

Constructor of A class
Constructor of B class
Constructor of C class

93. What is Hybrid inheritance? Explain with an example

Hybrid inheritance is a combination of more than one type of inheritance.

Example:

#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout<<“Constructor of A class”<<endl;
}
};
class B : public A
{
public:
B()
{
cout<<“Constructor of B class”<<endl;
}
};
class C
{
public:
C()
{
cout<<“Constructor of C class”<<endl;
}
};
class D : public B, public C   //D is derived from class B and class C
{
public:
D()
{
cout<<“Constructor of A class”<<endl;
}
};
int main()
{
D obj1;
//object of derived class D

return 0;
} //end of program

94. What is a namespace in C++? Explain with an example.

Namespace is used to prevent name conflicts.

Example:

namespace foo
{
class bar
{

//define it

};
}

namespace baz
{
class bar
{
// define it
};
}

As you can see above we have two classes name bar, that are completely different and separate thanks to the namespacing.

Symbols declared inside a namespace block are placed in a named scope that prevents them from being mistaken for identically-named symbols in other scopes.

95. Is it possible to create unnamed namespace?

Yes, it is possible to create unnamed namespace.

The name will be assigned by compiler.

The unnamed namespaces you have created will only be accessible within the file you created it in.

Example:

#include <iostream>
using namespace std;

// unnamed namespace declaration
namespace
{
int num = 30;
}

int main()
{
cout << num << “\n”;
return 0;

}

96. What is a class in C++

  • Class is a user defined data type
  • To use a class you need to create an object
  • Class can be considered as a blueprint. You can see what a class contains, but you cannot use it until you create an object.

Example of a class:

class myClass

{

public:

​int data_memeber_1;

​double data_memeber_2;

​void member_function()

​{

// code to drive the car ​

}

};

97. What are abstract class?

A class that cannot be instantiated and is usually implemented as a class that has one or more pure virtual (abstract) functions.

class AbstractClass
{
public:
virtual void AbstractMemberFunction() = 0; // Pure virtual function makes this class Abstract class.
virtual void NonAbstractMemberFunction1(); // Virtual function.

void NonAbstractMemberFunction2();
};

98. What is an object in C++

An object is created from a class.

An object is an instance of a class.

class MyClass
{
public:
int myNum; // Attribute (int variable)

};

int main()
{
MyClass myObj;  // object of MyClass

myObj.myNum = 15;

cout << myObj.myNum << “\n”;

return 0;
}

99. What is polymorphism? What are it’s different forms explain with code.

  • Polymorphism means many forms.
  • In C++ context, polymorphism means single function with same name, behave differently in different contexts.

For example, the + (plus) operator in C++:

4 + 5 <– integer addition

3.14 + 2.0  <– floating point addition

s1 + “bar”  <– string concatenation!

There are 2 types of Polymorphism.

1. Compile Time Polymorphism:

This is also known as static (or early) binding.

  • ​​Function Overloading
    ​​
  • Operator Overloading

Function Overloading Example:

#include <iostream>
using namespace std;
class Add
{
public:
int sum(int num1, int num2)
{
return num1+num2;
}
int sum(int num1, int num2, int num3)
{
return num1+num2+num3;
}
};
int main()
{
Add obj;
//This will call the first function
cout<<“Output: “<<obj.sum(10, 20)<<endl;
//This will call the second function
cout<<“Output: “<<obj.sum(11, 22, 33);
return 0;
}

2. Run time polymorphism:

This is also known as dynamic (or late) binding. ​Virtual Functions

#include <bits/stdc++.h>
using namespace std;

class super
{
public:
virtual void print ()
{
cout<< “print super class” <<endl;
}

void show ()
{
cout<< “show super class” <<endl;
}
};

class derived:public super
{
public:
void print ()
{
cout<< “print derived class” <<endl;
}

void show ()
{
cout<< “show derived class” <<endl;
}
}; /

/main function
int main()
{
super *sPtr;
derived d;
sPtr = &d;

//virtual function, binded at runtime (Runtime polymorphism)
sPtr->print();

// Non-virtual function, binded at compile time
sPtr->show();
return 0;
}

100. Example for -> Operator with structure

struct Point
{
int x;
int y;
};

Point* p; // declare pointer to a Point struct

p = new Point; // dynamically allocate a Point
p->x = 12;  // set the field values.
p->y = 34;

101. What is encapsulation, explain with an example

Encapsulation is a process of combining data members and functions in a single unit called class.

This is to prevent the access to the data directly, the access to them is provided through the functions of the class.

How Encapsulation is achieved in a class

To do this:

1) Make all the data members private.

2) Create public setter and getter functions for each data member in such a way that the set function set the value of data member and get function get the value of data member.

#include<iostream>
using namespace std;

class ExampleEncap
{
private:

int num;
char ch;

public:

int getNum()const
{
return num;
}
char getCh() const
{
return ch;
}

void setNum(int num)
{
this->num = num;
}
void setCh(char ch)
{
this->ch = ch;
}
};
int main()
{
ExampleEncap obj;
obj.setNum(100);
obj.setCh(‘A’);
cout<<obj.getNum()<<endl;
cout<<obj.getCh()<<endl;
return 0;
}

102. What is Data Abstraction, explain with an example.

Data Abstraction is a process of providing only the essential details to the outside world and hiding the internal details .

Data Abstraction is a programming technique that depends on the separation of the interface and implementation details of the program.

Abstraction using Classes: We can implement Abstraction in C++ using classes. Class helps us to group data members and member functions using available access specifiers.

Abstraction in Header files: One more type of abstraction in C++ can be header files. For example, consider the pow() method present in math.h header file

103. What are different types of storage classes, explain each of the storage classes in c++

There are 5 storage classes available in C++

  • auto
  • register
  • static
  • extern
  • mutable

auto Storage Class:

The auto storage class is the default storage class for all local variables.

{
int mount;
auto int month;
}

register Storage Class:

The register storage class is used to define local variables that should be stored in a register instead of RAM.

{
register int miles;
}

static Storage Class:

The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope.

static int count = 10; /* Global variable */

extern Storage Class:

The extern storage class is used to give a reference of a global variable that is visible to ALL the program files.

extern int count;

mutable Storage Class:

mutable storage class is applicable to only class data members.

If a data member of a class is declared as mutable, then it can be modified by an object which is declared as constant.

104. What are different types of access specifiers available in C++

Below are different access specifiers available in C++

Public: Data members and functions are accessible outside the class.

Private: Data members and functions cannot be accessed outside the class. The exception is the usage of a friend class.

Protected: Data members and functions are accessible only to the derived classes.

105. What is a scope resolution operator?

In C++, scope resolution operator is :: is used for following purposes.

  • To access a global variable when there is a local variable with same name:
  • To define a function outside a class.
  • To access a class’s static variables. In case of multiple Inheritance, if same variable name exists in two ancestor classes, we can use scope resolution operator to distinguish.
  • For namespace
  • Refer to a class inside another class: ​

Example: outside::inside B;

106. Example for Nested Classes in C++

A class which is declared in another enclosing class is called as Nested Classes.

Example:

#include<iostream>

using namespace std;

class OuterClass

{
private:
int x;

class NestedClass
{
int y;
void NestedFun(Enclosing *e)
{
cout<<e->x;
}
};
};

int main()
{

}

107. Explain IS-A and HAS-A relationship in inheritance

“IS A” : Establishes relation between related objects. You can use inheritance to establish the relation.

“HAS A”: Defines a capability for possibly unrelated objects. You can use interface to define the capability.

Example:

A car is-a vehicle
A car has-a steering wheel

108. Difference between C++ Struct and C++ class

In structure have a by default public. In class have a by default private.

Structure cannot be inherited. But class can be inherit.

There is no data hiding features comes with structures. Classes do, private, protected and public.

A structure can’t be abstract, a class can.

A structure is a value type, while a class is a reference type.

A structure is contain only data member , but class contain data member and member function.

In a Structure we can’t initialise the value to the variable but in class variable we assign the values.

Structure are value type, They are stored as a stack on memory. whereas class are reference type. They are stored as heap on memory.

109. what is meant by Dynamic Constructor in C++

Allocation of memory is done dynamically using dynamic memory allocator new in a constructor, it is known as dynamic constructor.

#include <iostream>
using namespace std;

class MyClass
{
const char* p;

public:
// default constructor
MyClass()
{
// allocating memory at run time
p = new char[6];
p = “hello”;
}

void display()
{
cout << p << endl;
}
};

int main()
{
MyClass obj = new MyClass();
obj.display();
}

110. How to access static member of a class? Give example

By using scope resolution operator.

#include <iostream>
using namespace std;
class A
{
public:
static int x;
static int getX() {return x;} // static member function
};

int A::x; // static member variable

int main()
{
A::x = 100;
cout<<A::getX();
return 0;
}

111. List few points about static member variable

• Belongs to the whole class, and there is only one of it, regardless of the number of objects.

• Must be defined and initialized outside of any function, like a global variable.

• It can be accessed by any member function of the class.

• Normally, it is accessed with the class scope operator. If it is private, use a static member function to read or write it.

112. List few points about static member function.

• Is like an ordinary non-member function, but its scope is the class.

• It can access all members of an object in its class, but only if you make the object available, such as in a parameter – there is no “this” object.

• Normally, it is called with the class scope operator.

113. How to do Constructor Delegation in C++

Sometimes it is useful for a constructor to be able to call another constructor of the same class.

This feature, called Constructor Delegation, was introduced in C++ 11.

Consider below class:

class A
{
int x, y, z;

public:
A()
{
x = 0;
y = 0;
z = 0;
}
A(int z)
{
// The below two lines are redundant
x = 0;
y = 0;
this->z = z;
}
};

Hence C++, allows us to eliminate redundant code with the help of constructor delegation, by allowing to call a constructor by placing it in the initializer list of other constructors.

class A
{
int x, y, z;

public:
A()
{
x = 0;
y = 0;
z = 0;
}

// Constructor delegation
A(int z) : A()
{
this->z = z; // Only update z
}
};

114. what is the reason that we should write our own copy constructor?

If we don’t provide any  implementation of copy constructor C++ compiler provide default copy constructor.

The problem with default copy constructor is that When we have members which dynamically gets initialized at run time, default copy constructor copies this members with address of dynamically allocated memory and not real copy of this memory.

Now both the objects points to the same memory and changes in one reflects in another object.

Hence, in such cases, we should always write our own copy constructor

115. How to prevent Object Copy in C++ ?

Keeping the Copy Constructor and Copy assignment operator as private in the class

#include <iostream>
using namespace std;

class Base {
int x;
public:
Base() { }
Base(int y): x(y) { }
private:

// Copy constructor
Base(const Base& obj) : x(obj.x) { }

// copy assignment operator
Base& operator=(const Base& tmp_obj)
{
x = tmp_obj.x;
return *this;
}
};
int main()
{ Base b1(10);
Base b2(b1); // error: calls copy constructor
b2 = b1; //  error: calls copy assignment operator
return 0;
}

116. Is it possible to create nested namespace in C++?

Yes it is possible to create nested namespace.

Example:

namespace X
{ ​
void foo()
​{ ​​
cout << “foo from X is called” << endl;
​} ​
namespace Y
​{
​​void foo() ​​
{ ​​​cout << “foo from Y is called” << endl;
​​} ​

}

}

Calling:
X::Y::foo();

117. Is it possible to create an alias for namespace?

Yes it is possible to create.

Syntax:

Namespace newName = oldName .

namespace newName = old_name;

newName::myFunc()

118. List down all the concepts of OOP.

Below are the concepts that are available in OOP

  • Classes.
  • Objects.
  • Encapsulation.
  • Polymorphism.
  • Inheritance.
  • Abstraction.
  • Overloading.
  • Error handling.

Classes: They are user defined data type.

Objects: They are instance of a class.

Encapsulation: Data members and member functions are encapsulated to restrict the access some of the object’s data from outside of class.

Polymorphism: It is a concept where a member function with same name will behave differently on different situations.

Inheritance: This concept is used to inherit some properties from base class to derived class.

Abstraction: In this concept consists in hiding the details of processing and representing only necessary information and result outside the class.

Error handling: In this concept, we handle the errors that can appear run time.

119. Example for Abstraction in C++

Abstraction is a concept where we show only relevant details and hide the complex details from the user.

Below is the example for abstraction:

Usually in OOP abstraction is achieved for data members, by making them private and modifying them with the help of getters and setters.

#include <iostream>
using namespace std;

class AbstractionExample
{
private:
int num;

public:
void setNum(int n)
{
num = n;
}

void getNum()
{
cout<<“Numbers is: “<<num<< endl;
}
};

int main()

{
AbstractionExample obj;
obj.setMyValues(100);
obj.getMyValues();
return 0;
}

120. Explain upcasting and downcasting in C++

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.

There are two ways are creating upcasting relationship:

Method 1:

Parent* parentObj; // Parent class pointer
Child childObj; // Creating child class object
parentObj = &childObj; // assigning to address reference of base class object

Method 2:

Parent &parentObj; // Parent class reference
Child childObj; // Creating child class object
parentObj = childObj; // direct assignment

Downcasting

In this process converting a base-class pointer or reference to a derived-class pointer or reference.

We cannot do this implicitly thus, we have to define explicitly.

Child *child = (Child) &parent;

121. what is difference between public, private and protected members?

Public Members:

The data members declared under public will be available to everyone.

The data members and member functions declared public can be accessed from other classes too.

Private Members:

The data members declared as private can be accessed only by the functions inside the class.

Only the member functions or the friend functions are allowed to access the private data members of a class.

Protected Members:

Protected access modifier is similar to that of private access modifiers.

The class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.

122. what is object slicing in C++?

Object slicing happens when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off to form the base class object.

class A
{
int foo;
};

class B : public A
{
int bar;
};

So an object of type B has two data members, foo and bar.

Then if you were to write this:

B b;

A a = b;

Then the information in b about member bar is lost in a.

123. Guess the output of Inheritance Program 1

#include<iostream>
using namespace std;
class Base1
{
public:
Base1()
{ ​
cout << ” Base1’s constructor called” << endl;
}
};

class Base2
{
public: Base2()
{
​cout << “Base2’s constructor called” << endl;
}
};

class Derived: public Base1, public Base2
{
public: Derived()
{
​cout << “Derived’s constructor called” << endl;
}
};

int main()
{
Derived d;
return 0;
}

Output:

Base1′s constructor called
Base2′s constructor called
Derived’s constructor called

Why?

Constructors of base classes are called in the same order as they are specified in inheritance.

124.Guess the output of Inheritance Program 2

#include <iostream>
using namespace std;

class Base1
{
public:
~Base1() { cout << ” Base1’s destructor” << endl;
}
};
class Base2 {
public:
~Base2() { cout << ” Base2’s destructor” << endl;
}
};

class Derived: public Base1, public Base2 {
public:
~Derived() { cout << ” Derived’s destructor” << endl;
}
};

int main()
{
Derived d;
return 0;
}

Output:

Derived’s destructor
Base2’s destructor
Base1’s destructor

Why?

Destructors are always called in reverse order of constructors.

125. Guess the output of Inheritance Program 3

#include<iostream>
using namespace std;
class base
{
int arr[10];
};

class b1: public base { };

class b2: public base { };

class derived: public b1, public b2 {};

int main(void)
{
cout << sizeof(derived);
return 0;
}

Output:

80

Why?

Both b1 and b2 inherit base class, 2 copies of base class will be there in derived class. This situation can be resolved by virtual classes.

126. Guess the output of Inheritance Program 4

#include<iostream>
using namespace std;

class Base {};

class Derived: public Base {};

int main()
{
Base *bp = new Derived;
Derived *dp = new Base;
}

Output:

Error in  ” Derived *dp = new Base;”

Why?

A Base class pointer/reference can point/refer to a derived class object, but the other way is not possible

127. Guess the output of Inheritance Program 5

#include<iostream>
using namespace std;

class Base1
{
public:
char c;
};

class Base2
{
public:
int c;
};

class Derived: public Base1, public Base2
{
public:
void show() { cout << c; }
};

int main(void)
{
Derived d;
d.show();
return 0;
}

Output:

Compiler Error in “cout << c;”

Why?

Because the variable c is present in both of the base class.

This error can be resolved by using scope resolution operator.

cout << Base2::c;

128. Guess the output of Inheritance Program 6

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

class Base
{
public:
virtual string print() const
{
return “This is Base class”;
}
};

class Derived : public Base
{
public:
virtual string print() const
{
return “This is Derived class”;
}
};

void describe(Base p)
{
cout << p.print() << endl;
}

int main()
{
Base b;
Derived d;
describe(b);
describe(d);
return 0;
}

Output

This is Base class

This is Base class

why?

when we assign an object of derived class to an object of base type, the derived class object is sliced off and all the data members inherited from base class are copied.

129. How to pass objects to a function?

#include <bits/stdc++.h>
using namespace std;

class Example
{
public: ​
int a; ​

// This function will take an object as an argument
​void add(Example E)
​{
​​a = a + E.a; ​
}
};

int main()
{ ​
Example E1;

​// Values are initialized for both objects
​E1.a = 50; ​

cout << “Initial Values \n”; ​
cout << “Value of object 1: ” << E1.a << “\n\n”;

​// Passing object as an argument to function add() ​
E1.add(E1);

​cout << “New values \n”;
​cout << “Value of object 1: ” << E1.a << “\n\n”;

​return 0;
}

Output:

Initial Values

Value of object 1: 50

New values

Value of object 1: 100

130. How to return an object from the function?

#include <bits/stdc++.h>
using namespace std;

class Example
{
public:
​int a;

​// This function will take  object as arguments and return object
​Example add(Example Ea, Example Eb)
​{ ​​
Example Ec;
​​Ec.a = Ec.a + Ea.a + Eb.a; ​​

// returning the object
​​return Ec;
​}
};
int main()
{ ​
Example E1, E2, E3; ​

// Values are initialized
​// for both objects
​E1.a = 150;
​E2.a = 200;
​E3.a = 0;

​cout << “Initial Values \n”;
​cout << “Value of object 1: ” << E1.a
​​<< “, \nobject 2: ” << E2.a
​​<< “, \nobject 3: ” << E3.a
​​<< “\n”; ​

// Passing object as an argument
​// to function add()
​E3 = E3.add(E1, E2); ​

// Changed values after
​// passing object as an argument
​cout << “New values \n”; ​
cout << “Value of object 1: ” << E1.a ​​
<< “, \nobject 2: ” << E2.a
​​<< “, \nobject 3: ” << E3.a ​​
<< “\n”; ​

return 0;
}

Output:

Initial Values
Value of object 1: 150,
object 2: 200,
object 3: 0

New values
Value of object 1: 150,
object 2: 200,
object 3: 500

131. Can we overload New operator?

Yes, we can overload new operator.

Syntax for overloading the new operator :

void* operator new(size_t size);

Example:

void* operator new(size_t num)
{
return malloc(num);
}

132. Can we overload Delete operator?

Yes, we can overload Delete operator.

Syntax for overloading the delete operator :

void operator delete(void*);

Example:

void operator delete(void *ptr)
{
free(ptr);
}

133. Does overloading work with Inheritance?

No. It will not work.

If we have a function with same name in base and derived class, function overloading will not work in inheritance.

Example:

#include <iostream>
using namespace std;
class Base
{
public: ​
int fun(int i)
​{

​​cout << “fun(int): “;
​​return i+3;
​}
};

class Derived : public Base
{
public: ​double fun(double d)
​{
​​cout << “fun(double): “;
​​return d+3.3;
​}
};

int main()
{
​Derived* derived = new Derived;
​cout << derived->fun(4) << ‘\n’;
​cout << derived->fun(4.4) << ‘\n’; ​
delete derived; ​
return 0;
}

Output:

fun(double): 7.3
fun(double): 7.7

We get the above output instead of our assumed output

f(int): 6
f(double): 6.6

134. What are local classes in C++

Classes defined inside a function are called as local classes.

#include<iostream>
using namespace std;
void myFun()
{ ​
class myLocalClass// local to myFun ​
{ ​​
/* members of myLocalClass class */ ​
};
}

int main()
{
​return 0;
}

Points to remember for local class:

1. All the member functions of Local classes must be defined inside the class only. 2. Local classes can access global types, variables and functions. Also, local classes can access other local classes of same function.

135. what are Anonymous classes in C++

A class which has no name given to it is called as anonymous class.

Anonymous classes cannot have a constructor but can have a destructor.

Anonymous classes can neither be passed as arguments to functions nor can be used as return values from functions.

Example:

#include <iostream>
using namespace std;
// Anonymous Class, this class has no name

class
{
​int i;
public: ​
void setData(int i) ​
{
​​this->i = i;
​}
​void print()
​{ ​​
cout << “Value for i : ” << this->i << endl;
​}
} myObj;​// object for anonymous class

int main()
{
​myObj.setData(20);
​myObj.print();
​return 0;
}

Output:

Value for i : 20

136. What is the size of an empty class in C++?

#include<iostream>
using namespace std;
class Empty {};
int main()
{
cout << sizeof(Empty);
return 0;
}

Output:

1 Size of empty class 1 byte.

It is nonzero to ensure that the two different objects will have different addresses.

137. Where is an object stored if it is created inside a block in C++?

C++ offers three different ways to create objects:

  • Stack-based such as temporary objects
  • Heap-based by using new
  • Static memory allocation such as global variables and namespace-scope objects

Memory Allocation and Deallocation Questions

138. What is the difference between new and malloc?

new()

  • calls constructor
  • It is an operator
  • Returns exact data type
  • on failure, Throws
  • can be overridden
  • size is calculated by compiler

malloc()

  • doesn’t calls constructors
  • It is a function
  • Returns void *
  • On failure, returns NULL
  • Memory allocated from heap
  • cannot be overridden
  • size is calculated manually

139. What is the difference between delete and free

Delete Operator:

Delete is an Operator in C++ which is used to free the memory allocated by new operator or for a NULL Pointer.

delete ptr;

Free():

Free function is use to deallocate memory allocated by malloc function.

free(ptr);

140. Is below code valid?

int *ptr = NULL;
delete ptr;

Yes, you can delete a pointer pointing to NULL. there is no need to check for NULL pointer

141. Is the code below valid?

#include<iostream>
using namespace std;

int main()
{
int *ptr = new int;
delete ptr;
delete ptr;
return 0;
}

No, you should not call delete twice.

142. what is the output of below program?

#include <iostream>
using namespace std;

class MyClass
{
int x;
MyClass() { x = 5;}
};

int main()
{
MyClass *t = new MyClass;
cout << t->x;
}

Output:

Compiler Error

Why?

MyClass::MyClass() is private.

143. What is the difference between delete and delete[]

If you allocate and create an array with new, it can only be deallocated by delete[].

If you allocate and create a non-array object with new, it can only be deallocated by delete.

The reason why there are separate delete and delete[] operators is that delete calls one destructor whereas delete[] needs to look up the size of the array and call that many destructors.

int* a = new int;
int* b = new int[10];

delete a;
delete[] b;

144. What is memory alignment?

Data structure alignment is the way data is arranged and accessed in computer memory.

This increases the performance of system due to the way the CPU handles memory.

To align the data, it may be necessary to insert some extra bytes between the end of the last data structure and the start of the next data structure as the data is placed in memory as multiples of fixed word size. This is called as data padding.

#include <iostream>
using namespace std;

// first structure

struct test1
{
short s;
int i;
char c;
};

// second structure
struct test2
{
int i;
char c;
short s;
};

// driver program

int main()
{
test1 t1;
test2 t2;
cout << “size of struct test1 is ” << sizeof(t1) << “\n”;
cout << “size of struct test2 is ” << sizeof(t2) << “\n”;
return 0;
}

Output:

size of struct test1 is 12
size of struct test2 is 8

145. Allocate multidimensional array using new?

int** a = new int*[rowCount];
for(int i = 0; i < rowCount; ++i)
a[i] = new int[colCount];

146. Different ways to deallocate an array – c++

new type requires delete
new type[size] requires delete []

Multithreading with C++ Questions

147.  what is the header file required for Thread Creation

#include <thread>

148. What std::thread accepts in constructor ?

1.) Function Pointer

2.) Function Objects

3.) Lambda functions

149. How Thread objects can be created?

std::thread thObj(<CALLBACK>);

150. Creating a thread using Function

Pointer #include <iostream>
#include <thread>

void thread_function()
{
for(int i = 0; i < 10; i++);
std::cout<<“thread function Executing”<<std::endl;
}

int main()
{
std::thread threadObj(thread_function);
for(int i = 0; i < 10; i++);
std::cout<<“Display From MainThread”<<std::endl;

threadObj.join();

std::cout<<“Exit of Main function”<<std::endl;
return 0;

}

151. Creating a thread using Function Objects

#include <thread>
class DisplayThread
{
public:
void operator()()
{
for(int i = 0; i < 10; i++)
std::cout<<“Display Thread Executing”<<std::endl;
}

};

int main()
{
std::thread threadObj( (DisplayThread()) );
for(int i = 0; i < 10; i++)
std::cout<<“Display From Main Thread “<<std::endl;

std::cout<<“Waiting For Thread to complete”<<std::endl;

threadObj.join();
std::cout<<“Exiting from Main Thread”<<std::endl;

return 0;
}

152. How to join and dethatch threads?

Joining Threads with std::thread::join()

std::thread th(funcPtr);

// Some Code

th.join();

Detaching Threads using std::thread::detach()

std::thread th(funcPtr); th.detach();

153. How to Pass Arguments to Threads

#include <iostream>
#include <string>
#include <thread>
void threadCallback(int x, std::string str)
{
std::cout<<“Passed Number = “<<x<<std::endl;
std::cout<<“Passed String = “<<str<<std::endl;
}

int main()
{
int x = 10;
std::string str = “prodevelopertutorial”;
std::thread threadObj(threadCallback, x, str);
threadObj.join();
return 0;
}

154.How to get a Thread ID ?

Every thread has an unique Id associated with it

std::thread::id

Friend Functions Questions

155. what are friend functions?

We know that, when you declare data members as private or protected, they cannot be accessed outside of the class.

This rule can be violated with the help of friend function.

When you make an external function as a friend of the class, it will be able to access the private data members.

156. Code for friend functions

#include <iostream>
using namespace std;
class MyClass
{
private:
int iNum;
public:

//friend function
friend int addFive(MyClass);
};

// friend function definition
int addFive(MyClass d)
{

//accessing private data from non-member function
d.iNum += 5;
return d.iNum;
}
int main()
{
MyClass D;
cout<<“iNum value is: “<< addFive(D);
return 0;
}

Output:

5

157. What are friend classes in C++ and what are their properties?

Similarly, like a friend function, a class can also be made a friend of another class using keyword friend.

When a class is made a friend class, all the member functions of that class becomes friend functions.

158. Code for friend class

#include <iostream>
class A {
private:
int a; public:
A() { a = 10;}
friend class B; // Friend Class
};

class B {
private:
int b;

public:
void showA(A& x)
{
// As B is friend of A, it can access private members of A
std::cout << “A::a=” << x.a;
}
};

int main()
{
A a;
B b;
b.showA(a);
return 0;
}

Output:

A::a=0

159. Code to add members of two different class by using friend function 

#include <iostream>
using namespace std;
// forward declaration
class B;
class A
{
private:
int numA;
public:
A(): numA(10) { }
// friend function declaration
friend int add(A, B);
};

class B
{
private:
int numB;
public:
B():numB(1) { }
// friend function declaration
friend int add(A , B);
};

 

int add(A objectA, B objectB)
{
return (objectA.numA + objectB.numB);
}
int main()
{
A objectA;
B objectB;
cout<<“Sum: “<< add(objectA, objectB);
return 0;
}

Output:
sum: 11

160. Code to swap two members using Friend Function

#include <iostream>

using namespace std;

class Swap {
// Declare the variables of Swap Class
int temp, a, b;

public:

// Define the parametrized constructor, for inputs
Swap(int a, int b)
{
this->a = a;
this->b = b;
}

// make swap() friend of Swap class
friend void swap(Swap&);
};

// Define the swap function outside class scope
void swap(Swap& s1)
{

cout << “\nBefore Swapping: ” << s1.a << ” ” << s1.b;

// Swap operations with Swap Class variables
s1.temp = s1.a;
s1.a = s1.b;
s1.b = s1.temp;
cout << “\nAfter Swapping: ” << s1.a << ” ” << s1.b;
}

int main()
{
Swap s(10, 20);
swap(s);
return 0;
}

Output:

Before Swapping: 10 20

After Swapping: 20 10

Standard Template Library Questions

161. what is vector in C++ and why should you use it?

  • Vector is a template based container.
  • Vector is a dynamic array.
  • Vector can be expanded or decreased during run time.
  • Below is the syntax for a vector of ints

std::vector<int> vecOfInts;

162. List different ways to initialize a vector in C++

There are 5 different ways to initialize a vector in C++

1. Initializing by one by one pushing values :

#include <iostream>
using namespace std;

int main()
{
// Create an empty vector
vector<int> vect;
vect.push_back(10);
vect.push_back(20);
vect.push_back(30);

for (int x : vect)
cout << x << ” “;

return 0;
}

2. Specifying size and initializing all values :

#include <iostream>
using namespace std;

int main()
{
int n = 3;

// Create a vector of size n with all values as 10.
vector<int> vect(n, 10);
for (int x : vect)
cout << x << ” “;

return 0;
}

3. Initializing like arrays :

#include <iostream>
using namespace std;
int main()
{
vector<int> vect{ 10, 20, 30 };

for (int x : vect)
cout << x << ” “;

return 0;
}

4. Initializing from array

#include <iostream>
using namespace std;

int main()
{
int arr[] = { 10, 20, 30 };
int n = sizeof(arr) / sizeof(arr[0]);

vector<int> vect(arr, arr + n);

for (int x : vect)
cout << x << ” “;

return 0;
}

5. Initializing from another vector :

#include <iostream>
using namespace std;

int main()
{
vector<int> vect1{ 10, 20, 30 };

vector<int> vect2(vect1.begin(), vect1.end());

for (int x : vect2)
cout << x << ” “;

return 0;
}

163. What are different ways to copy a vector in C++

Method 1 : Iterative method.

// Initializing vector with values
vector<int> vect1{1, 2, 3, 4};

// Declaring new vector
vector<int> vect2;

// A loop to copy elements of
// old vector into new vector
// by Iterative method
for (int i=0; i<vect1.size(); i++)
vect2.push_back(vect1[i]);

Method 2 : By assignment “=” operator.

// Initializing vector with values
vector<int> vect1{1, 2, 3, 4};

// Declaring new vector
vector<int> vect2;

// Using assignment operator to copy one  vector to other
vect2 = vect1;

Method 3 : By passing vector as constructor.

// Initializing vector with values
vector<int> vect1{1, 2, 3, 4};

// Declaring new vector and copying element of old vector constructor method, Deep copy
vector<int> vect2(vect1);

Method 4 : By using inbuilt function copy(first_iterator_o, last_iterator_o, back_inserter())

// Initializing vector with values
vector<int> vect1{1, 2, 3, 4};

// Declaring new vector
vector<int> vect2;

// Copying vector by copy function
copy(vect1.begin(), vect1.end(), back_inserter(vect2));

Method 5 : By using inbuilt function assign(first_iterator_o, last_iterator_o)

// Initializing vector with values
vector<int> vect1{1, 2, 3, 4};

// Declaring another vector
vector<int> vect2;

// Copying vector by assign function
vect2.assign(vect1.begin(), vect1.end());

164. what are different ways to Initialize a list in C++

1. Initialize list from specified elements

​std::list<char> chars { ‘A’, ‘B’, ‘C’ };

​for (char c: chars)
​​std::cout << c << ‘\n’;

2. Initialize list from elements of another list

std::list<char> another_list = { ‘A’, ‘B’, ‘C’ };

// copy constructor

std::list<char> chars(another_list);

for (char c: chars)

std::cout << c << ‘\n’;

3. Initialize list from elements of an array

char ch[] = { ‘A’, ‘B’, ‘C’ };

std::list<char> chars(std::begin(ch), std::end(ch));

4. Initialize a list of specified size by specified element

unsigned size = 3;

char ch = ‘A’;

// fill constructor

std::list<char> chars(size, ch);

5. Initialize an empty list

std::list<char> chars;

165. What is a list, explain with an example code

List in C++ is a double linked list.

They are sequence of containers, that are stored in non continious memory location. They are slow in traversal as compared to arrays.

Example:

#include <iostream>
#include <list>
#include <iterator>
using namespace std;

void showlist(list <int> g)
{
list <int> :: iterator it;
for(it = g.begin(); it != g.end(); ++it)
cout << ” ” << *it;
cout << ‘\n’;
}

int main()
{
list <int> list1;

for (int i = 0; i < 10; ++i)

{
list1.push_back(i);
}

cout << “\nList 1 (list1) is : “;
showlist(list1);

cout << “\n list1.front() : ” << list1.front();
cout << “\n list1.back() : ” << list1.back();

cout << “\n list1.pop_front() : “;
list1.pop_front();
showlist(list1);

cout << “\n list1.reverse() : “;
list1.reverse();
showlist(list1);

return 0;

}

Output:

List 1 (list1) is :  0 1 2 3 4 5 6 7 8 9

list1.front() : 0
list1.back() : 9
list1.pop_front() :  1 2 3 4 5 6 7 8 9
list1.reverse() :  9 8 7 6 5 4 3 2 1

166. What is a dequeue, explain with an example code.

  • Dequeue stands for double ended queue. It is basically implementation of the data structure double ended queue.
  • In a basic queue data structure allows insertion from end and deletion from the front.
  • But in Dequeue where insertion and deletion operations are possible at both the ends.

#include <iostream>
#include <deque>

using namespace std;

void showdq(deque <int> g)
{
deque <int> :: iterator it;
for (it = g.begin(); it != g.end(); ++it)
cout << ” ” << *it;
cout << ‘\n’;
}

int main()
{
deque <int> dqueue;
dqueue.push_back(10);
dqueue.push_front(20);
dqueue.push_back(30);
dqueue.push_front(15);
cout << “The deque is : “;
showdq(dqueue);

cout << “\n dqueue.size() : ” << dqueue.size();
cout << “\n dqueue.max_size() : ” << dqueue.max_size();

cout << “\n dqueue.at(2) : ” << dqueue.at(2);
cout << “\n dqueue.front() : ” << dqueue.front();
cout << “\n dqueue.back() : ” << dqueue.back();

cout << “\n dqueue.pop_front() : “;
dqueue.pop_front();
showdq(dqueue);

cout << “\n dqueue.pop_back() : “;
dqueue.pop_back();
showdq(dqueue);

return 0;
}

Output:

The deque is : 15 20 10 30

dqueue.size() : 4
dqueue.max_size() : 4611686018427387903
dqueue.at(2) : 10
dqueue.front() : 15
dqueue.back() : 30
dqueue.pop_front() : 20 10 30
dqueue.pop_back() : 20 10

167. what is a arrays in C++, explain with an example code.

Below are the points, where the C++ arrays are different from c style of array.

  • Array classes knows its own size
    In C-style array there is more risk of array being decayed into a pointer. Array classes don’t decay into pointers

Example:

#include<iostream>
#include<array> // for array, at()
#include<tuple> // for get()
using namespace std;
int main()
{
// Initializing the array elements
array<int,6> ar = {1, 2, 3, 4, 5, 6};

// Printing array elements using at()
cout << “The array elements are (using at()) : “;
for ( int i=0; i<6; i++)
cout << ar.at(i) << ” “;
cout << endl;

// Printing array elements using get()
cout << “The array elements are (using get()) : “;
cout << get<0>(ar) << ” ” << get<1>(ar) << ” “;
cout << get<2>(ar) << ” ” << get<3>(ar) << ” “;

// Printing array elements using operator[]
cout << “The array elements are (using operator[]) : “;
for ( int i=0; i<6; i++)
cout << ar[i] << ” “;
cout << endl;

// Printing first element of array
cout << “First element of array is : “;
cout << ar.front() << endl;

// Printing last element of array
cout << “Last element of array is : “;
cout << ar.back() << endl;

// Printing number of array elements
cout << “The number of array elements is : “;
cout << ar.size() << endl;

// Printing maximum elements array can hold
cout << “Maximum elements array can hold is : “;
cout << ar.max_size() << endl;

return 0;

}

Output:

The array elements are (using at()) : 1 2 3 4 5 6
The array elements are (using get()) : 1 2 3 4 The array elements are (using operator[]) : 1 2 3 4 5 6
First element of array is : 1
Last element of array is : 6
The number of array elements is : 6
Maximum elements array can hold is : 6

168. what is a forward_list in C++, explain with an example code.

  • forward_list is implementation of single linked list.
  • forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.

Example:

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

int main()
{
// Declaring forward list
forward_list<int> flist;

// Assigning values using assign()
flist.assign({1, 2, 3});

// Displaying forward lists
cout << “The elements of first forward list are : “;
for (int&a : flist)
cout << a << ” “;
cout << endl;

//push the element in front
flist.push_front(60);

cout << “The elements of first forward list are : “;
for (int&a : flist)
cout << a << ” “;
cout << endl;

//pop the element from front
flist.pop_front();

// Displaying the forward list
cout << “The forward list after pop_front operation : “;
for (int&c : flist)
cout << c << ” “;
cout << endl;

return 0;
}

Output:

The elements of first forward list are : 1 2 3

The elements of first forward list are : 60 1 2 3

The forward list after pop_front operation : 1 2 3

169. what is a queue in C++, explain with an example code.

  • C++ STL queue is implementation of queue data structure.
  • It will operate in a first in first out (FIFO).
  • Elements are inserted at the back (end) and are deleted from the front.

#include <iostream>
#include <queue>

using namespace std;

void show_queue(queue <int> gq)
{
queue <int> g = gq;
while (!g.empty())
{
cout << ” ” << g.front();
g.pop();
}
cout << ‘\n’;
}

int main()
{
queue <int> queue_example;
queue_example.push(10);
queue_example.push(20);
queue_example.push(30);

cout << “The queue queue_example is : “;
show_queue(queue_example);

cout << “\n queue_example.size() : ” << queue_example.size();
cout << “\n queue_example.front() : ” << queue_example.front();
cout << “\n queue_example.back() : ” << queue_example.back();

cout << “\n queue_example.pop() : “;
queue_example.pop();
show_queue(queue_example);

return 0;

}

Output:

The queue queue_example is : 10 20 30

queue_example.size() : 3
queue_example.front() : 10
queue_example.back() : 30
queue_example.pop() : 20 30

170.  what is a priority queue in C++, explain with an example code.

priority_queue is a STL container, whose first element will always greatest of all the elements.

And are stored in descending order.

Example:

#include <iostream>
#include <queue>

using namespace std;

void show_priority_queue(priority_queue <int> gq)
{
priority_queue <int> g = gq;
while (!g.empty())
{
cout << ” ” << g.top();
g.pop();
}
cout << ‘\n’;
}

int main ()
{
priority_queue <int> priority_queue_example; priority_queue_example.push(10);
priority_queue_example.push(30);
priority_queue_example.push(20);
priority_queue_example.push(5);
priority_queue_example.push(1);

cout << “The priority queue priority_queue_example is : “; show_priority_queue(priority_queue_example);
cout << “\n priority_queue_example.size() : ” << priority_queue_example.size();
cout << “\n priority_queue_example.top() : ” << priority_queue_example.top();

cout << “\n priority_queue_example.pop() : “;
priority_queue_example.pop(); show_priority_queue(priority_queue_example);

return 0;

}

Output:

The priority queue priority_queue_example is : 30 20 10 5 1

priority_queue_example.size() : 5
priority_queue_example.top() : 30
priority_queue_example.pop() : 20 10 5 1

171. what is a stack in C++, explain with an example code.

  • Stack STL container is implementation of stack data structure.
  • It will operate in a Last In First Out (LIFO).

Example:

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

void showstack(stack <int> s)
{
while (!s.empty())
{
cout << ” ” << s.top();
s.pop();
}
cout << ‘\n’;
}

int main ()
{
stack <int> s;
s.push(15);
s.push(36);
s.push(27);
s.push(5);
s.push(1);

cout << “The stack is : “;
showstack(s);

cout << “\ns.size() : ” << s.size();
cout << “\ns.top() : ” << s.top();
cout << “\ns.pop() : “;
s.pop();
showstack(s);

return 0;

}

Output:

The stack is : 1 5 27 36 15

s.size() : 5
s.top() : 1
s.pop() : 5 27 36 15

172. what is a set in C++, explain with an example code .

  • Set belongs to associative container type in C++.
  • Each element has to be unique in set.
  • Elements will be stored in sorted order.
  • Even if you add 2 elements with same value, only 1 will be stored.

There are total of 4 Associative containers:

  1. ​set
  2. ​multiset
  3. ​map
  4. multimap

Example:

#include <iostream>
#include <set>
#include <iterator>

using namespace std;

int main()
{
// empty set container
set<int> set_example;
// insert elements in random order
set_example.insert(140);
set_example.insert(130);
set_example.insert(160);
set_example.insert(120);
set_example.insert(150);
set_example.insert(150); // only one 150 will be added to the set set_example.insert(110);

// printing set set_example
set <int> :: iterator itr;
cout << “\nThe set set_example is : “;
for (itr = set_example.begin(); itr != set_example.end(); ++itr)
{
cout << ” ” << *itr;
}
cout << endl;
return 0;

}

Output:

The set set_example is : 110 120 130 140 150 160

173. what is a multi set in C++, explain with an example code.

  • Multisets are also a type of associative containers.
  • There can be multiple elements can have same values.

#include <iostream>
#include <set>
#include <iterator>

using namespace std;

int main()
{
// empty set container
multiset <int> multiset_example;

// insert elements in random order
multiset_example.insert(140);
multiset_example.insert(130);
multiset_example.insert(160);
multiset_example.insert(120);
multiset_example.insert(150);
multiset_example.insert(150);
multiset_example.insert(110);

// printing set multiset_example
set <int> :: iterator itr;
cout << “\nThe set multiset_example is : “;
for (itr = multiset_example.begin(); itr != multiset_example.end(); ++itr)
{
cout << ” ” << *itr;
}
cout << endl;

return 0;
}

Output:

The set multiset_example is : 110 120 130 140 150 150 160

174. what is a map in C++, explain with an example code.

  • Maps are associative containers.
  • Each element has a key value and a mapped value.
  • No two mapped values can have same key values.

Example:

#include <iostream>
#include <iterator>
#include <map>

using namespace std;

int main()
{
// empty map container
map<int, int> map_example;

// insert elements in random order
map_example.insert(pair<int, int>(1, 40));
map_example.insert(pair<int, int>(2, 30));
map_example.insert(pair<int, int>(3, 60));
map_example.insert(pair<int, int>(4, 20));
map_example.insert(pair<int, int>(5, 50));
map_example.insert(pair<int, int>(6, 50));
map_example.insert(pair<int, int>(7, 10));

// printing map map_example
map<int, int>::iterator itr;
cout << “\nThe map map_example is : \n”;
cout << “\tKEY\tELEMENT\n”;
for (itr = map_example.begin(); itr != map_example.end(); ++itr)
{
cout << ” ” << itr->first
<< ” ” << itr->second << ‘\n’;
}

return 0;

}

Output:

The map map_example is : ​

KEY​    ELEMENT
1    40
2    30
3    60
4    20
5    50
6    50
7    10

175. what is a multi map in C++, explain with an example code.

  • Multimap is similar to map with an addition that multiple elements can have same keys.
  • Rather than each element being unique, the key value and mapped value pair has to be unique.

#include <iostream>
#include <map>
#include <iterator>

using namespace std;

int main()
{
multimap <int, int> multimap_example;

// insert elements in random order
multimap_example.insert(pair <int, int> (1, 40)); multimap_example.insert(pair <int, int> (2, 30)); multimap_example.insert(pair <int, int> (3, 60)); multimap_example.insert(pair <int, int> (4, 20)); multimap_example.insert(pair <int, int> (5, 50)); multimap_example.insert(pair <int, int> (6, 50)); multimap_example.insert(pair <int, int> (6, 10));

// printing multimap multimap_example
multimap <int, int> :: iterator itr;
cout << “\nThe multimap multimap_example is : \n”;
cout << “\tKEY\tELEMENT\n”;
for (itr = multimap_example.begin(); itr != multimap_example.end(); ++itr)
{
cout << ‘\t’ << itr->first
<< ‘\t’ << itr->second << ‘\n’;
}

return 0;

}

Output:

The multimap multimap_example is :

​KEY​        ELEMENT
​1​                  40
​2​                  30
​3                  ​60
​4​                   20 ​
5​                  50
​6​                  50 ​
6​                 10

176. Example for Binary Search in C++ Standard Template Library (STL)

The prototype for binary search is :

binary_search(startaddress, endaddress, valuetofind)

startaddress: the address of the first element of the array.

endaddress: the address of the last element of the array.

valuetofind: the target value which we have to search for.

#include <algorithm>
#include <iostream>

using namespace std;

void show(int a[], int arraysize)
{
for (int i = 0; i < arraysize; ++i)
cout << a[i] << ” “;
}

int main()
{
int a[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int asize = sizeof(a) / sizeof(a[0]);
cout << “\n The array is : “;
show(a, asize);

cout << “\n\n For binary search to work, the array elements should be sorted. \     First we sort the array, then we search for the element 2”;

sort(a, a + asize);
cout << “\n\n The array after sorting is : “;
show(a, asize);

cout << “\n\n Perform binary search”;
if (binary_search(a, a + 10, 2))
cout << “\nElement found in the array”;
else
cout << “\nElement not found in the array”;

return 0;

}

Output

The array is : 1 5 8 9 6 7 3 4 2 0

For binary search to work, the array elements should be sorted.     First we sort the array, then we search for the element 2

The array after sorting is : 0 1 2 3 4 5 6 7 8 9

Perform binary search

Element found in the array

177. Perform sorting in C++ using Standard Template Library .

The prototype for sort is :

sort(startaddress, endaddress)

startaddress: the address of the first element of the array.

endaddress: the address of the next contiguous location of the last element of the array.

Example:

#include <iostream>
#include <algorithm>

using namespace std;

void show(int a[])

{ ​
for(int i = 0; i < 10; ++i)
​​cout << a[i] << ” “;
}

int main()
{ ​
int a[10]= {3, 5, 2, 1, 7, 4, 5, 8, 0};
​cout << “\n The array before sorting is : “;
​show(a);

​sort(a, a+10);

​cout << “\n\n The array after sorting is : “; ​
show(a);

​return 0;

}

Output:

The array before sorting is : 3 5 2 1 7 4 5 8 0 0

The array after sorting is : 0 0 1 2 3 4 5 5 7 8

178. what are iterators in C++, how many kinds are there?

  • Iterators are like pointers, that point to the memory address of a STL container.
  • They are used to traverse element one by one.
  • The main advantage of an iterator is to provide a common interface for all the containers type.
  • Iterators can be incremented with ++, dereferenced with *, and compared against another iterator with !=.

Depending upon the functionality, they are divided into 5 types:

Input Iterators:

They are used to access the elements from the container, but it does not modify the value of a container.

Operators used for an input iterator are:

  1. Increment operator(++)
  2. Equal operator(==)
  3. Not equal operator(!=)
  4. Dereference operator(*)

Output Iterators:

They are used to modify the value of a container, but it does not read the value from a container.

Operators used for an output iterator are:

  1. Increment operator(++)
  2. Assignment operator(=)

Forward Iterator:

These iterators can read and write into a container. Bidirectional Iterators: They have all the features of forward iterators and also they can move in both the directions, that is why their name is bidirectional.

Random-Access Iterators

They are not limited to moving sequentially, as their name suggests, they can randomly access any element inside the container.

179. Code example for Input Iterators

#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec = { 1, 2, 3, 4, 5 };

// Declaring an iterator
vector<int>::iterator iter;

for (iter = vec.begin(); iter != vec.end(); ++iter)
{
// Accessing elements using iterator
cout << (*iter) << ” “;
}

return 0;

}

180. Code example for Output Iterators

// C++ program to demonstrate output iterator
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int>vec = {1, 2, 3, 4, 5};

// Declaring an iterator
vector<int>::iterator iter;

for (iter=vec.begin(); iter!=vec.end(); ++iter)
{
// Assigning elements using iterator *
iter = 1;
}

// vec becomes 1 1 1 1 1

return 0;
}

181. Code example for Forward Iterator

#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec = { 1, 2, 3, 4, 5 };

// Declaring an iterator
vector<int>::iterator iter;

for (iter = vec.begin(); iter != vec.end(); ++iter)
{
// Assigning values to locations pointed by iterator
*iter = 1;
}

for (iter = vec.begin(); iter != vec.end(); ++iter)
{
// Accessing values at locations pointed by iterator
cout << (*iter) << ” “;
}

return 0;
}

182. Code to reverse a Vector using STL in C++.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
int main()
{

// Get the vector
vector<int> a = { 1, 2, 3, 4, 5, 6 };

// Print vector
cout << “Vector: “;
for (int i = 0; i < a.size(); i++)
cout << a[i] << ” “;
cout << endl;

// Reverse vector
reverse(a.begin(), a.end());

// Print reversed vector
cout << “Reversed Vector: “;
for (int i = 0; i < a.size(); i++)
cout << a[i] << ” “;
cout << endl;

return 0;

}

Output:

Vector: 1 2 3 4 5 6
Reversed Vector: 6 5 4 3 2 1

183. Code to remove duplicates from a sorted array using STL in C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
int arr[] = { 1, 2, 2, 3, 4, 4, 4, 5, 5 };

int n = sizeof(arr) / sizeof(arr[0]);

// Print array
cout << “\nBefore removing duplicates:\n”;
for (int i = 0; i < n; i++)
cout << arr[i] << ” “;

vector<int> v(arr, arr + n);
vector<int>::iterator it;

// use unique() method to remove duplicates it = unique(v.begin(), v.end());
// resize new vector
v.resize(distance(v.begin(), it));

cout << “\nAfter removing duplicates:\n”;
for (it = v.begin(); it != v.end();++it)
cout << *it << “, “;
cout << ‘\n’;

return 0;

}

Output:

Before removing duplicates: 1 2 2 3 4 4 4 5 5

After removing duplicates: 1, 2, 3, 4, 5,

184. Code to find the minimum and maximum element of a Vector using STL in C++

#include <bits/stdc++.h>
using namespace std;
int main()
{ ​vector<int> a = { 1, 45, 54, 71, 76, 12 };
​cout << “Vector: “;
​for (int i = 0; i < a.size(); i++)
​​cout << a[i] << ” “; ​
cout << endl;

​cout << “\nMin Element = ” << *min_element(a.begin(), a.end()); ​

cout << “\nMax Element = ” << *max_element(a.begin(), a.end());

​return 0;

}

Output:

Vector: 1 45 54 71 76 12

Min Element = 1
Max Element = 76

 Template and exception handling Questions

185. what are templates? How many types are there? Explain function template?

Templates allows us to write generic programs, that will work with different data types.

There are 2 types of templates:

1. Function Templates
2. Class Templates

A function template will work with any kind of data type.

How to declare a function template?

template <class T>
T myFun(T arg)
{
… .. ..
}

Example for function template to find largest of 2 numbers.

#include <iostream>
using namespace std;

// template function
template <class T>
T Large(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}

int main()
{

cout << Large(10, 20) <<” is larger.” << endl;
cout << Large(11.11, 22.22) <<” is larger.” << endl;
cout << Large(‘a’, ‘b’) << ” has larger ASCII value.”;
return 0;

}

Output:

20 is larger.
22.22 is larger.
b has larger ASCII value.

186.  Swap 2 numbers using function template

#include <iostream>
using namespace std;

template <typename T>

void Swap(T &n1, T &n2)
{
T temp;
temp = n1;
n1 = n2;
n2 = temp;
}

int main()
{
int i1 = 11, i2 = 22;
float f1 = 11.11, f2 = 22.22;
char c1 = ‘a’, c2 = ‘b’;
cout << “Before passing data to function template.\n”;
cout << “i1 = ” << i1 << “\ni2 = ” << i2;
cout << “\nf1 = ” << f1 << “\nf2 = ” << f2;
cout << “\nc1 = ” << c1 << “\nc2 = ” << c2;
Swap(i1, i2);
Swap(f1, f2);
Swap(c1, c2);
cout << “\n\nAfter passing data to function template.\n”;
cout << “i1 = ” << i1 << “\ni2 = ” << i2;
cout << “\nf1 = ” << f1 << “\nf2 = ” << f2;
cout << “\nc1 = ” << c1 << “\nc2 = ” << c2;

return 0;

}

Output:

Before passing data to function template.
i1 = 11
i2 = 22
f1 = 11.11
f2 = 22.22
c1 = a
c2 = b

After passing data to function template.

i1 = 22
i2 = 11
f1 = 22.22
f2 = 11.11
c1 = b
c2 = a

187. what are class template with example.

Similar to function template, we can also create class template.

Sometimes, there will be an requirement to implement class that is same for all classes, but the data types used are different.

Below is the syntax to create class template:

template <class T>
class className
{
public:
T var;
};

Example:

#include <iostream>
using namespace std;
template <class T>
class Calculator
{
private:
T num1, num2;

public:
Calculator(T n1, T n2)
{
num1 = n1;
num2 = n2;
}

void displayResult()
{
cout << “Numbers are: ” << num1 << ” and ” << num2 << “.” << endl;
cout << “Addition is: ” << add() << endl;
cout << “Subtraction is: ” << subtract() << endl;
cout << “Product is: ” << multiply() << endl;
cout << “Division is: ” << divide() << endl;
}
T add() { return num1 + num2; }

T subtract() { return num1 – num2; }

T multiply() { return num1 * num2; }

T divide() { return num1 / num2; }
};
int main()
{
Calculator<int> intCalc(20, 10);
Calculator<float> floatCalc(22.4, 11.2);

cout << “Int results:” << endl;
intCalc.displayResult();
cout << endl << “Float results:” << endl;
floatCalc.displayResult();

return 0;
}

Output:

Int results: Numbers are: 20 and 10.
Addition is: 30
Subtraction is: 10
Product is: 200
Division is: 2

Float results:
Numbers are: 22.4 and 11.2.
Addition is: 33.6
Subtraction is: 11.2
Product is: 250.88
Division is: 2

188. How to create default values for the parameter list

It can be done in the template declaration:

Syntax:

template<typename T1 = defaultType, typename T2 = defaultType> class class-identifier

Example:

template <typename T = int>
class myClass
189. Guess the output for template question 1

#include <iostream>
using namespace std;

template <typename T>

void fun(const T&x)
{
static int count = 0;
cout << “x = ” << x << ” count = ” << count << endl;
++count;
return;
}

int main()
{
fun<int> (2);
cout << endl;
fun<int>(2);
cout << endl;
fun<double>(2.2);
cout << endl;

return 0;

}

Output:

x = 2 count = 0
x = 2 count = 1
x = 2.2 count = 0

Why?

  • Compiler will create a new instance of a template function for every data type.
  • So compiler creates two functions in the above example, one for int and other for double.
  • Every instance has its own copy of static variable.
  • The int instance of function is called twice, so count is incremented for the second call

190. Guess the output for template question 2

#include <iostream>
using namespace std;

template <typename T>
T max(T x, T y)
{
return (x > y)? x : y;
}
int main()
{
cout << max(3, 7) << std::endl;
cout << max(3.0, 7.0) << std::endl;
cout << max(3, 7.0) << std::endl;
return 0;
}

Output:

Error

Compiler Error in last cout statement as call to max is ambiguous.

191.  what is an exception and exception handling in C++?

  • An exception is an unexpected problem that arises during the execution of the program.
  • Exception handling provides a mechanism provide a way to transfer control from one part of the program to another part.

C++ provides 3 keywords to handle exception.

try, catch, throw

try: It represents a block of code that can throw an exception.

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

throw: Used to throw an exception.

Example:

#include <iostream>
using namespace std;
int main()
{
int x =-1;
cout << “Before try \n”;
try {
cout << “Inside try \n”;
if (x < 0)
{
throw x;
cout << “After throw (Never executed) \n”;
}
}
catch (int x )
{
cout << “Exception Caught \n”;
}
cout << “After catch (Will be executed) \n”;
return 0;
}

Output:

Before try
Inside try
Exception Caught
After catch (Will be executed)

10. Guess the output for exception handling question 1

#include <iostream>
using namespace std;
int main()
{
int x = -1;
try
{
cout << “Inside try \n”;
if (x < 0)
{
throw x;
cout << “After throw \n”;
}
}
catch (int x ){
cout << “Exception Caught \n”;
}
cout << “After catch \n”;
return 0;
}

Inside try
Exception Caught
After catch

192. Explain the below templates with example code in C++

is_unsigned template in C++
is_abstract template in C++
is_polymorphic template in C++
is_floating_point Template in C++
is_object Template in C++
is_class template in C++
is_empty template in C++
is_pointer Template in C++

is_unsigned template in C++

It is used to check whether the type is a unsigned arithmetic type or not.

Syntax:

template <class T > struct is_unsigned;

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

int main()
{ ​

cout << “signed char:” << is_unsigned<signed char>::value << ‘\n’;
​cout << “unsigned char:” << is_unsigned<unsigned char>::value << ‘\n’;
​cout << “signed int:” << is_unsigned<signed int>::value << ‘\n’;
​cout << “Unsigned int:” << is_unsigned<unsigned int>::value << ‘\n’; ​

return 0;

}

Output:

signed char:0
unsigned char:1
signed int:0
Unsigned int:1

is_abstract template in C++

It is used to check whether the type is a abstract class type or not.

Syntax:

template < class T > struct is_abstract;

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

struct myClass
{
​int m;
};

struct myClassAbstract
{
​virtual void foo() = 0;
};

class myClassAbstractDerived : myClassAbstract
{
};
int main()
{ ​
cout << “myClass:” << is_abstract<myClass>::value << ‘\n’;
​cout << “myClassAbstract:” << is_abstract<myClassAbstract>::value << ‘\n’; ​cout << “myClassAbstractDerived:” << is_abstract<myClassAbstractDerived>::value << ‘\n’; ​

return 0;
}

Output:

myClass:0
myClassAbstract:1
myClassAbstractDerived:1

is_polymorphic template in C++

It is used to checks whether the type is a polymorphic class type or not.

Syntax:

template < class T > struct is_polymorphic;

Example:

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

struct myClass
{ ​
void foo();
};
class someClass
{
​virtual void foo() = 0;
};

struct someClassDerived : someClass
{
};

int main()
{
​cout << “myClass:” << is_polymorphic<myClass>::value  << ‘\n’;
​cout << “someClass:” << is_polymorphic<someClass>::value  << ‘\n’;
​cout << “someClassDerived:” << is_polymorphic<someClassDerived>::value << ‘\n’;

​return 0;
}

Output:

myClass:0
someClass:1
someClassDerived:1

is_floating_point Template in C++

It is used to check whether the given type is a floating point value or not.

Syntax:

template < class T > struct is_floating_point;

Example:

#include <iostream>
using namespace std;

int main()
{ ​
cout << “char: ” << is_floating_point<char>::value  << endl; ​
cout << “int: ” << is_floating_point<int>::value  << endl;
​cout << “float: ” << is_floating_point<float>::value  << endl;
​return 0;
}

Output:

char: 0
int: 0
float: 1

is_object Template in C++

It  is used to check whether the given type is object or not.

Syntax:

template <class T > struct is_object;

#include <iostream>
#include <type_traits>
using namespace std;
class myClass
{
};

// main program

int main()
{
​cout << “myClass: ” << is_object<myClass>::value << ‘\n’;
​cout << “myClass&: ” << is_object<myClass&>::value << ‘\n’;
​cout << “int: ” << is_object<int>::value << ‘\n’;
​cout << “int&: ” << is_object<int&>::value;
​return 0;
}

Output:

myClass: 1
myClass&: 0
int: 1
int&: 0

is_class template in C++

It is used to check whether the given type is class or not.

Syntax:

template <class T> struct is_class;

#include <iostream>
#include <type_traits>
using namespace std;
class myClass1
{
};
union myClass2
{ ​
int var1;
​float var2;
};
int main()
{
​cout << “myClass1: ” << is_class<myClass1>::value << endl;
​cout << “myClass2: ” << is_class<myClass2>::value << endl; ​

return 0;
}

Output:

myClass1: 1
myClass2: 0

is_empty template in C++

It is used to check whether the given type is empty or not.

Syntax: template < class T > struct is_empty;

Example:

#include <iostream>
using namespace std;
// empty struct struct
myStruct1
{
};

// struct with local variable
structmyStruct2
{
​int variab;
};

// Struct with global variable
struct myStruct3
{ ​
static int variab;
};

// Struct with virtual destructor
struct myStruct4
{
​virtual ~myStruct4();
};

// Driver code

int main()
{
​cout << “Is myStruct1 empty: ” << is_empty<myStruct1>::value << ‘\n’;
​cout << “Is myStruct2 empty: ” << is_empty<myStruct2>::value << ‘\n’;
​cout << “Is myStruct3 empty: ” << is_empty<myStruct3>::value << ‘\n’;
​cout << “Is myStruct4 empty: ” << is_empty<myStruct4>::value << ‘\n’;

​return 0;
}

Output:

Is myStruct1 empty: 1
Is myStruct2 empty: 0
Is myStruct3 empty: 1
Is myStruct4 empty: 0

is_pointer Template in C++

it is used to check whether the given type is pointer or not.

Syntax: template <class T > struct is_pointer;

Example:

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

// main program
class myClass
{
};

int main()
{
​cout << “myClass: ” << is_pointer<myClass>::value << ‘\n’;
​cout << “myClass*: ” << is_pointer<myClass*>::value << ‘\n’; ​
cout << “myClass&: ” << is_pointer<myClass&>::value << ‘\n’;
​cout << “nullptr_t: ” << is_pointer<nullptr_t>::value << ‘\n’; ​
return 0;
}

Output:

myClass: 0
myClass*: 1
myClass&: 0 nullptr_t: 0

193. Code for user defined exception in C++

To create a user defined exception, include <exception> header file.

Create a class named MyException and inherited all properties from the exception class.

Create a function exceptionMessage() which returns an error message string.

Hence whenever an exception of type MyException occurs, this message will be displayed.

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

class MyException : public exception
{
public:
char * exceptionMessage ()
{
return “C++ Exception”;
}
};

int main()
{
try
{
throw MyException();
}
catch(MyException e)
{
cout << “MyException caught” <<endl;
cout << e.exceptionMessage() <<endl;
}
catch(exception e)
{
//Other errors
}
return 0;
}

194. what are Variadic function templates in C++?

  • Variadic templates are template that take a variable number of arguments.
  • Variadic function templates are functions which can take multiple number of arguments.

Example:

#include <iostream>

// this function takes no parameter, it is used to break the recursion chain.

void print()
{
}

// Variadic Template Function

template<typename T, typename … Args>
void print(T first, Args … args)
{

// Print the First Element
std::cout<<first<<” , “;

// Forward the remaining arguments
print(args …);
}

int main()
{

print(2, 3.4, “aaa”);

return 0;

}

Design Pattern Questions

195. List different types of design pattern available in C++

On a high level Design pattern can be divided in to 3 types.

1. Creational Patterns
2. Structural Patterns
3. Behavioural Patterns

They can be further divided into below types:

1. Creational Patterns

  •  Builder ​
  • Factories
  • Prototype
  •  Singleton

2. Structural Patterns

  •  Adapter ​
  •  Bridge
  • Composite
  •  Decorator
  •  Façade ​
  • Flyweight
  •  NullObject
  •  Proxy

3. Behavioural Patterns

  •  Chain of Responsibility
  •  Command
  •  Interpreter
  •  Iterator
  •  Mediator
  •  Memento ​
  •  Observer
  •  State ​
  •  Strategy(Policy)
  •  Template ​
  •  Visitor

196. Explain different types of Creational Design Patterns

There are 4 types of Creational Design Patterns, theya are:

​1 Builder
​2 Factories
​3 Prototype
​4 Singleton

1. Builder Design pattern;

The Builder Creational Pattern is used to separate the construction of a complex object from its representation so that the same construction process can create different objects representations.

For example, for making a tea, you need tea leaves, water and milk, boil the water and add the ingredients.

Depending on the type of tea you want you might omit one or the other items. But the process remains the same.

2.  Factories:

A utility class that creates an instance of a class from a family of derived classes.

3. Prototype:

It Specify the kind of objects to create using a prototypical instance, and create new object by copying this prototype.

4. Singleton:

This design pattern ensures that a class has only one instance and provides a global point of access to that instance.

197. Explain different types of Structural Design Patterns

There are 8 structural design patters:

  1. Adapter: Convert the interface of a class into another interface that clients expect.
  2. Bridge : The Bridge Pattern is used to separate out the interface from its implementation. Doing this gives the flexibility so that both can vary independently.
  3. Composite : Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual object and compositions of object uniformly.
  4. Decorator : The decorator pattern helps to attach additional behaviour or responsibilities to an object dynamically. Decorators provide a flexible alternative to sub classing for extending functionality. This is also called “Wrapper”. If your application does some kind of filtering, then Decorator might be good pattern to consider for the job.
  5. Façade : The Facade Pattern hides the complexities of the system by providing an interface to the client from where the client can access the system on a unified interface.Facade defines a higher-level interface that makes the subsystem easier to use. For instance making one class method perform a complex process by calling several other classes.
  6. Flyweight : The pattern for saving memory (basically) by sharing properties of objects. Imagine a huge number of similar objects which all have most of their properties the same. It is natural to move these properties out of these objects to some external data structure and provide each object with the link to that data structure.
  7. NullObject : The intent of a Null Object is to encapsulate the absence of an object by providing a substitutable alternative that offers suitable default do nothing behaviour.
  8. Proxy : An object representing another object.

198. Explain different types of Behavioural Design Patterns

There are 12 structural design patters:

  1. Chain of Responsibility: Chain of Responsibility pattern has the intent to avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chains the receiving objects and passes the requests along the chain until an object handles it.
  2. Command : Command pattern is an Object behavioural pattern that decouples sender and receiver by encapsulating a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undo-able operations.
  3. Interpreter  : Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
  4. Iterator : The basic idea of the iterator is that it permits the traversal of a container (like a pointer moving across an array).
  5. Mediator : Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
  6. Memento : Without violating encapsulation the Memento Pattern will capture and externalize an object’s internal state so that the object can be restored to this state later.
  7. Observer : The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
  8. State  : The State Pattern allows an object to alter its behaviour when its internal state changes. The object will appear as having changed its class.
  9. Strategy(Policy) : Defines a family of algorithms, encapsulates each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients who use it.
  10. Template : By defining a skeleton of an algorithm in an operation, deferring some steps to subclasses, the Template Method lets subclasses redefine certain steps of that algorithm without changing the algorithm’s structure.
  11. Visitor : The Visitor Pattern will represent an operation to be performed on the elements of an object structure by letting you define a new operation without changing the classes of the elements on which it operates.
  12. Model-View-Controller (MVC) : A pattern often used by applications that need the ability to maintain multiple views of the same data. The Model is the actual data representation  or other objects representing a database. The View is an interface to reading the model or a fat client GUI. The Controller provides the interface of changing or modifying the data

199. Example code for singleton design pattern

#include <iostream>
using namespace std;
class Singleton
{
static Singleton *instance;
int data;

// Private constructor so that no objects can be created.
Singleton()
{
data = 0;
}

public:
static Singleton *getInstance()
{
if (!instance)
instance = new Singleton;
return instance;
}
int getData()
{
return this -> data;
}
void setData(int data)
{
this -> data = data;
}
};

//Initialize pointer to zero so that it can be initialized in first call to getInstance Singleton *Singleton::instance = 0;

int main(){
Singleton *s = s->getInstance();
cout << s->getData() << endl;
s->setData(100);
cout << s->getData() << endl;
return 0;
}

Bitwise Operations Questions

200. Check if a digit is even or odd  using bitwise operator

Use the ‘&’ operator. If num&1 is non zero, then the number is odd.

#include<stdio.h>

int main()
{
int num = 20;
(num & 1)? printf(“Odd”):
printf(“Even”);
return 0;
}

201. Count the number of set bits.

Example:

Input : n = 6
Output : 2
Binary representation of 6 is 110 and has 2 set bits

Ans: Loop through all the bits of the integer in it’s binary form and increase the count when you encounter set bits.

int count_set_bits(int n)
{
int count = 0;
while (n)
{
count += n & 1;
n >>= 1;
}
return count;
}

202. Program to find whether a num is power of two

bool check_pow_2(int num)
{
// num is a power of 2 only if its binary representation has one bit as 1.
if ((num & (num-1)) == 0) ​
return true;
return false;
}

Convert letter to uppercase:

AND by underline => (x & ‘_’)
Result is always uppercase even if letter is already uppercase
eg. (‘a’ & ‘_’) => ‘A’ ; (‘A’ & ‘_’) => ‘A’

Swap two nibbles in a byte

A nibble consists four bits.
<< (left shift operator) and >> (right shiftoperator) operators are used to swap the nibble.
SWAP_NIBBLES(data) ((data & 0x0F)<<4 | (data & 0xF0)>>4)

203. How to turn off a particular bit in a number?

int turn_off_articular_bit(int number, int bit)
{
// bit must be greater than 0
if (bit <= 0) return number;
// Do & of number with a number with all set bits except
// the bit
return (number & ~(1 << (bit – 1)));
}

int main()
{
printf(“%d”,TurnOffParticularBit(15, 4) );

return 0;
}

204. How to turn on a particular bit in a number?

int turn_on_particular_bit(int number, int bit)
{
// bit must be greater than 0
if (bit <= 0) return number;
// Do | of n with a number with all
// unset bits except the k’th bit

return (n | (1 << (k – 1)));
}

int main()
{
printf(“%d”,TurnOffParticularBit(15, 4) );
return 0;
}

Set nth bit

To set a particular bit of number. Left shift 1 n times and perform bitwise OR operation with num. Which is newNum = (1 << n) | num;.

newNum = (1 << n) | num;

Unset nth bit

  • Input number and nth bit position to clear from user.
  • Left shift 1, n times i.e. 1 << n.
  • Perform bitwise complement with the above result. So that the nth bit becomes unset and rest of bit becomes set i.e. ~ (1 << n).
  • Finally, perform bitwise AND operation with the above result and num. The above three steps together can be written as x & ~(1<<n)

Toggle nth bit

Step by step descriptive logic to toggle nth bit of a number.

Input number and nth bit position to toggle from user. Store it in some variable say num and n.

Left shift 1 to n times, i.e. 1 << n.

Perform bitwise XOR with num and result evaluated above i.e. num ^ (1 << n);.

x ^ (1<<n)

Multiply by 2

n << 1; // n*2

Divide by 2

n >> 1; // n/2

Exchange (swap) two values

a ^= b;
b ^= a;
a ^= b;

Calculate 2^n

1 << n;

Equality check

(a^b) == 0; // a == b

Sum of 2 integers using bitwise operations

int getSum(int a, int b)
{
int sum = a;
while (b != 0)
{
sum = a ^ b;//calculate sum of a and b without thinking the carry
b = (a & b) << 1;//calculate the carry
a = sum;//add sum(without carry) and carry
}
return sum;
}

205. Check if the number is positive or negative?

The Most Significant Bit will determine the sign of a number.

If the MSB is set, then the number is negative.

​sign = (num > 0) – (num < 0); ​

​if(sign == 1)
​{ ​​
printf(“Enter number is a positve number\n”);
​}
​else if(sign == -1)
​{
​​printf(“Enter number is a negative number\n”);
​}
​else ​{ ​​printf(“Enter number is zero\n”);
​}

206. Check if a particular bit is set.

Bit = Number & (1 << nth)

Number is the number whose bit you want to check and Nth is the bit number, (1<<N) SET the particular bit at Nth position.

If bitwise AND of n and (1<<N) is non-zero, then result is SET else result is NOT SET.

Example: Statement (1<<3) returns 8 (in Binary: 0000 1000), see the binary 3rd (count from 0 to 7) bit is SET here.

207. Toggle a particular bit

Bitwise XOR (^) operator use to toggle the bit of an integral data type. To toggle the nth bit shift the ‘1’ nth position toward the left and “XOR” it.

Number ^= (1<< nth Position)

208. Multiply a given Integer with 3.5 using bitwise operation

Multiply a given integer (num) with 3.5 using the following operation, (2 *num) + num + (num/2).

num = (num<<1) + num + (num>>1);; // equivalent to data * 3.5

209. Guess the output of the program?

#include<stdio.h>
int main()
{
​int num = 8;
​printf (“%d %d”, num << 1, num >> 1);
​return 0;
}

Output:

16 4

Why?

One to the right(<<) and other to the left(>>).

210. Guess the output of the program

#include<stdio.h>
int main()
{
​int x = 2;
​(x & 1) ? printf(“true”) : printf(“false”);
​return 0;
}

Output:

False
int x = 2
x = 00000010 in binary

Now the condition (00000010 & 00000001)

Condition false as it leads to 0.