Loading...

C and C++ Interview Questions and Answers

by GangBoard Admin, January 28, 2019

In case you’re searching for C and C++ Interview Questions and answers for Experienced or Freshers, you are at the correct place. Gangboard offers Advanced C and C++ Interview Questions and answers that assist you in splitting your C and C++ interview and procure dream vocation as C and C++ Developer.

Q1) What is C++?

Answer: C++ is a programming language that is a superset of the C Language. C++ supports Classes which is not present in C. Unlike C, C++ is an object-oriented programming language supporting OOPS concepts like Polymorphism, Inheritance, etc.,

Q2) List out the differences between C and C++

Answer:

S.No. C C ++
1. Procedure Oriented Programming Object Oriented Programming
2. No Exception handling Provides Exception Handling
3. No References Supports References.
4. No OOPS Concept. Provides OOPS concepts like Inheritance, Polymorphism etc.,

 Q3) What are the differences between Pointer and Reference?

Answer:

S.No. Pointer Reference
1. It is an alias for another variable. It stores the address of a variable.
2. Must be initialized when declared. Initialization is not mandatory while declaration of a pointer.
3. Cannot be assigned to NULL value. Pointer can be assigned to NULL value.
4. Cannot be made to change the value once the reference is assigned. Pointer can be made to point to different address or simply reassigned.
5. Does not require * operator to access the value. Requires * operator to access the value stored in the address which it points to.

Q4) Name the OOPS concepts available in C++?

Answer:

  • Polymorphism
  • Inheritance
  • Encapsulation
  • Abstraction
  • Data Binding

Q5) What is a Class?

Answer:

A class is basically a user defined custom data type which is like a blue print that show cases the characteristics and behavior. For example, let’s take a bird. The characteristic of a bird are feathers, beak etc., The behavior or Features of a bird are Flying, eating etc., There are different variety of birds. So we can define a Class named bird and using this class’s characteristics and behavior we can declare different types of birds.

Q6) What is an object?

Answer:

Objects are instances of the class through which one can access the member variables and member functions. For example, consider the following class:

Class Bird
{
                char name [50];
};
Bird B1;

Here, B1 is an object of the class Bird. Through object B1, we can access the data member name and assign values. Similarly, we can create multiple objects for a class.

Q7) What is Inheritance?

Answer: Inheritance is the concept of reusing existing functionality by inheriting from it. By this way we eliminate redundancy of code. For example, we inherit some the genes from our father or grandfather. Similarly one can inherit an existing class to derive a new class. The exiting class is the base class while the inherited class will be derived class.

Q8) What is Polymorphism?

Answer: Polymorphism is the concepts of having one functionality do multiple things. The words “poly”(many) and “morph” (forms) is itself explain the concept.

Q9) What are the types of Polymorphism?

Answer:  Polymorphism is classified into two types namely:

  • Compile-time Polymorphism or Overloading
  • Run-time Polymorphism or Overriding

Q10) What is Encapsulation?

Answer: Encapsulation is the process of combining the data members and member functions together into a single unit so that outside members cannot access the data. Suppose a class contains private data members the only the member function of the class can access the data members.

Q11) What is Abstraction?

Answer: Abstraction is the process of revealing only vital elements without showing the actual implementation. Suppose a class contains public members then these public members can be accessed from outside the class too. But if these members were private then they cannot be accessed outside the class.

Q12) What are Storage Classes?

Answer: Storage class are nothing, but which determines the lifetime or scope of variables and functions. The different types of storage classes available in C++ are:

  1. Auto
  2. Static

Extern

  1. Register
  2. Mutable

Q13) When register storage class should be used?

Answer: Memory access in CPU register is speedy and the look-up execution time is way more efficient than normal memory in stack. So, when a variable is being used regularly or frequently then it can be declared as a register storage class.

Q14) What are access specifiers in C++?

Answer: Access specifiers are the keywords that determines the availability of the data members/member functions of a class outside.  The three access specifiers available in C++ are:

  • Public: Data members and Member functions declared under public specification can be accessed from outside the class.
  • Private: Data members and Member functions declared under private specification can be accessed only within the class and cannot be accessed from outside the class even by derived class objects.
  • Protected: Data members and Member functions declared under protected specification can be accessed by its own class and the derived classes.

Q15) What is constructor?

Answer: A constructor is a special member function of a class that initializes the class object. The compiler provides a default constructor if the user has not provided a constructor. The constructor function name should be declared as the same name of Class. For example:

Class Bird
{
                char name [50];
   public:
                Bird ()
{
       printf(“\nThis is Default Constructor of Class Bird\n”)
}
};

There are basically three types of constructor available namely:

  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor

Q16) What is destructor?

Answer: A destructor is a special member function of a class that destroys the resources that have been allocated to the class object. The destructor class name is same as that of the class but prefixed with a ~ symbol.

For example:

Class Bird
{                char name [50];
   public:
                ~Bird ()
{
       printf(“\nThis is Destructor of Class Bird\n”)
}
};

Q17) Explain Virtual Destructor

Answer: A virtual destructor does the same function as that of a normal destructor but along with the destruction of derived class objects too. The virtual keyword must be employed before the function name as shown:

virtual ~Bird()

Q18) What is copy constructor?

Answer: A copy constructor is one of the types of constructor that is used for initializing a class object with the help of another object. It takes the same name as that of the class with one const class reference object as argument For example:

Class Bird
{
                char name [50];
   public:
Bird (const class &B)
{
       name = B.name;
}
};

Q19) Explain Function Overloading

Answer: Function overloading as the name suggest, overloading a function to give different functionality. The function name will be same, but it must differ in either of the following conditions:

  1. Differ in Number of Arguments and\or
  2. Differ in the type of Input Arguments

Example:

#include <iostream>
using namespace std;
void Show (int i) {
  cout << " Here is int " << i << endl;
}
void Show (double  f) {
  cout << " Here is float " << f << endl;
}
void Show (char* c) {
  cout << " Here is char* " << c << endl;
}
int main() {
  Show (10);
  Show (10.10);
  Show ("ten");
  return 0;
}

Q20) Can a constructor be overloaded?

Answer: Yes, but only through number of input arguments. Example – Default and parameterized constructors.

Q21) Can a destructor be overloaded?

Answer: No. A destructor must simply destroy all the resources allocated for the object.

Q22) Explain Function Overriding

Answer: Function Overriding is a run time polymorphism which allows derived class to provide its own implementation of the base class member functions. The newly implemented function in derived class is called Overridden Function.

Example:

class Base 
{ 
public: 
    void display () 
    { cout<< "Base Class Display" <<endl; } 
};  
class Derived: public Base 
{ 
public: 
    void display () 
    { cout<< "Derived Class Display" <<endl; } 
};

Q23) What are Virtual Functions?

Answer: Virtual functions are base class member functions which helps to resolve function calls when there is redefinition for the same function provided by the derived class. Some of the important points to be remembered:

  • Virtual functions of the base class can be redefined in the derived class.
  • Provided virtual function in base class, when there is a base class pointer pointing to derived class object, the invoke of the function will call the derived class implementation.
  • Virtual is just a keyword used to help C++ deiced at run-time which method has to be called depending on the type of the object pointed by base class pointer.

Example:

#include<iostream> 
using namespace std; 
class Base 
{ 
public: 
    void F_1() { cout << "Base F-1\n"; } 
    virtual void F_2() { cout << " Base F-2\n"; } 
    virtual void F_3() { cout << " Base F-3\n"; } 
    virtual void F_4() { cout << " Base F-1\n"; } 
}; 
class Derived : public Base 
{ 
public: 
    void F_1() { cout << "Derived F-1\n"; } 
    void F_2() { cout << "Derived F-2\n"; } 
    void F_4(int x) { cout << "Derived F-4\n"; } 
}; 
int main() 
{ 
    Base *P; 
    Derived D1; 
    P = &D1; 
     // Early binding because F_1() is non-virtual in base 
    P->F_1(); 
     // Late binding 
    P->F_2(); 
    // Late binding (
    P->F_3(); 
    // Late binding 
    P->F_4(); 
  }
Output:
Base F-1
Derived F-2
Base F-3
Base F-4

Here base class pointer points to derived class object. Function F_1() was not virtual and it invoked base class function whereas Function F_2() was virtual and hence it invoked derived class method.

Q24) What is pure virtual function?

Answer: Pure virtual function is a type of virtual function which has only declaration and not definition. A pure virtual function declaration is assigned with zero. All deriving class must implement the pure virtual function.

virtual Display() = 0;

Q25) What is an Abstract Class?

Answer: A class is said to be abstract when it contains at least one pure virtual function. Instantiation is not allowed for an abstract class. And the deriving class must implement or provide definition for the pure virtual functions.

Example:

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

Q26) What is the use of pure virtual function?

Answer: A pure virtual function does not have implementation in base class. This will be useful during scenarios where no actual implementation is required in the base class context. For example let’s say we have a base class named Shape which is having a function “DrawShape()” as pure virtual. In base class there is actually no need to give a definition. Now, when a Class Square derives from Class Shape, it provides an actual definition for DrawShape() as drawing a square.

Q27) Can Constructors be virtual?

Answer: In order to create an object, we need to know the complete information about it or the exact type of what we want to create. Hence, a constructor cannot be virtual.

Q28) Can Destructors be declared as pure virtual function?

Answer: Yes, but we must define the destructor anyways.

Q29) What is virtual class?

Answer: A virtual class resolves the ambiguity caused due to multilevel inheritance. Suppose two Classes B and C derives from a Base Class A. And another derived Class D derives from Classes B and C. Now when we create an object for Class D, it will have multiple copies of Base Class B. But if the Base Class A is derived as virtual by Classes B and C, this will be prevented.

Example:

Class A
{ … };
Class B: virtual public A
{ … };
Class C: virtual public A
{ … };
Class D: public B, public C
{ … };

Q30) What are the different types of inheritance?

Answer:

  • Multiple: (Class A, B) -> Class C
  • Multi-Level: Class A -> Class B -> Class C
  • Hierarchical: Class A -> (Class B, C) -> Class D

Q31) What are new and delete operator?

Answer: The new operator is used to dynamically allocate memory and delete operator is used to destroy the memory allocated by the new operator.

Q32) What are Friend Functions?

Answer: Friend functions are special member functions of a class which can access the data members and member functions from outside the class without using the Class object.

Example:
#include <iostream>
using namespace std;
class Length
{
    private:
        int value;
    public:
        Length () {  value = 0; }
        friend int addExtra(Distance); //friend function
};
int addFive(Length l) // friend function definition
{   
 //accessing private data from non-member function
    l.value += 5;
    return l.value;
}
int main()
{
    Length L;
    cout<<"Length: "<< addExtra(L);
    return 0;
}

Q33) What is a Friend class?

Answer: Similar to friend function one class can be made as a friend to another class. Let’s say X and Y are separate classes. When X is made friend to class Y, the member functions of Class X becomes friend functions to Class Y. Member functions of Class X can access the private and protected data of Class Y but Class Y cannot access the same of ClassX.

class X;
class Y
{
   // class X is a friend class of class Y
   friend class X;
   ... .. ...
}
class X
{
   ... .. ...
}

Q34) What is a scope resolution operator?

Answer: A scope resolution operator :: is used for defining the member functions of a class outside its class. It is also used for resolving the scope of the global variables.

class Line {
   public:
      Line();  // This is the constructor
   private:
      double length;
};
// Member functions definitions including constructor
Line::Line() {
   cout << "Object is being created" << endl;
   length = 0;
}

Q35) What are actual and formal parameters?

Answer: Actual parameters are variables or arguments that are being passed to the function during a function call.

Formal parameters are the variables or arguments that are being received in the functions.

Q36) Explain Call by Value?

Answer: Call by Value method passes only the values of the actual parameters to the formal parameters. So, two different copies are made. Any change made to the formal parameters will not affect the actual parameters.

Example:

#include <iostream>
using namespace std; 
// function declaration
void Exchange(int A, int B) {
   int temp;
   temp = A; 
   A = B;    
   B = temp; 
}
int main () {
   int X = 100, Y = 200;
   cout << "Before Exchange, value of X :" << X << endl;
   cout << "Before Exchange, value of Y :" << Y << endl;
   Exchange (X, Y);
   cout << "After Exchange, value of X :" << X << endl;
   cout << "After Exchange, value of Y :" << Y << endl;
    return 0;
} 

Output:
Before Exchange, value of X :100
Before Exchange, value of Y :200
After Exchange, value of X :100
After Exchange, value of Y :200

Q37) Explain Call by Address?

Answer: In Call by Address, the address of the actual parameters are passed to the formal parameters which are pointer variables. Hence, any change made to the formal parameters are reflected in the actual parameters too.

Example:

#include <iostream>
using namespace std;
// function declaration
void Exchange(int *A, int *B) {
   int temp;
   temp = *A; 
   *A = *B;  
   *B = temp; 
} 
int main () {
   int X = 100, Y = 200; 
   cout << "Before Exchange, value of X :" << X << endl;
   cout << "Before Exchange, value of Y :" << Y << endl;
   Exchange (&X, &Y);
   cout << "After Exchange, value of X :" << X << endl;
   cout << "After Exchange, value of Y :" << Y << endl;
    return 0;
}
Output:
Before Exchange, value of X :100
Before Exchange, value of Y :200
After Exchange, value of X :200
After Exchange, value of Y :100

Q38) Explain Call by Reference?

Answer: In Call by reference the formal parameters are reference variables and so both the actual and formal parameters point to the same memory locations. Hence, any changes made to the formal parameters will reflect in the actual parameters too.

Example:

#include <iostream>
using namespace std;
 // function declaration
void Exchange(int &A, int &B) {
   int temp;
   temp = *A; 
   *A = *B; 
   *B = temp; 
}
 int main () {
   int X = 100, Y = 200;
   cout << "Before Exchange, value of X :" << X << endl;
   cout << "Before Exchange, value of Y :" << Y << endl;
   Exchange (X, Y);
   cout << "After Exchange, value of X :" << X << endl;
   cout << "After Exchange, value of Y :" << Y << endl;
   return 0;
}
Output:
Before Exchange, value of X :100
Before Exchange, value of Y :200
After Exchange, value of X :200
After Exchange, value of Y :100

Q39) Explain command line arguments?

Answer: Main() is the entry point of a C++ program and it behaves like a function. It takes arguments like any other functions except that it cannot be invoked from within the program. Here, command line arguments come into picture. The arguments passed through the command line are received by the main function as input arguments.

Example:

int main( int ARGC, char *ARGV[]) {
}

Here,ARGC – Count of  number of arguments passed through the command line.
ARGV – Is the vector or array containing the values of the arguments
ARGC[0] – is the program name.
Suppose
$ ./a.out 25 35
ARGC = 3
ARGV [0] = a.out
ARGV [1] = 25
ARGV [2] = 35  

Q40) Explain about Recursive Functions?

Answer: Recursive functions are functions which call itself. The functionality of recursive functions are similar to loops – repeats the same logic again and again. Important points to consider for recursive functions:

  1. Function Call from within the function
  2. Proper exit condition/break point in the logic.

Example:

#include<iostream>
using namespace std;
void print (int num)

{
                cout<<”\n”<<num;
                if (num == 5)
               { 
return; 
}
else
{
                num++;
                print(num);

}
}
int main()
{               
 print(1);                
 return 0;
}

Q41) What is stack overflow and when does it occur?

Answer: A stack overflow denotes that the stack memory is filled and memory can be stored further in the Stack. A stack overflow occurs when a recursive function keeps on executing without any exit condition or break point. For each and every recursive call, a new function call address will be written into the stack memory thus leading to stack overflow when there is no proper exit condition.

Q42) What is shallow copy and deep copy?

Answer: Shallow copy performs bit-by-bit memory dump from one object to another whereas Deep copy performs field by field memory dump. Copy Constructor and overloaded assignment operator are examples of deep copy.

Q43) How does a normal object and a pointer object access members of a class?

Answer: Normal object access class members using . dot operator.

Pointer objects access class members using -> arrow operator.

Q44) What are the different types of initialization available in C++?

Answer:

  • Traditional C Way: int num = 10;
  • Constructor notation: int num(10);

Q45) What are exit and abort functions?

Answer: An exit call invokes the destructor of all constructed objects and then does a graceful termination from the program.

An abort call abruptly ends the program and dumps core memory. It does not call any destructor.

Q46) Compare C Struct and C++ Struct?

Answer:

S.No C Struct C++ Struct
1. Cannot have functions. Can have member functions.
2. Cannot have static members. Can have static members.
3. Struct keyword is necessary while declaring structure type variables. Do not require any keyword for declaring structure type variables.
4. Size of empty structure is undefined. Size of empty structure is 1.

Q47) What is an interface?

Answer: An interface is class which contains only pure virtual functions. It just provides a group of functions without any definition that must be overridden by the implemented classes. If all the functions in an abstract class are pure virtual then it becomes an interface.

     Bird (const class &B)
{
       name = B.name;
}
};

Q48) What does delete[] do?

Answer: The delete[] operator deletes the array of dynamically allocated memory allocated by the new[] operator.  

No Comments


Leave a Reply

Your email address will not be published Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

Online Training Quick Enquiry






Get Free Online training