cpp interview questions and answers

CPP interview questions and answers



cpp interview questions and answers

CPP interview questions and answers or c++ interview questions and answers

We are going to discuss some Commonly asked c++ interview question.

1. Why we use the const keyword in c++?

Answer: When we don't want to overwrite or change the existing variable values we use the const keyword.

example:                                                                                                                                                    
const int n = 10//it means n will always be 10 if we will try to change its value we will get an error.
               n = 25;  //error: Assignment of read only variable 'n'
                                                                                                                                                                   

2.Size of int, float, double, boolean, char.
  • int ------ 4 bytes (stores the whole number without decimal)
  • float  --- 4 bytes (store decimal number can store up to 7 decimal)
  • double - 8 bytes (store decimal number can store up to 15 decimal)
  • bool ---- 1 byte  (store true or false values)
  • char ---- 1 byte  (store single character/number/ASCII/letter)


3. What will be the output of below code?

#include <iostream>
using namespace std;
int main () {
  float f1 = 35e3;
  double d1 = 12E4;
  cout << f1 << "\n";
  cout << d1;
  return 0;
}

Answer:
35000
120000

Note: 'e' or 'E' indicates the power of 10 in 35e3 (means 35 *10^3) and 12E4(means 12*10^4).

4. How we can find the length of a string whose name is txt?

Ans: txt.length(); or txt.size();



5. Write a c++ program to swap two number without using any third variable.

Ans:
#include <iostream>
using namespace std;
int main()
{
    int a,b;
    cin>>a>>b;
    cout<<"Before swap:\n"<<a<<"\n"<<b;
    a=a*b;
    b=a/b;
    a=a/b;
    cout<<"\nAfter swap:\n"<<a<<"\n"<<b;
    return 0;
}

6. Define Function Overloading in CPP.

When multiple functions have the same name with different parameter is known as function overloading.

Example:
int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)
int plusFunc(int x, int y) {
  return x + y;
}

double plusFunc(double x, double y) {
  return x + y;
}

int main() {
  int myNum1 = plusFunc(65);
  double myNum2 = plusFunc(4.76.26);
  cout << "Int: " << myNum1 << "\n";
  cout << "Double: " << myNum2;
  return 0;
}

7. What is OOP and Advantages of OOP over procedural programming.

Ans:
OOP stands for Object-Oriented Programming.

Advantages of OOP over Procedural programming are:

  • Faster and easier to execute.
  • Cleaner code or clear structure of the program.
  • keeps code dry (means same code will not repeat again)
  • We can reuse code.
8. What is class and how to create a class in c++?

Everything in c++ is associated with class and object, the class is basically a template for an object. Inside the class, we have attributes and methods called as class members.

To create a class we use the class keyword.



Example

Create a class called "MyClass":
class MyClass {       // The class  
public:             // Access specifier    
int n;        // Attribute (int variable)    
string str;  // Attribute (string variable)};


Example explained
  • The class keyword is used to create a class called MyClass.
  • The public keyword is an access specifier, which specifies that members (attributes and methods) of the class are accessible from outside the class.
  • Inside the class, there is an integer variable n and a string variable str. When variables are declared within a class, they are called attributes.
  • Always end the class definition with a semicolon (;).

9. What is an object and how to create an object in c++?

An object is an instance of the class, the object inherits all the variable and function from its belonging class.

Creating an object

First, we have to create a class.
In our previous answer, we have created a class known as MyClass so we are going to use it for creating an object.

To create an object of class we have to specify the class name followed by object name.
Example:
MyClass MyObj;
In the above example, we have created an object of the class named MyObj.

To access class attributes we use a dot (.) syntax.
Example:
MyObj.n = 10;

Example

Create an object called "MyObj" and access the attributes:
class MyClass {       // The class  
public:             // Access specifier    
int n;        // Attribute (int variable)    
string str;  // Attribute (string variable)};

int main() {
  MyClass MyObj;  // Create an object of MyClass
  // Access attributes and set values  

  MyObj.n 10
  MyObj.str = "Some text";
  // Print attribute values 

  cout << MyObj.n << "\n";
  cout << MyObj.str;
  return 0;
}
10. What is method in C++?

Methods are function which belongs to the class. It can be defined inside or outside class, when it is outside class we have to declare method inside.

Inside Class Example

class MyClass {        // The class  
public:              // Access specifier    
void Method() {  // Method/function defined inside the class      
cout << "Hello World!";
    }
};

int main() {
MyClass myObj;     // Create an object of MyClass  

myObj.Method();  // Call the method  
return 0;
}

Outside Class Example

class MyClass {        // The class 
public:              // Access specifier    
void Method();   // Method/function declaration
};

// Method/function definition outside the class

void MyClass::Method() {
  cout << "Hello World!";
}

int main() {
  MyClass myObj;     // Create an object of MyClass  

  myObj.Method();  // Call the method  
  return 0;
}

11.What is Constructor in C++?

The constructor is a special method inside class whose name is same as class name from which it belongs and it is always public with no return value.

Example of Constructor

class MyClass {     // The class 
public:           // Access specifier    
MyClass() {     // Constructor      
cout << "Hello World!";
    }
};

int main() {
  MyClass myObj;    // Create an object of MyClass (this will call the constructor)  

  return 0;
}
12. How many types of access specifier are there in c++?

  • public- class member can be accessed from outside of the class.
  • private-Class member can access only inside a class which means it can't be accessible from outside the class.
  • protected-can't accessible from outside the class but inherited class can access.

13. What is Encapsulation in C++?
Hiding sensitive data from the user is known as encapsulation it can be achieved by using private access specifier.
If we want other's to read and modify private members we can use get and set method.

Example

#include <iostream>
using namespace std;

class Employee {
  private:
    // Private attribute    

    int salary;

  public:
    // Setter    

    void setSalary(int s) {
      salary = s;
    }
    // Getter    

  int getSalary() {
      return salary;
    }
};

int main() {
  Employee myObj;
  myObj.setSalary(50000);
  cout << myObj.getSalary();
  return 0;
}
14. What is inheritance in C++?
Inheriting attributes and methods from other class is known as inheritance.
The class which inherits from another class is known as child class.
The class being inherited from is known as parent class.
To inherit from a class we use: symbol

Example of Inheritance

// Base class
class Vehicle {
  public:
    string brand = "Ford";
    void honk() {
      cout << "Tuut, tuut! \n" ;
    }
};

// Derived class

class Car: public Vehicle {
  public:
    string model = "Mustang";
};

int main() {
  Car myCar;
  myCar.honk();
  cout << myCar.brand + " " + myCar.model;
  return 0;
}

  • In the above example we can also drive another class from class car and for that base class will be car and that will be grandchild of Vehicle class.(Multilevel inheritance)

Example

// Base class (parent)
class MyClass {
  public:
    void myFunction() {
      cout << "Some content in parent class." ;
    }
};

// Derived class (child)

class MyChild: public MyClass {
};

// Derived class (grandchild)

class MyGrandChild: public MyChild {
};

int main() {
  MyGrandChild myObj;
  myObj.myFunction();
  return 0;
}
  • A class can be drived from more than one base class and the base classes will be seprated by comma (Multiple Inheritance)

Example

// Base classclass MyClass {
  public:
    void myFunction() {
      cout << "Some content in parent class." ;
    }
};

// Another base class

class MyOtherClass {
  public:
    void myOtherFunction() {
      cout << "Some content in another class." ;
    }
};

// Derived class

class MyChildClass: public MyClass, public MyOtherClass {
};

int main() {
  MyChildClass myObj;
  myObj.myFunction();
  myObj.myOtherFunction();
  return 0;
}
15. What is polymorphism in C++?
Polymorphism means having many forms when various classes are related to one another through inheritance than this is known as polymorphism. One base class having many derived class.

Example

// Base class
class Animal {
  public:
    void animalSound() {
    cout << "The animal makes a sound \n" ;
  }
};

// Derived class

class Pig : public Animal {
  public:
    void animalSound() {
    cout << "The pig says: wee wee \n" ;
   }
};

// Derived class

class Dog public Animal {
  public:
    void animalSound() {
    cout << "The dog says: bow wow \n" ;
  }
};

int main() {
  Animal myAnimal;
  Pig myPig;
  Dog myDog;

  myAnimal.animalSound();
  myPig.animalSound();
  myDog.animalSound();
  return 0;
}
16. File Manupulation in C++?
First, to work with files we have to include fstream header file with iostream header file.
Objects included in fstream are:

  • ofstream- Used to create and write files.
  • ifstream- Used to read the file.
  • fstream- Combination of ofstream and ifstream, used to create, read and write files.

Example of Creating file

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

int main() {
  // Create and open a text file  

ofstream MyFile("filename.txt");

  // Write to the file  

MyFile << "File creation!";

  // Close the file  

MyFile.close();
}

Example of reading file

// Create a text string, which is used to output the text file
string myText;

// Read from the text file 

ifstream MyReadFile("filename.txt");

// Use a while loop together with the getline() function to read the file line by line

while (getline (MyReadFile, myText)) {
  // Output the text from the file  

cout << myText;
}

// Close the file

MyReadFile.close();

17. Exception in C++?
When our code goes wrong then an error occurs which stops our program and shows an error message. The technical term for this is throwing an exception.
There is three exceptional handling keyword in c++:

  • try- block of code to be tested.
  • throw- throw an exception when problem is detected.
  • catch- block of statement to be executed when an error occurs.

Example

try {
  int age = 17;
  if (age > 20) {
    cout << "Access granted - you are old enough.";
  } else {
    throw (age);
  }
}
catch (int myNum) {
  cout << "Access denied - You must be at least 18 years old.\n";
  cout << "Age is: " << myNum;
}

No comments:

For Query and doubts!

Powered by Blogger.