Here are the list of most frequently asked C and C++ Interview Questions and Answers in technical interviews. These questions and answers are suitable for both freshers and experienced professionals at any level.
C programming language supports multiple features
Data types divided into two types
Errors in c programming are divided in two types. They are
Here we can discuss about the compile time they are
A runtime error is a program error that occurs while the program is running.
Function is nothing but collection of set of statements called function .they are two type
The functions which are coming with compiler by default that functions we can
call it as pre defined functions
Ex: qrt,pow etc
The functions which are written by the programmer, then we can call it as user defined functions. To write user defined function need three components. They are below
Control statements are divided into three types
These statements are decision making statements in source code. This are several types
When we are going to use repeated code we will use iterative statements. These are several types
Jump statements are used to break the loops , continue the loop and jump to the required statement. These are several types
Class defines a datatype, it's type definition of category of thing(s). But a class actually does not define the data, it just specifies the structure of data. To use them you need to create objects out of the class. Class can be considered as a blueprint of a building, you can not stay inside blueprint of building, you need to construct building(s) out of that plan. You can create any number of buildings from the blueprint, similarly you can create any number of objects from a class.
- class Vehicle
- {{"{"}}
- public:
- int numberOfTyres;
- double engineCapacity;
- void drive(){{"{"}}
- // code to drive the car
- }
- };
Object is the instance of a class, which is concrete. From the above example, we can create instance of class Vehicle as given below
- Vehicle vehicleObject;
We can have different objects of the class Vehicle, for example we can have Vehicle objects with 2 tyres, 4tyres etc. Similarly different engine capacities as well.
Access specifiers are used to define how the members (functions and variables) can be accessed outside the class. There are three access specifiers defined which are public, private, and protected
Members declared as private are accessible only with in the same class and they cannot be accessed outside the class they are declared.
Members declared as public are accessible from any where.
Members declared as protected can not be accessed from outside the class except a child class. This access specifier has significance in the context of inheritance.
- A class’s interface should be sensible enough. It should behave the way user expects it to.
- It should be designed from the outside in.
Inheritance is the process wherein characteristics are inherited from ancestors.
Similarly, in Java, a subclass inherits the characteristics (properties and methods)
of its superclass (ancestor).
For example, a vehicle is a superclass
and a car is a subclass. ... The inheritance mechanism is very useful in code reuse.
The biggest benefits of proper inheritance are :
Substitutability: The objects of a properly derived class can be easily and safely substituted for an object of its base class.
Extensibility: The properly derived class can be freely and safely used in place of its base class even if the properly derived class is created a lot later than defining the user code. Extending the functionalities of a system is much easier when you add a properly derived class containing enhanced functionalities.
Yes, there are a few rules about inlining :
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:
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 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.
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.
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.
// A C program to demonstrate different storage // classes #include <stdio.h> // declaring and initializing an extern variable extern int x = 9; // declaring and initialing a global variable z // simply int z; would have initialized z with // the default value of a global variable which is 0 int z = 10; int main() {{"{"}} // declaring an auto variable (simply // writing "int a=32;" works as well) auto int a = 32; // declaring a register variable register char b = 'G' ; // telling the compiler that the variable // z is an extern variable and has been // defined elsewhere (above the main // function) extern int z; printf ( "Hello World!\n" ); // printing the auto variable 'a' printf ( "\nThis is the value of the auto " " integer 'a': %d\n" ,a); // printing the extern variables 'x' // and 'z' printf ( "\nThese are the values of the" " extern integers 'x' and 'z'" " respectively: %d and %d\n" , x, z); // printing the register variable 'b' printf ( "\nThis is the value of the " "register character 'b': %c\n" ,b); // value of extern variable x modified x = 2; // value of extern variable z modified z = 5; // printing the modified values of // extern variables 'x' and 'z' printf ( "\nThese are the modified values " "of the extern integers 'x' and " "'z' respectively: %d and %d\n" ,x,z); // using a static variable 'y' printf ( "\n'y' is a static variable and its " "value is NOT initialized to 5 after" " the first iteration! See for" " yourself :)\n" ); while (x > 0) {{"{"}} static int y = 5; y++; // printing value of y at each iteration printf ( "The value of y is %d\n" ,y); x--; } // exiting printf ( "\nBye! See you soon. :)\n" ); return 0; } |
Encapsulation is the mechanism by which data and associated operations/methods are bound together and thus hide the data from outside world. It's also called data hiding. In c++, encapsulation achieved using the access specifiers (private, public and protected). Data members will be declared as private (thus protecting from direct access from outside) and public methods will be provided to access these data.
- class Person
- {{"{"}}
- private:
- int age;
- public:
- int getAge(){{"{"}}
- return age;
- }
- int setAge(int value){{"{"}}
- if(value > 0){{"{"}}
- age = value;
- }
- }
- };
In the class Person, access to the data field age is protected by declaring it as private and providing public access methods. What would have happened if there was no access methods and the field age was public? Anybody who has a Person object can set an invalid value (negative or very large value) for the age field. So by encapsulation we can preventing direct access from outside, and thus have complete control, protection and integrity of the data.
Data abstraction refers to hiding the internal implementations and show only the necessary details to the outside world. In C++ data abstraction is implemented using interfaces and abstract classes.
- class Stack
- {{"{"}}
- public:
- virtual void push(int)=0;
- virtual int pop()=0;
- };
- class MyStack : public Stack
- {{"{"}}
- private:
- int arrayToHoldData[]; //Holds the data from stack
- public:
- void push(int) {{"{"}}
- // implement push operation using array
- }
- int pop(){{"{"}}
- // implement pop operation using array
- }
- };
In the above example, the outside world only need to know about the Stack class and its push, pop operations. Internally stack can be implemented using arrays or linked lists or queues or anything that you can think of. This means, as long as the push and pop method performs the operations work as expected, you have the freedom to change the internal implementation with out affecting other applications that use your Stack class.
Inheritance allows one class to inherit properties of another class. In other words, inheritance allows one class to be defined in terms of another class.
- class SymmetricShape
- {{"{"}}
- public:
- int getSize()
- {{"{"}}
- return size;
- }
- void setSize(int w)
- {{"{"}}
- size = w;
- }
- protected:
- int size;
- };
- // Derived class
- class Square: public SymmetricShape
- {{"{"}}
- public:
- int getArea()
- {{"{"}}
- return (size * size);
- }
- };
In the above example, class Square inherits the properties and methods of class SymmetricShape. Inheritance is the one of the very important concepts in C++/OOP. It helps to modularise the code, improve reusability and reduces tight coupling between components of the system.
Most of the times compilers will do optimization to the code to speed up the program. For example in the below code,
- int a = 10;
- while( a == 10){{"{"}}
- // Do something
- }
compiler may think that value of 'a' is not getting changed from the program and replace it with 'while(true)', which will result in an infinite loop. In actual scenario the value of 'a' may be getting updated from outside of the program.
Volatile keyword is used to tell compiler that the variable declared using volatile may be used from outside the current scope so that compiler wont apply any optimization. This matters only in case of multi-threaded applications
In the above example if variable 'a' was declared using volatile, compiler will not optimize it. In shot, value of the volatile variables will be read from the memory location directly.
In c++, variables can be initialized in two ways, the traditional C++ initialization using "=" operator and second using the constructor notation.
- int i = 10;
variable i will get initialized to 10.
- int i(10);
Implicit conversions are performed when a type (say T) is used in a context where a compatible type (Say F) is expected so that the type T will be promoted to type F.
short a = 2000 + 20;
In the above example, variable a will get automatically promoted from short to int. This is called implicit conversion/coercion in c++.
C++ inline functions are special functions, for which the compiler replaces the function call with body/definition of function. Inline functions makes the program execute faster than the normal functions, since the overhead involved in saving current state to stack on the function call is avoided. By giving developer the control of making a function as inline, he can further optimize the code based on application logic. But actually, it's the compiler that decides whether to make a function inline or not regardless of it's declaration. Compiler may choose to make a non inline function inline and vice versa. Declaring a function as inline is in effect a request to the compiler to make it inline, which compiler may ignore. So, please note this point for the interview that, it is upto the compiler to make a function inline or not.
- inline int min(int a, int b)
- {{"{"}}
- return (a < b)? a : b;
- }
- int main( )
- {{"{"}}
- cout << "min (20,10): " << min(20,10) << endl;
- cout << "min (0,200): " << min(0,200) << endl;
- cout << "min (100,1010): " << min(100,1010) << endl;
- return 0;
- }
If the complier decides to make the function min as inline, then the above code will internally look as if it was written like
- int main( )
- {{"{"}}
- cout << "min (20,10): " << ((20 < 10)? 20 : 10) << endl;
- cout << "min (0,200): " << ((0 < 200)? 0 : 200) << endl;
- cout << "min (100,1010): " << ((100 < 1010)? 100 : 1010) << endl;
- return 0;
- }
We organize our C++ programs into different source files (.cpp, .cxx etc). When you consider a source file, at the preprocessing stage, some extra content may get added to the source code ( for example, the contents of header files included) and some content may get removed ( for example, the part of the code in the #ifdef of #ifndef block which resolve to false/0 based on the symbols defined). This effective content is called a translation unit. In other words, a translation unit consists of
A symbol is said to be linked internally when it can be accessed only from with-in the scope of a single translation unit. By external linking a symbol can be accessed from other translation units as well. This linkage can be controlled by using static and extern keywords.
template <typename T, typename U> struct is_same {{"{"}} static const bool value = false; }; template <typename T> struct is_same<T, T> {{"{"}} static const bool value = true; }; template <class A, class B> bool IsSameClass() {{"{"}} return is_same<A, B>::value; }
Although you can call an inline function from within itself, the compiler may not generate inline code since the compiler cannot determine the depth of recursion at compile time. A compiler with a good optimizer can inline recursive calls till some depth fixed at compile-time (say three or five recursive calls), and insert non-recursive calls at compile time for cases when the actual depth gets exceeded at run time.