C++ Interview Questions Guide
C++ Interview Questions Guide
1. What is C++?
If there are two or more functions with the same name defined in different libraries
then how will the compiler know which one to refer to? Thus namespace came to
picture. A namespace defines a scope and differentiates functions, classes,
variables etc. with the same name available in different libraries. The namespace
starts with the keyword “namespace”. The syntax for the same is as follows:
namespace namespace_name {
// code declarations
}
There are three ways to input a string, using cin, get, and getline. All three methods
are mentioned in the sample program below.
#include <iostream>
using namespace std;
int main()
{
char s[10];
getline(cin, str);
return 0;
}
The difference between c and c++ is that C++ is a object oriented language, which
means that it has all the features of C as well as its own thing that is the concept of
OOP. C++ has many functionalities of OOP that are missing from C such as
encapsulation, abstraction, classes, objects, etc.
#include<iostream>
#include<string.h>
using namespace std;
int main ()
{
char n[50], t;
int i, j;
cout << "Enter a string : ";
gets(n);
i = strlen(n) - 1;
A template in C++ is used to pass data types as parameters . These make it easier
and more simpler to use classes and functions.
int main(){
cout<<fun<int>(11,22);
}
Using namespace std in C++ tells the compiler that you will be making use of the
name space called ‘std’. The ‘std’ namespace contains all the features of the
standard library. You need to put this statement at the start of all your C++ codes if
you don’t want to keep on writing std:: infront of every variable/string or whatever
standard library feature you are making use of, as it becomes tedious to do so.
Pointers in C++ are a data type that store the memory address of another variable.
For eg.
or
int age;
int *int_value;
*int_value = &age;
A function in C++ is a block of code that can be referenced from anywhere in the
system and that serves a specific purpose.
int fun(){
int a = 11;
return 11;
}
int main(){
int b = fun();
}
Destructors in c++ are special function/methods that are used to remove memory
allocation for objects. They are called usually when the scope of an object ends. eg.
when a function ends you can call a destructor. They are of the same name as the
class – syntax – ~<classname>();
There are 2 approaches to convert integer variables to string. Both the approaches
with a sample code are mentioned below.
Approach-1
#include<iostream>
#include<string>
using namespace std;
void main()
{
int n= 1;
string s= to_string(n);
cout << s;
}
Approach-2
#include<iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
int n = 17;
Function Overloading happens in C++ when two or more functions share the same
name. They can be differentiated on the basis of the type of data they are passing
as parameters or even the number of paramters they are passing. eg. int fun(char a);
& int fun(int b); & void fun(int a, int b)
Stl is the standard template library. It is a library that allows you to use a standard
set of templates for things such as: Algorithms, functions, Iterators in place of
actual code.
queue<int> Q;
for(k=0;k<10;k++)
{
Q.push(k);
}
or
Type casting in C is used to change the data type. They are of two types: Implicit
Type Conversion: It is automatic. Explicit Type Conversion: It is user-defined.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
To compile and run c program in notepad++ follow the steps mentioned below:
Step-1: Download and install notepad++
Step-2: Download and install MinGw gcc along with gcc.
Step-3: Configure notepad++ for gcc. This step can be further divided into two
sub-steps. A: Create C compiler tool in Notepad++
B: Creating C execution tool.
Step-4: Execute C program in Notepad++
There are 95 reserved keywords in C++ which are not available for re-definition or
overloading.
It is a header file that includes basic objects such as cin, cout, cerr, clog.
In C++ programming, the space can be given using the following code.
cout << ” ” ;
There are several methods by which one can allocate memory to 2D array
dynamically one of which is as follows.
#include <iostream>
int main()
{
int row = 2, col = 2;
int* a = new int[row * col];
int i, j, count = 0;
for (i = 0; i < row; i++)
for (j = 0; j < col; j++)
*(a+ i*col + j) = count++;
delete[ ] a;
return 0;
}
Goto statement provided unconditional jump in the code. The syntax is: goto label;
label: statement;
#include <iostream>
using namespace std;
void main () {
float d, avg, add = 0.0;
int j, n;
cin >> n;
jump:
avg = add/ (j- 1);
cout << avg;
}
When a function with same name is present in both parent and child class then it is
called function overriding.
#include <iostream>
using namespace std;
class parent {
public:
void display(){
cout<<"Parent Class";
}
};
class child: public parent{
public:
void display() {
cout<<"Child Class";
}
};
int main() {
child o = parent();
o.display();
return 0;
}
– “sizeof” operator
– Pointer to member operator- “.*”
There are many more such uses that make C++ a desired language.
Bool is a data type in C++ which takes two values- True and False. Syntax is as
follows:
bool b1 = true;
#include<iostream>
using namespace std;
int main()
{
int a= 60, b= 70;
bool c, d;
c= a== b; // false
c= a< b; // true
cout <<b1;
cout << b2 ;
return 0;
}
Runtime abnormal conditions that occur in the program are called exceptions.
These are of 2 types:
– Synchronous
– Asynchronous
For limiting the decimal places in C++ there are five functions : floor(), ceil(),
trunc(), round() and setprecision(). Out of these five, only setprecision() function is
used for setting the decimal places to put as output. All the functions are mentioned
in the following sample code.
#include<bits/stdc++.h>
using namespace std;
int main()
{
float a =2.33333;
cout << floor(a) << endl;
cout << ceil(a) << endl;
cout << trunc(a) << endl;
cout << round(a) << endl;
cout << setprecision(2) << a;
return 0;
}
In C++, there are three functions in the cstdlib header file to return the absolute
value of the integer. Those are:
– abs()
– labs()
– llabs()
The difference lies in the range for integer value being passed as an argument. For
abs() its type int in C++. For labs(), its type long int in C++ and for llabs() its long
long int in C++.
#include <cstdlib>
#include <iostream>
int main()
{
int a, b, c;
a = abs(22);
b= labs(1234355L);
c= llabs(1234863551LL);
cout << a;
cout << b;
cout<< c;
return 0;
}
inheritance
– C++ supports operator overloading whereas Java does not support operator
overloading.
– C++ has pointers which can be used in the program whereas Java has pointers
but internally.
– C++ uses a compiler only whereas Java uses both compiler and interpreter.
– C++ has both call by value and call by reference whereas Java supports only call
by value.
– C++ supports structures and joins whereas Java does not support structure and
joins
– Java supports unsigned right shift operator (>>>) whereas C++ does not.
– C++ is interactive with hardware whereas Java is not that interactive with
hardware.
The strings in C++ can be concatenated in two ways- one considering them string
objects and second concatenating them C style strings.
#include <iostream>
using namespace std;
int main()
{
string s_1, s_2, fin;
cout << "Enter string";
getline (cin, s_1);
cout << "Enter string ";
getline (cin, s_2);
fin= s_1 + s_2;
cout << fin;
strcat(str1, str2);
return 0;
}
There are three methods for converting char variable to int type variable. These are
as follows: – atoi()
– sscanf()
– typecasting
#include<stdio.h>
#include<stdlib.h>
int main() {
char *s = "6790";
char d = 's';
int a,b,c;
return 0;
}
Using the rand() function we can generate random numbers in C++ within a range.
#include <iostream>
#include <random>
int main()
{
int max=100, min=54,i;
int range = max - min + 1;
for (i=min; i<max;i++)
{
int num = rand() % range + min;
cout<<num;
}
return 0;
A linear data structure which implements all the operations (push, pop) in LIFO
(Last In First Out) order. Stack can be implemented using either arrays or linked
list.The operations in Stack are
– Push: adding element to stack
– Pop: removing element from stack
– isEmpty: returns true if stack is empty
– Top: returns the top most element in stack
Conio.h is a header file used for console input and output operations and is used
for creating text based user interfaces.
To find the absolute value in c++, we can use abs() function. The abs() function in
C++ returns the absolute value of an integer number.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int a=3.456;
int x = abs(a);
cout << x;
return 0;
}
To exit Turbo C++, use the Quit option under the File Menu, or press Alt + X.
Any object which has an ability to iterate through elements of the range it has been
pointing to is called iterator.
:: is called a scope resolution operator which is used to access global variables with
the same name as of local variables, for defining functions outside the class, for
accessing static variables, and for referring to a class inside of another class.
When you have written code in the file (notepad),save the file as “hello.cpp.” If
you want to write in a file using C++ code, you can do it using iostream and
fstream libraries in C++.
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream file_name;
file_name.open ("sample.txt");
file_name<< "Write in the file";
file_name.close();
return 0;
}
Alt+Enter is the keyboard shortcut used to maximize (full screen) turbo C++.
For example:
class Sample
{
// Access specifier
private:
// Data Members
string s;
// Member Functions()
void printname()
{
cout << s;
}
};
GCC and clang are great compilers if the programmer’s target more portability
strcmp() function is an in-built function of <string.h> header file which takes two
strings as arguments and compares these two strings lexicographically.
#include<stdio.h>
#include<string.h>
int main()
{
// z has greater ASCII value than g
char a[] = "zfz";
char b[] = "gfg";
if (r==0)
printf("Strings are equal");
else
printf("Strings are unequal");
printf("%d" , r);
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream fout;
string r;
fout.open("test.txt");
while (fout) {
getline(cin, r);
if (r == "-1")
break;
fout << line << endl;
}
fout.close();
ifstream fin;
fin.open("test.txt");
while (fin) {
getline(fin, line);
cout << line << endl;
}
fin.close();
return 0;
}
stringstream string_name(str);
clear()
str()
<<
>>
If the program does not have using namespace std; then when you write cout <<;
you would have to put std::cout <<; same for other functions such as cin, endl etc.
#include <iostream>
int main()
{
std::cout << "Hello, World!";
return 0;
}
The length of a string can be calculated by using in-built functions such as length(),
size(), strlen() and also by loops (while and for).
#include<iostream>
#include<cstring>
using namespace std;
main() {
string s = "Hi I am Mr X";
char arr[] = "Hi I am Mr X";
cout << s.length();
cout << s.size();
cout <<strlen(arr);
char *c = arr;
int count = 0;
while(*c != '\0'){
count++;
c++;
}
cout << count;
count = 0;
for(int i = 0; arr[i] != '\0'; i++){
count++;
}
cout << count;
}
There is an in-built function- length()- in C++ to find the length of the string. The
code snippet to find the length of string is as follows
class Circle{
public:
float radius;
}
Inline functions are functions used to increase the execution time of a program.
Basically, if a function is inline, the compiler puts the function code wherever the
function is used during compile time. The syntax for the same is as follows:
A friend function has the access rights to all private and protected members of the
class.
class Circle{
double radius;
public:
friend void printradius( Circle c );
};
void printradius(Circle c ) {
/* Because printradius() is a friend of Circle, it can
directly access any member of this class */
cout << "Radius of circle: " << c.width;
}
int main() {
Circle c;
return 0;
}
Exceptions are errors that happen during execution of code. To handle them we use
throw, try & catch keywords.
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector <string> vec_1;
vec_1.push_back("sample code");
vec_1.push_back("change example");
for(vector <string>::iterator i=vec_1.begin();i!=vec_1.end();++i)
cout<<*i;
return 0;
}
For example:
Scope resolution operator in c++ is denoted by double colon (::). It can be used:
Character constant are members of the character set in which a program is written
which is surrounded by single quotation marks (‘).
A feature that allows functions and classes to operate with generic types that means
a function or class can work on different data types without being rewritten is
called template.
sort(vec.begin(), vec.end());
for (auto x : v)
cout << x << "" "";
return 0;
}
"
A pure virtual function is a type of virtual function which does not have
implementation, but is only declared. It is declared by assigning 0 in declaration.
Syntax for the same is as follows:
class Test
{
// Data members of class
public:
/* Other members */
};
#include <iostream>
#include <iterator>
#include <map>
int main()
{
map<int, int> test;
// inserting elements
test.insert(pair<int, int>(1, 2));
test.insert(pair<int, int>(2, 3));
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> vec;
int add (0);
while (!vec.empty())
{
add+= vec.back();
vec.pop_back();
}
return 0;
}
C++ is a standardized language and Visual C++ is a product that implements the
standard of C++. One can write portable C++ programs using Visual C++, but one
can also use Microsoft-only extensions which destroys portability but enhances
your productivity.
free(p);
*p = 110;
Solution: Before freeing the pointer check the assignment or any operation requir
scanf("%d",n);
Solution: To avoid this is the only solution
– Algorithms: Searching and sorting algorithms such as binary search, merge sort
etc.
– Containers: Vector, list, queue, arrays, map etc.
– Functions: They are objects that act like functions.
– Iterators: It is an object that allows transversing through elements of a container,
e.g., vector<int>::iterator.
std::flush synchronizes the stream buffer with its controlled output sequence.
1 string str_1;
2 cout << "Enter the string";
3 cin >> str_1;
Way 2:
1 string str_1;
2 cout << "Enter the string";
3 getline (cin, str_1)
#include <iostream>
using namespace std;
class Base_Class {
public:
virtual void print_msg() {
cout << "Base";
}
};
The length of an array in C++ can be calculated using sizeof() function. The code
depicting the same is mentioned below.
#include <iostream>
using namespace std;
void main()
{
int a[] = {0,1,2,3,4,5};
int a_size = sizeof(a)/sizeof(a[0]);
cout << ""Size of the array is: "" << a_size;
}
"
There are 2 approaches to convert integer variables to string. Both the approaches
with a sample code are mentioned below.
Approach 1:
#include<iostream>
#include<string>
using namespace std;
void main()
{
int n= 1;
string s= to_string(n);
cout << s;
}
Approach 2:
#include<iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
int n = 17;
To sort a string, the sort function in c++ can be used. The sample code for the same
is as follows.
#include<iostream>
#include <stdio.h>
using namespace std;
int main()
{
string s = ""anmbdfc"";
str_sort(s);
return 0;
}
Output: abcdfmn
"
int main()
{
string str_value = "1122";
int int_value = stoi(str_value);
}
or
int main()
{
const char *str_ptr = "1122";
int int_value = atoi(str_value);
}
Two string can be compared using strcmp() function. It return boolean value; if it
returns ‘0’ then the strings are same and if it returns ‘1’ then the two strings are not
same.
int main()
{
if (strcmp(str_value_a, str_value_b) == 0)
cout<<"These strings are the same";
else
cout<<"These strings are not the same";
}
Precision in C++ can be set by using the following functions- floor(), ceil(),
round(), trunc() and setprecision(). Using setprecision() in a program.
#include<bits/stdc++.h>
using namespace std;
void main()
{
double p = 8.04149;
cout << fixed << setprecision(2) << pi<<endl;
}
Using this pointer, every object is provided access to its own address. It is an
implicit parameter to all member functions. Only member functions have a this
pointer and not a friend function.
#include<iostream>
using namespace std;
class sample
{
private:
int a;
public:
void set_var (int a)
{
this->a = a;
}
void print()
{
cout << x ;
}
};
int main()
{
sample obj;
int a = 2;
obj.set_var(a);
obj.print();
return 0;
}
int main
{
string str_a = ""Hi, My name is"";
string str_b = ""Raj"";
string str_c = str_a + str_b;
cout<<""The string is:""<<str_c;
return 0;
}"
int main()
{
string str[]=""Hello World!"";
int g = str.size();
cout<<""The size of the string is""<<g;
}
or you can use the strlen function."
}"
You can use the cin function to take in values, like such:
int main()
{
int age;
cout<<""Enter your name!"";
cin>>age;
}"
syntax: reverse(the index you want to start reversing at,the index you want to end
reversing at)
vector<int> value = {11,22,33};
reverse(value.begin(),value.end());
for(int j=0;j<value_c.size();j++)
value_d.push_back(value_c[j]+4);
return value_d;
//returning the vector
}
int main()
{
vector<int> value_a,value_b;
value_b = fun(value_a);
//receiving the vector
return 0;
} "
int main()
{
int n;
cin >> n;
int a[n];
int i;
for(i = 0; i < n; i++)
{
cin >> arr[i];
}
for(i = n-1; i >= 0; i--)
{
cout << arr[i] << ” “;
}
cout << endl;
return 0;
}
"
int main ()
{
char * flag_pointer;
char string_value[10]=""Great Learning!"";
flag_pointer =strtok (string_value,"" !"");
while (flag_pointer!=NULL)
{
cout<<string_value;
flag_pointer=strtok(NULL,"" !"");
}
return 0;
}"
To sort a string, the sort function in c++ can be used. The sample code for the same
is as follows.
#include<iostream>
#include <stdio.h>
using namespace std;
void str_sort(string &s)
{
sort(s.begin(), s.end());
cout << s;
}
int main()
{
string s = ""anmbdfc"";
str_sort(s);
return 0;
}
Output: abcdfmn
"
Constructor is a method in class which has the same name as that of class and is
followed by parentheses (). It is automatically called when an object of a class is
created.
int main() {
Hello obj; // Create an object of Hello (this will call the constructor)
return 0;
}
"
Just like a child inherits some features and attributes from his parent similarly a
class inherit attributes and methods from another class. The parent class is called
base class and the child class is called derived class.
// Base class
class Food_Item{
public:
void taste() {
cout << ""The taste of every food item is different. \n"" ;
}
};
// Derived class
class Chips: public Food_Item{
public:
void taste() {
cout << ""The taste of chips is salty \n"" ; }
};
"
Class in C++ provides a blueprint for object, that means, object is created from the
class.
For example,
class Circle{
public:
float radius;
}
Circle C1;
Circle C2;
To prevent access to data directly, Encapsulation is the process that combines data
variables and functions in a class. This is achieved by doing the following:
Abstraction in C++ means showing only what is necessary. It’s part of Object
oriented Programming concept. Abstraction is used to hide any irrelevant data to
the outside world and only showing what is absolutely necessary for the outside
world to use.
eg. Classes use the abstraction concept to only show relevant data types or
elements. This is done through access specifiers such as: public, private, protected.
Member functions are those functions that you declare within a class, they are
members of the class. You can reference them using class objects. Eg.
class A
{
public:
int add(int b)
{
a = b * 10;
return a;
};
};"
Here Z may inherit similar features from X & Y as they both have inherited them
from W. This can cause issues and that’s why we use virtual base classes as they
stop multiple features of a class from appearing in another class.
Private members of the class are not accessible by object or function outside the
class. Only functions inside the class can access them or friend functions.
However, pointers can be used to access private data members outside the class.
Sample code is as follows:
#include <iostream>
using namespace std;
class sample_test{
private:
int n;
public:
sample_test() { n = 45; }
int display() {
return n;
}
};
A base class constructor will be called whenever the derived class constructor is
called. Upon the creation of a dervied class object the order of constructor
execution is : base class constructor then Default class constructor.
An abstract class in C++ is such that cannot be used directly and is used to form a
base class for others to inherit from.
If you create an object for an abstract class the compiler will throw an error at you.
An object oriented technique of hiding data members is called data hiding. In other
words, giving restricted access to the data members so as to maintain object
integrity.
#include <bits/stdc++.h>
using namespace std;
class parent
{
public:
void print()
{ cout<< ""base class""; }
};
void print()
{ cout<< ""derived class""; }
};
int main()
{
parent *p;
child c;
p = &c;
For example, when building a house it is built in modular way. First foundation is
laid, then structure is made and so on.