C++
C++
Interview Questions
A list of top frequently
asked C++ interview questions and answers are given below.
1) What is C++?
C++ is an object oriented
programming language created by Bjarne Stroustrup. It is released in 1985.
2) What are the
advantages of C++?
C++ doesn't only maintains
all aspects from C language, it also simplify memory management and add several
features like:
- Includes a new datatype known as a
class.
- Allows object oriented
programming.
3) What is the
difference between C and C++?
No.
|
C
|
C++
|
1)
|
C
follows the procedural style programming.
|
C++ is
multi-paradigm. It supports both procedural and object oriented.
|
2)
|
Data is
less secured in C.
|
In C++,
you can use modifiers for class members to make it inaccessible for outside
users.
|
3)
|
C
follows the top-down approach.
|
C++
follows the bottom-up approach.
|
4)
|
C does
not support function overloading.
|
C++
supports function overloading.
|
5)
|
In C,
you can't use functions in structure.
|
In C++,
you can use functions in structure.
|
6)
|
C does
not support reference variables.
|
C++
supports reference variables.
|
6)
|
In C,
scanf() and printf() are mainly used for input/output.
|
C++
mainly uses stream cin and cout to perform input and output operations.
|
4) What is the
difference between reference and pointer?
No.
|
Reference
|
Pointer
|
1)
|
References
are less powerful than pointers. Once a reference is created, it can't refer
to other object later.
|
Pointers
provide the powerful facilities than references.
|
2)
|
References
are safer and easier to use than pointers.
|
Pointers
are comparatively difficult to use.
|
5) What are the C++ access specifiers?
The access specifiers are
used to define how to functions and variables can be accessed outside the
class.
There are three types of
access specifiers:
- Private: Functions and
variables declared as private can be accessed only within the same class
and they cannot be accessed outside the class they are declared.
- Public: Functions and
variables declared under public can be accessed from anywhere.
- Protected: Functions and
variables declared as protected cannot be accessed outside the class
except a child class. This specifier is generally used in inheritance.
6) What is the destructor?
Destructor is used to delete
any extra resources allocated by the object.
7) What is an overflow error?
It is a type of arithmetical
error. It is happen when the result of an arithmetical operation been greater
than the actual space provided by the system.
C Langauage
C
language Tutorial with programming approach for beginners and
professionals, helps you to understand the C language tutorial easily. Our C
tutorial explains each topic with programs.
The C Language is developed
for creating system applications that direct interacts to the hardware devices
such as drivers, kernals etc.
C programming is considered
as the base for other programming languages, that is why it is known as mother
language.
It can be defined by
following ways:
- Mother language
- System programming language
- Procedure-oriented programming
language
- Structured programming language
- Mid level programming language
Features
of C Language
C is the widely used
language. It provides a lot of features that are given below.
- Simple
- Machine Independent or Portable
- Mid-level programming language
- structured programming language
- Rich Library
- Memory Management
- Fast Speed
- Pointers
- Recursion
- Extensible
Dynamic memory allocation in C
The concept of dynamic
memory allocation in c language enables the
C programmer to allocate memory at runtime. Dynamic memory
allocation in c language is possible by 4 functions of stdlib.h header file.
- malloc()
- calloc()
- realloc()
- free()
Before learning above
functions, let's understand the difference between static memory allocation and
dynamic memory allocation.
static memory allocation
|
dynamic memory allocation
|
memory is allocated at compile time.
|
memory is allocated at run time.
|
memory can't be increased while executing program.
|
memory can be increased while executing program.
|
used in array.
|
used in linked list.
|
Now let's have a quick look at
the methods used for dynamic memory allocation.
malloc()
|
allocates single block of requested memory.
|
calloc()
|
allocates multiple block of requested memory.
|
realloc()
|
reallocates the memory occupied by malloc() or calloc()
functions.
|
free()
|
frees the dynamically allocated memory.
|
malloc()
function in C
The malloc() function allocates
single block of requested memory.
It doesn't initialize memory at
execution time, so it has garbage value initially.
It returns NULL if memory is
not sufficient.
The syntax of malloc() function
is given below:
calloc()
function in C
The calloc() function allocates
multiple block of requested memory.
It initially initialize all
bytes to zero.
It returns NULL if memory is
not sufficient.
The syntax of calloc() function
is given below:
1.
ptr=(cast-type*)calloc(number, byte-size)
realloc()
function in C
If memory is not sufficient for
malloc() or calloc(), you can reallocate the memory by realloc() function. In
short, it changes the memory size.
Let's see the syntax of
realloc() function.
1.
ptr=realloc(ptr, new-size)
free()
function in C
The memory occupied by malloc()
or calloc() functions must be released by calling free() function. Otherwise,
it will consume memory until program exit.
Let's see the syntax of free()
function.
1.
free(ptr)
What is
memory leak? Why it should be avoided
Ans: Memory leak occurs when programmers create a memory in heap and forget to delete it. Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate.
Ans: Memory leak occurs when programmers create a memory in heap and forget to delete it. Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate.
/* Function with memory leak */
#include <stdlib.h>
void f()
{
int *ptr = (int *)
malloc(sizeof(int));
/* Do some work */
return; /* Return without
freeing ptr*/
}
|
What are the differences between C and C++?
1) C++ is a kind of superset of C, most of C programs except few exceptions (See this and this) work in C++ as well.
2) C is a procedural programming language, but C++ supports both procedural and Object Oriented programming.
3) Since C++ supports object oriented programming, it supports features like function overloading, templates, inheritance, virtual functions, friend functions. These features are absent in C.
4) C++ supports exception handling at language level, in C exception handling is done in traditional if-else style.
5) C++ supports references, C doesn’t.
6) In C, scanf() and printf() are mainly used input/output. C++ mainly uses streams to perform input and output operations. cin is standard input stream and cout is standard output stream.
1) C++ is a kind of superset of C, most of C programs except few exceptions (See this and this) work in C++ as well.
2) C is a procedural programming language, but C++ supports both procedural and Object Oriented programming.
3) Since C++ supports object oriented programming, it supports features like function overloading, templates, inheritance, virtual functions, friend functions. These features are absent in C.
4) C++ supports exception handling at language level, in C exception handling is done in traditional if-else style.
5) C++ supports references, C doesn’t.
6) In C, scanf() and printf() are mainly used input/output. C++ mainly uses streams to perform input and output operations. cin is standard input stream and cout is standard output stream.
There are many more differences, above is a list of main
differences.
What is this pointer?
The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. ‘this’ pointer is a constant pointer that holds the memory address of the current object. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name).
The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. ‘this’ pointer is a constant pointer that holds the memory address of the current object. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name).
What are
virtual functions – Write an example?
Virtual functions are used with inheritance, they are called according to the type of object pointed or referred, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at runtime. Virtual keyword is used to make a function virtual.
Virtual functions are used with inheritance, they are called according to the type of object pointed or referred, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at runtime. Virtual keyword is used to make a function virtual.
Following things are necessary to
write a C++ program with runtime polymorphism (use of virtual functions)
1) A base class and a derived class.
2) A function with same name in base class and derived class.
3) A pointer or reference of base class type pointing or referring to an object of derived class.
1) A base class and a derived class.
2) A function with same name in base class and derived class.
3) A pointer or reference of base class type pointing or referring to an object of derived class.
For example, in the following
program bp is a pointer of type Base, but a call to bp->show() calls show()
function of Derived class, because bp points to an object of Derived class.
#include<iostream>
using namespace std;
class Base {
public:
virtual void show() { cout<<" In Base \n";
}
};
class Derived: public Base {
public:
void show() { cout<<"In Derived \n"; }
};
int main(void)
{
Base *bp = new Derived;
bp->show();
// RUN-TIME POLYMORPHISM
return 0;
}
|
Storage
Classes in C
Storage Classes are used to describe about the features of a
variable/function. These features basically include the scope, visibility and
life-time which help us to trace the existence of a particular variable during
the runtime of a program.
C
language uses 4 storage classes, namely:
auto: This is the default storage class for
all the variables declared inside a function or a block. Hence, the keyword
auto is rarely used while writing programs in C language. Auto variables can be
only accessed within the block/function they have been declared and not outside
them (which defines their scope). Of course, these can be accessed within
nested blocks within the parent block/function in which the auto variable was
declared. However, they can be accessed outside their scope as well using the
concept of pointers given here by pointing to the very exact memory location
where the variables resides. They are assigned a garbage value by default
whenever they are declared.
extern:
Extern storage class simply tells us that the variable is defined elsewhere and
not within the same block where it is used. Basically, the value is assigned to
it in a different block and this can be overwritten/changed in a different
block as well. So an extern variable is nothing but a global variable
initialized with a legal value where it is declared in order to be used
elsewhere. It can be accessed within any function/block. Also, a normal global variable
can be made extern as well by placing the ‘extern’ keyword before its
declaration/definition in any function/block. This basically signifies that we
are not initializing a new variable but instead we are using/accessing the
global variable only. The main purpose of using extern variables is that they
can be accessed between two different files which are part of a large program.
For more information on how extern variables work, have a look at this link.
static: This storage class is used to declare static
variables which are popularly used while writing programs in C language. Static
variables have a property of preserving their value even after they are out of
their scope! Hence, static variables preserve the value of their last use in
their scope. So we can say that they are initialized only once and exist till
the termination of the program. Thus, no new memory is allocated because they
are not re-declared. Their scope is local to the function to which they were
defined. Global static variables can be accessed anywhere in the program. By
default, they are assigned the value 0 by the compiler.
register: This storage class declares register variables
which have the same functionality as that of the auto variables. The only
difference is that the compiler tries to store these variables in the register
of the microprocessor if a free register is available. This makes the use of
register variables to be much faster than that of the variables stored in the
memory during the runtime of the program. If a free register is not available,
these are then stored in the memory only. Usually few variables which are to be
accessed very frequently in a program are declared with the register keyword
which improves the running time of the program. An important and interesting
point to be noted here is that we cannot obtain the address of a register
variable using pointers.
Q #1) What are the key features in C programming language?
- Portability – Platform
independent language.
- Modularity –
Possibility to break down large programs into small modules.
- Flexibility – The
possibility to a programmer to control the language.
- Speed – C comes
with support for system programming and hence it is compiling and executes
with high speed when comparing with other high-level languages.
- Extensibility – Possibility
to add new features by the programmer.
Q #2) What are the basic data types associated with C?
- Int
– Represent
number (integer)
- Float
– Number
with a fraction part.
- Double
– Double-precision
floating point value
- Char
– Single
character
- Void
– Special
purpose type without any value.
Q #3) What is the description for syntax errors?
Ans) The mistakes when creating a program called syntax errors.
Misspelled commands or incorrect case commands, an incorrect number of
parameters when called a method /function, data type mismatches can identify as
common examples for syntax errors.
Q #4) What is the process to create increment and decrement
stamen in C?
Ans) There are two possible methods to perform this task.
1) Use increment (++) and decrement (-) operator.
Example When x=4, x++ returns 5 and x- returns
3.
2) Use conventional + or – sign.
When x=4, use x+1 to get 5 and x-1 to get 3.
Q #5) What are reserved words with a programming language?
Ans) The words that are part of the slandered C
language library are called reserved words. Those reserved
words have special meaning and it is not possible to use them for any activity
other than its intended functionality.
Example void, return, int.
Q #6) What is the explanation for the dangling pointer in C?
Ans) When there is a pointer with pointing to a memory address
of any variable, but after some time the variable was deleted from the memory
location while keeping the pointer pointing to that location.
Q #7) Describe static function with its usage?
Ans) A function, which has a function definition prefixed with
a static keyword is defined as a static function. The static function should
call within the same source code.
Q #8) What is the difference between abs() and fabs() functions?
Ans) Both functions are to retrieve absolute value. abs() is
for integer values and fabs() is for floating type numbers. Prototype for abs()
is under the library file < stdlib.h > and fabs() is under < math.h
>.
Q #9) Describe Wild Pointers in C?
Ans) Uninitialized pointers in the C code are known as Wild
Pointers. These are a point to some arbitrary memory location and can cause
bad program behavior or program crash.
Q #10) What is the difference between ++a and a++?
Ans) ‘++a” is called prefixed increment and the increment
will happen first on a variable. ‘a++’ is called postfix increment and the
increment happens after the value of a variable used for the operations.
Q #11) Describe the difference between = and == symbols in C
programming?
Ans) ‘==’ is the comparison operator which is use to compare
the value or expression on the left-hand side with the value or expression on
the right-hand side.
‘=’ is the assignment operator which is use to assign the value
of the right-hand side to the variable on the left-hand side.
Q #12) What is the explanation for prototype function in C?
Prototype function is a declaration of a function with the
following information to the compiler.
- Name
of the function.
- The
return type of the function.
- Parameters
list of the function.
In this example Name of the function is Sum, the return type is
integer data type and it accepts two integer parameters.
Q #13) What is the explanation for cyclic nature of data types
in C?
Ans) Some of the data types in C have special characteristic
nature when a developer assign value beyond the range of the data type. There
will be no any compiler error and the value change according to a cyclic order.
This is called as cyclic nature and Char, int, long int data types have this
property. Further float, double and long double data types do not have this
property.
This is called as cyclic nature and Char, int, long int data
types have this property. Further float, double and long double data types do
not have this property.
Q #14) Describe the header file and its usage in C programming?
Ans) The file contains the definitions and prototypes of the
functions being used in the program are called a header file. It is also known
as a library file.
Example– The header file contains commands like
printf and scanf is the stdio.h.
Q #15) There is a practice in coding to keep some code blocks in
comment symbols than delete it when debugging. How this affect when debugging?
Ans) This concept called as commenting out and is the way to
isolate some part of the code which scans possible reason for the error. Also,
this concept helps to save time because if the code is not the reason for the
issue it can simply uncomment.
Q #16) What are the general description for loop statement and
available loop types in C?
Ans) A statement that allows executing statement or group of
statements in repeated way is defined as a loop.
There are 4 types of a loop statement in C.
- While
loop
- For
Loop
- Do…While
Loop
- Nested
Loop
Q #17) What is a nested loop?
Ans) A loop running within another loop is referred as a nested
loop. The first loop is called Outer loop and inside the loop is called
Inner loop. Inner loop executes the number of times define an outer loop.
Q #18) What is the general form of function in C?
Ans) Function definition in C contains four main sections.
- Return
Type ->
Data type of the return value of the function.
- Function
Name ->
The name of the function and it is important to have a meaningful name
that describes the activity of the function.
- Parameters -> The
input values for the function that need to use perform the required
action.
- Function
Body ->
Collection of statement that needs to perform the required action.
Q #19) What is a pointer on a pointer in C programming language?
Ans) A pointer variable that contains the address of another
pointer variable is called pointer on a pointer. This concept de-refers twice
to point to the data held by a pointer variable.
In this example **y returns value of the variable a.
Q #20) What are the valid places to have keyword “Break”?
Ans) The purpose of the Break keyword is to bring the control
out of the code block which is executing. It can appear only in Looping or
switch statements.
Q #21) What is the behavioral difference when include header
file in double quotes (“”) and angular braces (<>)?
Ans) When Header file include within double quotes (“”),
compiler search first in the working directory for the particular header file.
If not found then in the built in the include path. But when Header file
include within angular braces (<>), the compiler only search in the
working directory for the particular header file.
Q #22) What is a sequential access file?
Ans) In general programs store data into files and retrieve
existing data from files. With the sequential access file such data saved in a
sequential pattern. When retrieving data from such files each data need to read
one by one until required information find.
Q #23) What is the method to save data in stack data structure
type?
Ans) Data is stored in Stack data structure type using First
in Last out (FILO) mechanism. Only top of the stack is accessible at a
given instance. Storing mechanism is referred as a PUSH and retrieve is referred
as a POP.
Q #24) What is the significance of C program algorithms?
Ans) The algorithm needs to create first and it contains step
by step guidelines on how the solution should create. Also, it contains the
steps to consider and the required calculations/operations within the program.
Q #34) Is that possible to store 32768 in an int data type
variable?
Ans) Int data type only capable of storing values between –
32768 to 32767.To store 32768 a modifier needs to use with int data type. Long
Int can use and also if there is no any negative values unsigned int is also
possible to use.
Q #35) Is there any possibility to create customized header file
with C programming language?
Ans) It is possible and easy to create a new header file.
Create a file with function prototypes that needs to use inside the program.
Include the file in ‘#include’ section from its name.
Q #36) Describe dynamic data structure in C programming
language?
Ans) Dynamic data structure is more efficient to the memory.
The memory access occurs as needed by the program.
Q #37) Is that possible to add pointers to each other?
Ans) There is no possibility to add pointers together. Since
pointer contains address details there is no way to retrieve the value from
this operation.
Q #38) What is indirection?
Ans) If you have defined a pointer to a variable or any memory
object, there is no direct reference to the value of the variable. This is
called indirect reference. But when we declare a variable it has a direct
reference to the value.
Q #39) What are the ways to a null pointer can use in C
programming language?
Ans) Null pointers are possible to use in three ways.
- As
an error value.
- As
a sentinel value.
- To
terminate indirection in the recursive data structure.
Q #40) What is the explanation for modular programming?
Ans) The process of dividing the main program into executable
subsection is called module programming. This concept promotes the reusability.
Write a program to
print "hello world" without using semicolon?
There are various ways to
do so. Let's see a program to print "hello world" using if.
1.
#include<stdio.h>
2.
void main(){
3.
if(printf("hello world")){}
4. }
42) Write a program to
swap two numbers without using third variable?
1.
#include<stdio.h>
2.
#include<conio.h>
3.
main()
4.
{
5.
int a=10, b=20;
6.
clrscr();
7.
printf("Before swap a=%d b=%d",a,b);
8.
9.
a=a+b;//a=30 (10+20)
10.
b=a-b;//b=10 (30-20)
11.
a=a-b;//a=20 (30-10)
12.
13.
printf("\nAfter swap a=%d b=%d",a,b);
14.
getch();
15. }
43) Write a program to
print fibonacci series without using recursion?
1.
#include<stdio.h>
2.
#include<conio.h>
3.
void main()
4.
{
5.
int n1=0,n2=1,n3,i,number;
6.
clrscr();
7.
printf("Enter the number of elements:");
8.
scanf("%d",&number);
9.
printf("\n%d %d",n1,n2);//printing 0 and 1
10.
11.
for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed
12.
{
13.
n3=n1+n2;
14.
printf(" %d",n3);
15.
n1=n2;
16.
n2=n3;
17.
}
18.
getch();
19. }
44) Write a program to
print fibonacci series using recursion?
1.
#include<stdio.h>
2.
#include<conio.h>
3.
void printFibonacci(int n){
4.
static int n1=0,n2=1,n3;
5.
if(n>0){
6.
n3 = n1 + n2;
7.
n1 = n2;
8.
n2 = n3;
9.
printf("%d ",n3);
10.
printFibonacci(n-1);
11.
}
12.
}
13.
void main(){
14.
int n;
15.
clrscr();
16.
printf("Enter the number of elements: ");
17.
scanf("%d",&n);
18.
19.
printf("Fibonacci Series: ");
20.
printf("%d %d ",0,1);
21.
printFibonacci(n-2);//n-2 because 2 numbers are already printed
22.
23.
getch();
24. }
45) Write a program to
check prime number in C Programming?
1.
#include<stdio.h>
2.
#include<conio.h>
3.
void main()
4.
{
5.
int n,i,m=0,flag=0;
6.
clrscr();
7.
printf("Enter the number to check prime:");
8.
scanf("%d",&n);
9.
m=n/2;
10.
for(i=2;i<=m;i++)
11.
{
12.
if(n%i==0)
13.
{
14.
printf("Number is not prime");
15.
flag=1;
16.
break;
17.
}
18.
}
19.
if(flag==0)
20.
printf("Number is prime");
21.
getch();
22. }
46) Write a program to
check palindrome number in C Programming?
1.
#include<stdio.h>
2.
#include<conio.h>
3.
main()
4.
{
5.
int n,r,sum=0,temp;
6.
clrscr();
7.
printf("enter the number=");
8.
scanf("%d",&n);
9.
temp=n;
10.
while(n>0)
11.
{
12.
r=n%10;
13.
sum=(sum*10)+r;
14.
n=n/10;
15.
}
16.
if(temp==sum)
17.
printf("palindrome number ");
18.
else
19.
printf("not palindrome");
20.
getch();
21. }
47) Write a program to
print factorial of given number without using recursion?
1.
#include<stdio.h>
2.
#include<conio.h>
3.
void main(){
4.
int i,fact=1,number;
5.
clrscr();
6.
printf("Enter a number: ");
7.
scanf("%d",&number);
8.
9.
for(i=1;i<=number;i++){
10.
fact=fact*i;
11.
}
12.
printf("Factorial of %d is: %d",number,fact);
13.
getch();
14. }
48) Write a program to
print factorial of given number using recursion?
1.
#include<stdio.h>
2.
#include<conio.h>
3.
4.
long factorial(int n)
5.
{
6.
if (n == 0)
7.
return 1;
8.
else
9.
return(n * factorial(n-1));
10.
}
11.
12.
void main()
13.
{
14.
int number;
15.
long fact;
16.
clrscr();
17.
printf("Enter a number: ");
18.
scanf("%d", &number);
19.
20.
fact = factorial(number);
21.
printf("Factorial of %d is %ld\n", number, fact);
22.
getch();
23. }
49) Write a program to
check armstrong number in C?
1.
#include<stdio.h>
2.
#include<conio.h>
3.
main()
4.
{
5.
int n,r,sum=0,temp;
6.
clrscr();
7.
printf("enter the number=");
8.
scanf("%d",&n);
9.
temp=n;
10.
while(n>0)
11.
{
12.
r=n%10;
13.
sum=sum+(r*r*r);
14.
n=n/10;
15.
}
16.
if(temp==sum)
17.
printf("armstrong number ");
18.
else
19.
printf("not armstrong number");
20.
getch();
21. }
50) Write a program to
reverse a given number in C?
1.
#include<stdio.h>
2.
#include<conio.h>
3.
main()
4.
{
5.
int n, reverse=0, rem;
6.
clrscr();
7.
printf("Enter a number: ");
8.
scanf("%d", &n);
9.
while(n!=0)
10.
{
11.
rem=n%10;
12.
reverse=reverse*10+rem;
13.
n/=10;
14.
}
15.
printf("Reversed Number: %d",reverse);
16.
getch();
17. }