0% found this document useful (0 votes)
10 views2 pages

C++

Uploaded by

manaliphotos2503
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
10 views2 pages

C++

Uploaded by

manaliphotos2503
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 2

Top 100 C++ Interview Questions and

Answers in 2024
By Great Learning Editorial Team / Updated on Nov 13, 2024 / Published on Nov 8, 2023

Table of contents

C++ programming is a general-purpose programming language that was created by Bjarne Stroustrup. It is essential to know
C++ if you want to work in the software development domain. C++ is an extension of the C programming language. The first
set of c++ interview questions is curated for freshers and talks about the basic c++ interview questions.

Great Learning has curated a list of the top 20 frequently asked c++ interview questions; they are:

This C++ interview questions blog is further divided into groups as follows.

Basic C++ Interview Questions


Advanced C++ Interview Questions
C++ Programming Interview Questions
C++ OOPS Interview Questions
C++ Interview Questions FAQS

Basic C++ Interview Questions


All set to kickstart your coding career in c++? Look no further and start your professional career with these c++ interview
questions for freshers. We will start with the basics and slowly move towards slightly advanced questions to set the pace. If
you are an experienced professional, this section will help you brush up on your C++ skills.

What is C++?

As an extension of the C language, C++ was developed by Bjarne Stroustrup as a general-purpose cross-platform language
which gives programmers a high level of control over system resources and memory.

Why C++?

The use of C++ is varied such as:

– It is used in developing graphical user interface-based applications like adobe photoshop.

– It is used in developing games as it overrides the complexity of 3D games.

– There is much-animated software developed in C++

– Most of the compilers are written in C++.

– Google Chrome, Mozilla Firefox etc. web browsers are developed using C++

There are many more such uses that make C++ the desired language.

What is namespace in 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 the picture. A namespace defines the 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

What is operator overloading in C++?

Operator overloading in C++ is an overloaded declaration is declaration in the same scope of function or operator declared
with the same name more than once.

How to learn C++?

C++ is a programming language which is an extension of C. Thus, one should prefer to learn C first (it’s not necessary). After
learning C, then understand the basic difference between C and C++. Implement all the basic programs you learnt in C in
C++ also. Then dive into the OOPs concept of C++. Do as much hands-on as possible to understand basic OOPs, and then
dive into advanced-level OOPs. When all the basics are clear, build a small game to understand the structure and remain
concepts if any. By following all these steps one can learn C++.

What is the difference between C and C++?

The difference between c and c++ is that C++ is an object-oriented language, which means that it has all the features of C
as well as its own thing which is the concept of OOP. C++ has many functionalities of OOP that are missing from C such as
encapsulation, abstraction, classes, objects, etc.

C C++

C is a procedure-oriented programming language. C++ is an object-oriented programming language.

C does not support data hiding. C++ supports data hiding.

C is a subset of C++ C++ is a superset of C.

C doest not support Function and operator overloading C++ support Function and operator overloading

Functions can not be defined inside structures. Functions can be defined inside structures.

What is a template in C++?

A template in C++ is used to pass data types as parameters. These make it easier and simpler to use classes and functions.

template <typename T>

int fun (T a,T b)

return (a+b);

int main(){

cout<<fun<int>(11,22);

What is using namespace std in C++?

Using namespace std in C++ tells the compiler that you will be making use of the namespace 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.

How to download turbo C++ for windows 10?

To download turbo c++ follow the steps mentioned below:

Step-1: Download turbo C++ from http://www.turboccom/p/download.html

Step-2: Extract the Turbo.C.zip file.

Step-3: Run setup.exe file.

Step-4: Follow the instructions mentioned.

How to paste in turbo C++?

Paste in turbo C++ can be done by two techniques:

Shift+Insert
Open the file in notepad with .cpp extension. Make the changes and save it. After saving the file, you can open it from
the Turbo C++ application file menu from where you stored the cpp file.

What is a pointer in C++?

Pointers in C++ are a data type that store the memory address of another variable.

For eg.

char *str = "Hi, How are you?";

Here the pointer variable *str points to the string "Hi, How are you?"

or

int age;

int *int_value;

*int_value = &age;

cout<<"Enter your age please:";

cin>>age;

cout<<"n Your age is:"<<*int_value;

// this will print your age as the variable is pointing to the variable age.

What is a function in C++?

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();

What is a destructor in C++?

Destructors in c++ are special functions/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 it a destructor.

They are of the same name as the class - syntax - ~<classname>();

What is function overloading in C++?

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 parameters they are passing. eg. int fun(char
a); & int fun(int b); & void fun(int a, int b)

What is stl in C++?

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);

How to run a C++ program in cmd?

verify gcc installtion using the command:


$ gcc -vthen go to your working directory or folder where your code is:
$ cd <folder_name>then build the file containing your c code as such:
$ gcc main.cpp

or
$ g++ -o main main.cpp then run the executable generated in your system:
$ main.exe

What is type casting in C++?

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.

How to use a string in C++?

A string is a sequence of characters. In C++, the string is a data type as well as a header file. This header file consists of
powerful functions of string manipulation. A variable of string is declared as follows:

string str= "Hello";

And to use string one needs to include the header file.

// Include the string library

#include <string>

// Create a string variable

string str= "Hello";

What is stream in C++?

Stream refers to a stream of characters to be transferred between program thread and i/o.

What is the difference between structure and class in C++?

The difference between structure and class is as follows:

– By default, the data members of the class are private whereas data members of structure are public.

– While implementing inheritance, the access specifier for struct is public whereas for class its private.

– Structures do not have data hiding features whereas class does.

– Structures contain only data members whereas class contains data members as well as member functions.

– In structure, data members are not initialized with a value whereas in class, data members can be initialised.

– Structures are stored as stack in memory whereas class is stored as heap in memory.

How to clear screen in C++?

One can clear screen using – clrscr() or system(“clear”).

How to compile and run C program in notepad++ ?

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++

How many keywords in C++?

There are 95 reserved keywords in C++ which are not available for re-definition or overloading.

What is iostream in C++?

It is a header file that includes basic objects such as cin, cout, cerr, clog.

How to give space in C++?

In C++ programming, the space can be given using the following code.

cout << ” ” ;

Which operator cannot be overloaded in C++ ?

Some of the operators that cannot be overloaded are as follows:

– Dot operator- “.”

– Scope resolution operator- “::”

– “sizeof” operator

– Pointer to member operator- “.*”

How to copy and paste in turbo C++ ?

Press Ctrl + Insert to copy.

Press Shift + Insert to paste.

What is an exception in C++?

Runtime abnormal conditions that occur in the program are called exceptions. These are of 2 types:

– Synchronous

– Asynchronous

C++ has 3 specific keywords for handling these exceptions:

– try

– catch

– throw

What is the difference between C++ and Java?

This is one of the most common c++ interview questions asked, the difference between c++ and java are as follows:

– C++ supports goto statements whereas Java does not.

– C++ is majorly used in system programming whereas Java is majorly used in application programming.

– C++ supports multiple inheritance whereas Java does not support multiple 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.

What is stack in C++?

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

What is conio.h in C++?

Conio.h is a header file used for console input and output operations and is used for creating text based user interfaces.

How to exit from turbo C++?

To exit Turbo C++, use the Quit option under the File Menu, or press Alt + X.

What is iterator in C++?

Any object which has an ability to iterate through elements of the range it has been pointing to is called iterator.

What is :: in C++?

:: 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.

What is enum in C++?

enum is abbreviation of Enumeration which assigns names to integer constant to make a program easy to read. Syntax for
the same:

enum enum_name{const1, const2, ....... };

What is endl in C++?

Endl is a predefined object of ostream class to insert a new line characters.

How to save a file in C++?

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;

Which operators can be overloaded in C++?

List of operators that can be overloaded are:

+ , - , * , / , % , ^, & , | , ~ , !, =, ++ , --, ==, != , && , ||

+= , -= , /= , %= , ^= , &=, |= , *= , = , [] , (), ->, ->* , new , new [] , delete ,


delete []

How to include all libraries in C++?

The library <bits/stdc++.h> in c++ is used to include all the libraries.

How to maximize turbo C++ window?

Alt+Enter is the keyboard shortcut used to maximize (full screen) turbo C++.

What is an expression in C++?

An expression is a combination of operators, constants and variables. These seven types of expressions for examples:

- Constant expressions: 89 +10/0

- Integral expressions: x * y

- Floating expressions: 189

- Relational expressions: a<=b

- Logical expressions: a > b && a == 7

- Pointer expressions: *ptr

- Bitwise expressions: p << 5

Why namespace std is used in C++?

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.

Which is the best C++ compiler?

There are several good compilers for C++ such as:

MinGW /
GCC- Borland c++
Dev C++
Embracadero
Clang
Visual C++
Intel C++
Code Block

GCC and clang are great compilers if the programmers target more portability with good speed.

Intel and other compilers target speed with relatively less emphasis on portability.

What are the different data types present in C++?

The 4 data types in C++ are:

Primitive Datatype such as char, short, int, float, long, double, bool, etc.
Derived datatype such as an array, pointer, etc.
Enumeration such as enum
User-defined data types such as structure, class, etc.

What are the advantages of C++?

Mid-level programming language


Portability
C++ has the concept of inheritance
Multi-paradigm programming language
Memory Management
C++ is a highly portable language
Fast and Powerful
C++ contains a rich function library

What is the difference between reference and pointer?

Reference Pointers

Pointers are used to store the address of


Reference is used to refer to an existing variable in another name
a variable

The pointer can have a null value


References cannot have a null value assigned
assigned

The pointer can be referenced but


A reference variable can be referenced bypassing by the value
passed by reference

Pointers no need to be initialized on the


A reference must be initialized on the declaration
declaration

A reference shares the same memory address with the original variable and Pointer has its own memory address and
takes up some space on the stack size on the stack

What is exception handling in C++?

Exceptions are errors that happen during the execution of code. To handle them we use throw, try & catch keywords.

What is visual C++?

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 destroy portability but enhances your
productivity.

What is stl in C++ with example?

STL in C++ is a library and abbreviation of Standard Template Library. STL is a generalized library that provides common
programming data structures/ container classes, functions, algorithms, and iterators. STL has four components

- 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.

What is flush in C++?

std::flush synchronizes the stream buffer with its controlled output sequence.

Advanced C++ Interview Questions

This section of the blog talks about advanced C++ Interview Questions for your reference.

What is a class in C++?

C language is not an object-oriented programming language, so it is a constant attempt of C++ to introduce OOPs. Class is
a user-defined data type that defines a blueprint of data type. For example,

class Circle{

public:

float radius;

What is inline function in C++?

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:

inline return_type function_name(argument list) {

//block of code

What is friend function in C++?

A friend function has 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;
// Use friend function to print the radius.
printradius( c); return 0;
}

How to use vector in C++?

A sample code to see how to use vector in C++ is as follows:

#include<iostream>

#include<vector>

using namespace std;

int main()

vector <string> vec_1;

vec_push_back("sample code");

vec_push_back("change example");

for(vector <string>::iterator i=vec_begin();i!=vec_end();++i)

cout<<*i;

return 0;

What is vector in C++?

A sequence of containers to store elements, a vector is a template class of C++. Vectors are used when managing ever-
changing data elements. The syntax of creating vector.

vector <type> variable (number of elements)

For example:

vector <int> rooms (9);

What is scope resolution operator in C++?

Scope resolution operator in c++ is denoted by double colon (::). It can be used:

– when there is a local variable with same name as of global variable

– When a function has to be defined outside a class

– When class’s static variables needs to be accessed

– When a class inside another class has to be referred

– In case of multiple Inheritance

What are character constants in C++?

A character constant is member of the character set in which a program is written which is surrounded by single quotation
marks (‘).

What are templates in C++?

A feature that allows functions and classes to operate with generic types which means a function or class can work on
different data types without being rewritten is called a template.

How to sort vector in C++?

#include <bits/stdc++.h>

using namespace std;

int main()

vector<int> vec{ 1,9,4,3,2,8,5,7};

sort(vec.begin(), vec.end());

for (auto x : v)

cout << x << "" "";

return 0;

What is pure virtual function in C++?

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:

virtual void show() = 0;

/* Other members */

};

How to use map in C++?

Associative containers storing a combination of a key value or mapped value is called Maps. Syntax:

map<key_type , value_type> map_name;

#include <iostream>

#include <iterator>

#include <map>

using namespace std;

int main()

map<int, int> test;

// inserting elements

test.insert(pair<int, int>(1, 2));

test.insert(pair<int, int>(2, 3));

map<int, int>::iterator itr;

for (itr = test.begin(); itr != test.end(); ++itr) {

cout << itr->first

cout << itr->second << 'n';

return 0;

How to empty a vector in C++?

Std::vector::empty tests whether a vector is empty or not. A sample code for illustrating the same is as follows:

#include <iostream>

#include <vector>

int main ()

std::vector<int> vec;

int add (0);

for (int i=1;i<=5;i++) vec.push_back(i);

while (!vec.empty())

add+= vec.back();

vec.pop_back();

std::cout << add;

return 0;

How to remove segmentation fault in C++?

Segmentation fault indicates an error memory corruption. In layman terms, when a piece of code tries to do read and write
operation in a read only location in memory. Below are the reasons and solutions for segmentation error:

Reason: Accessing an address that is freed

int* p = malloc(8);

*p = 100;

free(p);

*p = 110;

Solution: Before freeing the pointer check the assignment or any operation required to perform.

Reason: Accessing out of array index bounds

int arr[2];

arr[3] = 10;

Solution: Correcting the array bound

Reason: Improper use of scanf()

int n = 2;

scanf("%d",n);

Solution: To avoid this is the only solution

Reason: Dereferencing uninitialized pointer

int *p;

printf("%d",*p);

Solution: A pointer must point to valid memory before accessing it.

Reason: Stack Overflow

Solution: It can be resolved by having a base condition to return from the recursive function.

How to initialize a 2d vector in C++?

The syntax to initialize a 2d vector is as follows:

std::vector<std::vector<int> > name_of_vector;

For example: std::vector<std::vector<int> > v { { 1, 2, 1 },

{ 2, 6, 7 } };

C++ OOPS Interview Questions


C++ Interview Questions also include questions on OOPs Concepts. This section on C++ OOPS Interview Questions will
help you learn more about the concepts.

What is oops in C++?

OOP or Object Oriented Programming in C++ is a type of programming in which you create objects and classes to emulate
real-world concepts such as Abstraction, Polymorphism, Encapsulation, and Inheritance.

Here classes are data types that allow you to list several types of data within it and even functions. You can access these
classes with the help of class objects

What is a constructor in C++?

Constructor in C++ is a method in the class which has the same name as that of the class and is followed by parentheses ().
It is automatically called when an object of a class is created.

class Hello { // The class

public: // Access specifier

Hello() { // Constructor

cout << ""Hello World!"";

};

int main() {

Hello obj; // Create an object of Hello (this will call the constructor)

return 0;

What is inheritance in C++?

Inheritance in C++ is 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"" ; }

};

What is object in C++?

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;

What is encapsulation in C++?

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:

Making all data variables private.

Creating getter and setter functions for data variables.

What is an abstraction in C++?

Abstraction in C++ means showing only what is necessary. It’s part of the Object-oriented Programming concept. Abstraction
is used to hide any irrelevant data from the outside world and only show 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, and protected.

What is a member function in C++?

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;

};

};

What is a virtual base class in C++?

Let’s understand this with an example.

You Have 4 classes: W,X,Y,Z

Here X & Y inherit from W. So they both have similar features being inherited from W.

Now, Z inherits from both X & Y

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.

How to access private members of a class in C++?

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.

The 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;

};

How to call a base class constructor from a derived class in C++?

A base class constructor will be called whenever the derived class constructor is called. Upon the creation of a derived class
object, the order of constructor execution is: base class constructor then Default class constructor.

What is an abstract class in C++?

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.

What is containership in C++?

Containership in C++ is a relationship in which a class’s object is nested within another class. The class that contains the
object is called a container class and the class whose object is stored is called a contained class.

What is data hiding in C++?

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.

Polymorphism Concept

What is runtime polymorphism in C++?

Polymorphism means having many forms whether it is a function or operator in programming.

Runtime polymorphism is achieved by function overriding.

#include <bits/stdc++.h>

using namespace std;

class parent

public:

void print()

{ cout<< ""base class""; }

};

class child:public parent

public:

void print()

{ cout<< ""derived class""; }

};

int main()

parent *p;

child c;

p = &c;

//virtual function, binded at runtime (Runtime polymorphism)

p->print();

return 0;

What is copy constructor in C++?

A copy constructor in c++ is a constructor which creates an object by initializing it with an object of the same class, which
has been created previously.
The syntax for copy constructor is as follows:

classname (const classname &obj) {

// body of constructor

How is modularity introduced in C++?

Modularity is a way of mapping encapsulated abstractions into real and physical modules which is closely related to
Encapsulation. It is a concept in which separate programs are divided into separate modules.

For example, when building a house it is built in modular way. First foundation is
laid, then structure is made and so on.

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

The size of an empty class is 1 byte generally just to ensure that the two different objects will have different addresses.

C++ Programming Interview Questions

Programming is an important aspect for any programmer or developer. This section of the blog talks about c++ interview
questions that will be beneficial to programming. Here is the list of the top 20 c++ programming questions.

How to write hello world in C++?

Hello world in C++ is as follows:


#include <iostream>
int main()
{
std::cout << "Hello, World!";
return 0;
}

How to input string in C++?

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];

cout << "Enter a string: ";


cin >> str;

cout << "nEnter another string: ";


cin.get(s, 10);

getline(cin, str);

return 0;
}

How to reverse a string in C++?

To reverse a string, a sample code is mentioned below.

#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;
for (j = 0; j < i; j++,i--)
{
t = s[j];
s[j] = s[i];
s[i] = t;
}
cout << "nReverse string : " << s;
return 0;
}

How to convert integer to string in C++?

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;

// declaring output string stream


ostringstream s1;

// Sending a number as a stream into output str


s<< n;
// the str() converts number into string
string fin = s.str();
// Displaying the string
cout << fin;
return 0;
}

How to input string in C++ with spaces?

The code to input a string in C++ with spaces is as follows:

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

int main()
{
string s;

cout << "Enter the sentence";


getline(cin, s);
cout << str;
return 0;
}

How to dynamically allocate a 2d array in C++?

There are several methods by which one can allocate memory to 2D array dynamically one of which is as follows:

#include <iostream>
int main()
{
int row = 2, col = 2;
int* a = new int[row * col];

int i, j, count = 0;
for (i = 0; i < row; i++)
for (j = 0; j < col; j++)
*(a+ i*col + j) = count++;

for (i = 0; i < row; i++)


for (j = 0; j < col; j++)
printf("%d ", *(a + i*col + j));

delete[ ] a;
return 0;
}

How to use goto statement in C++ ?

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;

for(j = 1; j <= n; ++j)


{
cout << "Enter number" << i;
cin >> d;

if(d < 0.0)


{
goto jump;
}
add+= d;
}

jump:
avg = add/ (j- 1);
cout << avg;
}

What is function overriding in C++?

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;
}

What is bool in C++?

Bool is a data type in C++ which takes two values- True and False.

The 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;
}

How to set decimal places in C++ ?

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 =33333;
cout << floor(a) << endl;
cout << ceil(a) << endl;
cout << trunc(a) << endl;
cout << round(a) << endl;
cout << setprecision(2) << a;
return 0;
}

How to get absolute value in C++?

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 syntax for all the functions is same

function_name(integer value)

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++
For llabs() its long long int in C++.

The sample code for illustrating the three functions is as follows:

#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
int a, b, c;

a = abs(22);
b= labs(1234355L);
c= llabs(1234863551LL);
cout << a;
cout << b;
cout<< c;
return 0;
}

How to concatenate string in C++ ?

The strings in C++ can be concatenated in two ways- one considering them string objects and the second concatenating
them C-style strings.

#include <iostream>
using namespace std;

int main()
{
string s_1, s_2, fin;
cout << "Enter string";
getline (cin, s_1);
cout << "Enter string ";
getline (cin, s_2);
fin= s_1 + s_2;
cout << fin;

char str1[50], str2[50], fin[100];

cout << "Enter string";


cin.getline(str1, 50);

cout << "Enter string";


cin.getline(str2, 50);

strcat(str1, str2);

cout << "str1 = " << str1 << endl;


cout << "str2 = " << str2;

return 0;
}

How to convert char to int in C++ ?

There are three methods for converting char variable to int type variable. These are as follows:

atoi()
sscanf()
typecasting

A sample code depicting all three functions are as follows:

#include<stdio.h>
#include<stdlib.h>
int main() {
char *s = "6790";
char d = 's';
int a,b,c;

sscanf(s, "%d", &a); // Using sscanf


printf("a : %d", a);

b = atoi(s); // Using atoi()


printf(“b : %d", b);

c = (int)(d); // Using typecasting


printf("c : %d", c);

return 0;
}

How to generate random numbers in C++ with a range?

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;
}

How to find absolute value in C++?

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;
}

How to write a class in C++?

A class in C++ is the building block that leads to Object-Oriented programming and is a user-defined data type which holds
data and functions. The syntax to write a class in C++ is as follows:

Class (keyword) Class_Name (this is user defined)


{
Access specifier: // private, public, protected
Data members //int, char, float, double etc. variables to be used
Member function() { } // Methods to access data members
}; //Class end
For example:
class Sample
{
// Access specifier
private:

// Data Members
string s;

// Member Functions()
void printname()
{
cout << s;
}
};

How to use strcmp function in C++?

strcmp() function is an in-built function of <string.h> header file which takes two strings as arguments and compares these
two strings lexicographically.

The syntax of the function is as follows:

int strcmp(const char *l, const char *r );

#include<stdio.h>
#include<string.h>
int main()
{
// z has greater ASCII value than g
char a[] = "zfz";
char b[] = "gfg";

int r = strcmp(a, b);

if (r==0)
printf("Strings are equal");
else
printf("Strings are unequal");

printf("%d" , r);

return 0;
}

How to write to a file in C++?

A file is read in c++ using a fstream header file.

#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;
}

What is stringstream in C++?

Stringstream is a class in c++ that associates a string object with a stream allowing to read from the string as if it were a
stream.

Syntax is as follows:

stringstream string_name(str);

Basic operations are as follows:

clear()
str()
<<
>>

C++ Interview Questions FAQS

What are the important topics in C++?


The significant topics in C++ are abstraction, control statements, constructor, objects, and classes, inheritance, destructor,
static, polymorphism, abstract class, interface, namespace, exception handling, encapsulation, arrays, strings, and File IO,
to name a few.

How do I prepare for C++?


As you start preparing for C++, you need to be sure that you are the basic data structures as well as algorithms. These are
the basic things that you are most likely to be asked about rather than more complicated concepts. To put it simply, you have
to be very clear about the fundamentals of C++ syntax.

What is C++ best used for?


C++ is used especially when a low-level programming language is needed. C++ is mostly used for graphics-heavy software,
which includes a photo and video editing apps, games, and browsers; while, C is usually used for OS kernels and embedded
devices.

What are the basics of C++?


The basic elements of C++ are input, output, conditional, arithmetic, and looping. To know more about it, you first need to
understand the concept of C++.

How to code in C++?


You have to start it by choosing a file name that explains the purpose of the program. The next step will include building the
Executable Code: Compile and Link (aka Build) the source code ” hello. cpp ” into executable code (” hello.exe ” in Windows
or ” hello ” in UNIX/Linux/Mac). On IDE (like CodeBlocks), push the “Build” button.

What is C++ and its features?


C++ is basically an object-oriented programming (OOP) language that many consider the best language that helps in
creating large-scale applications. The features of C++ include Object Oriented, Simple, Platform Dependent, Mid-level
programming language, Structured programming language, Rich Library, Memory Management, and Powerful & Fast.

Is C++ hard to learn?


The syntax of C++ is not difficult to understand for most people. And it becomes especially easy to learn if you already know
what C is. However, the versatility of C++ makes it a powerful language, which is why some find it a bit hard to learn.

Is Java better than C++?


Java is usually a high-level, object-oriented, and interpreted language, which uses objects. On the other hand, C uses
functions. Java is mostly found easier to learn by many since it is high level, while C performs faster since it is closer to
machine code.

Why is C++ called OOP?


The reason why C++ is called OOP or Object Oriented Programming is that C++ sees a problem as objects that are involved
rather than the process to do it.

This brings us to the end of the blog on c++ interview questions. We hope you are now well-equipped with the kind of
questions that may be asked during an Interview. Wondering where to learn the highly coveted in-demand skills for free?
Check out the courses on Great Learning Academy.
Popular Courses Interview Questions

PGP In Data Science and Business Analytics Java Interview Questions

PGP In Artificial Intelligence And Machine Learning Python Interview Questions

PGP In Management SQL Interview Questions

PGP In Cloud Computing Selenium Interview Questions

Software Engineering Course Machine Learning Interview Questions

PGP In Digital Marketing NLP Interview Questions

View More → View More →

Salary Blogs

Salary Calculator

Data Architect Salary

Cloud Engineer Salary

Software Engineer Salary

Product Manager Salary

Get our android app Get our ios app


of Use Great Learning Careers

(Formerly known as Great Lakes E-Learning Services Private Limited).All rights reserved

You might also like