Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address
Withoutbook LIVE Mock Interviews
C++: It's a powerful and versatile programming language widely used for system/software development, game development, embedded systems, and more. Introduction

1. What is C++?

C++ is a high-level programming language developed by Bjarne Stroustrup at Bell Labs in 1979. It is an extension of the C programming language and provides features like object-oriented programming (OOP), generic programming, and more.

2. Why learn C++?

C++ is widely used in various domains including system/application software, game development, embedded systems, and more. It offers performance benefits and flexibility, making it a valuable skill for programmers.

3. What are the basic features of C++?

Some basic features of C++ include:

  • Object-oriented programming (OOP)
  • Classes and objects
  • Inheritance
  • Polymorphism
  • Encapsulation
  • Templates
  • Exception handling
  • Standard Template Library (STL)

4. How to print "Hello, World!" in C++?

    
#include 
using namespace std;

int main() {
    cout << "Hello, World!" << endl;
    return 0;
}
    
  
Syntax

1. What is the basic syntax in C++?

The basic syntax in C++ includes:

  • Statements terminated by a semicolon (;)
  • Curly braces ({}) to define blocks of code
  • Comments: Single-line (//) and multi-line (/* */)
  • Function definitions and calls
  • Variable declarations and assignments
  • Control structures: if, else, while, for, switch, etc.
  • Preprocessor directives: #include, #define, etc.

2. What is a statement in C++?

A statement in C++ is a single executable instruction. It typically ends with a semicolon (;).

3. What are comments in C++?

Comments are used to document code and are ignored by the compiler. C++ supports single-line comments (//) and multi-line comments (/* */).

4. How to declare variables in C++?

    
// Syntax for variable declaration:
data_type variable_name;

// Example:
int num;
float salary;
char letter;
    
  
Data Types

1. What are data types in C++?

Data types in C++ define the type and size of data that a variable can hold. C++ supports various data types including:

  • Primitive data types: int, float, double, char, bool, etc.
  • Derived data types: Arrays, Pointers, References
  • User-defined data types: Structures, Classes, Enumerations

2. What are primitive data types in C++?

Primitive data types represent the basic building blocks of data in C++. Some commonly used primitive data types include:

  • int: Integer data type
  • float: Floating-point data type
  • double: Double-precision floating-point data type
  • char: Character data type
  • bool: Boolean data type (true or false)

3. How to declare variables with different data types in C++?

    
// Syntax for variable declaration:
data_type variable_name;

// Examples:
int num;
float salary;
double pi;
char letter;
bool is_valid;
    
  
Variables

1. What are variables in C++?

In C++, a variable is a named memory location used to store data. It has a data type that specifies the type of data it can hold.

2. How to declare variables in C++?

To declare a variable in C++, you need to specify its data type followed by the variable name. Here's the syntax:

    
data_type variable_name;
    
  

For example:

    
int num;
float salary;
char letter;
    
  

3. What are the rules for naming variables in C++?

Some rules for naming variables in C++ are:

  • Variable names can contain letters, digits, and underscores.
  • Variable names cannot start with a digit.
  • Variable names are case-sensitive.
  • Variable names cannot be keywords or reserved words.

4. How to initialize variables in C++?

You can initialize variables at the time of declaration. Here's the syntax:

    
data_type variable_name = initial_value;
    
  

For example:

    
int num = 10;
float salary = 1000.50;
char letter = 'A';
    
  
Constants

1. What are constants in C++?

In C++, a constant is a value that cannot be changed during the execution of a program. Once defined, its value remains the same throughout the program.

2. How to define constants in C++?

You can define constants in C++ using the 'const' keyword or using preprocessor directives like #define. Here's how:

    
// Using const keyword:
const data_type constant_name = value;

// Using #define directive:
#define CONSTANT_NAME value
    
  

For example:

    
// Using const keyword:
const int MAX_VALUE = 100;

// Using #define directive:
#define PI 3.14159
    
  

3. What are the advantages of using const over #define for constants?

Using const has several advantages over #define for defining constants:

  • Const variables have a data type associated with them, making them type-safe.
  • Const variables are scoped, whereas #define constants are not.
  • Const variables obey the rules of scope, type-checking, and namespace visibility.
  • Const variables can be used to define complex types and arrays, which is not possible with #define.
Operators

1. What are operators in C++?

In C++, operators are symbols used to perform operations on operands. They can be classified into various categories such as arithmetic, relational, logical, bitwise, assignment, and more.

2. What are some commonly used arithmetic operators in C++?

Some commonly used arithmetic operators in C++ are:

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • % (Modulus)

3. How to use relational operators in C++?

Relational operators are used to compare values. Here are some examples:

    
int a = 5, b = 10;
cout << (a == b) << endl;  // Output: 0 (false)
cout << (a < b) << endl;   // Output: 1 (true)
    
  

4. What are assignment operators in C++?

Assignment operators are used to assign values to variables. Examples include =, +=, -=, *=, /=, etc.

5. How to use logical operators in C++?

Logical operators are used to perform logical operations. Examples include && (logical AND), || (logical OR), and ! (logical NOT).

Control Structures

1. What are control structures in C++?

In C++, control structures are used to control the flow of execution in a program. They include:

  • Conditional statements: if, else, else if
  • Looping statements: for, while, do-while
  • Switch statement
  • Jump statements: break, continue, return, goto

2. How to use if-else statements in C++?

The if-else statement is used to execute a block of code based on a condition. Here's an example:

    
int num = 10;
if (num > 0) {
    cout << "Number is positive";
} else {
    cout << "Number is negative";
}
    
  

3. What is the syntax for the for loop in C++?

The for loop is used to execute a block of code repeatedly. Here's the syntax:

    
for (initialization; condition; increment/decrement) {
    // code to be executed
}
    
  

4. How to use switch statement in C++?

The switch statement is used to select one of many code blocks to be executed. Here's an example:

    
int day = 3;
switch (day) {
    case 1:
  cout << "Sunday";
  break;
    case 2:
  cout << "Monday";
  break;
    // More cases...
    default:
  cout << "Invalid day";
}
    
  
Functions

1. What are functions in C++?

Functions in C++ are blocks of code that perform a specific task. They allow you to break down your program into smaller, manageable pieces, which makes your code more organized, easier to understand, and reusable.

2. What is the structure of a function in C++?

The structure of a function in C++ consists of:

  • Return Type
  • Function Name
  • Parameters (optional)
  • Function Body
  • Return Statement (optional)

3. Example of a simple function

Here's an example of a simple function that adds two integers and returns the result:

  
int add(int a, int b) {
    return a + b;
}
  
    

You can call this function elsewhere in your code like this:

  
int result = add(3, 5);
// Now, result will be 8
  
    
Arrays

1. What are arrays in C++?

Arrays in C++ are a collection of elements of the same data type stored in contiguous memory locations. They allow you to store multiple values of the same type under a single name.

2. How to declare an array in C++?

You can declare an array in C++ using the following syntax:

  
data_type array_name[array_size];
  
    

For example:

  
int numbers[5]; // Declares an array of integers with size 5
  
    

3. How to access elements of an array in C++?

You can access elements of an array using their index. The index starts from 0 for the first element and goes up to (size - 1) for the last element.

  
int numbers[5] = {10, 20, 30, 40, 50};
int first_element = numbers[0]; // Accesses the first element (10)
int third_element = numbers[2]; // Accesses the third element (30)
  
    

4. Example of iterating over an array

You can iterate over the elements of an array using loops like for loop:

  
int numbers[5] = {10, 20, 30, 40, 50};
for(int i = 0; i < 5; i++) {
    cout << numbers[i] << " "; // Prints each element separated by space
}
  
    
Pointers

1. What are pointers in C++?

Pointers in C++ are variables that store memory addresses. They point to the location of other variables or objects in memory. Pointers are used to manipulate memory directly and to work with dynamic memory allocation.

2. How to declare a pointer in C++?

You can declare a pointer in C++ using the following syntax:

  
data_type *pointer_name;
  
    

For example:

  
int *ptr; // Declares a pointer to an integer
  
    

3. How to assign a value to a pointer in C++?

You can assign the address of a variable to a pointer using the address-of operator `&`. For example:

  
int num = 10;
int *ptr = # // Assigns the address of 'num' to 'ptr'
  
    

4. How to access the value pointed to by a pointer in C++?

You can access the value pointed to by a pointer using the dereference operator `*`. For example:

  
int num = 10;
int *ptr = #
cout << *ptr; // Outputs the value of 'num' (10)
  
    

5. Example of using pointers in C++

Here's an example of using pointers to swap two numbers:

  
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}
int main() {
    int x = 5, y = 10;
    cout << "Before swapping: x = " << x << ", y = " << y << endl;
    swap(&x, &y);
    cout << "After swapping: x = " << x << ", y = " << y << endl;
    return 0;
}
  
    
Strings

1. What are strings in C++?

In C++, strings are sequences of characters stored in contiguous memory locations. They are used to represent text.

2. How to declare and initialize a string in C++?

You can declare and initialize a string in C++ using the following syntax:

  
#include 
using namespace std;

string str = "Hello, world!";
  
    

3. How to perform operations on strings in C++?

C++ provides various operations and functions to work with strings, such as:

  • Concatenation
  • Substring extraction
  • Length determination
  • Comparison
  • Accessing individual characters

4. Example of string operations in C++

Here's an example of performing operations on strings:

  
#include 
#include 
using namespace std;

int main() {
    string str1 = "Hello";
    string str2 = "world";
    
    // Concatenation
    string result = str1 + ", " + str2 + "!";
    
    // Length determination
    int length = result.length();
    
    // Output
    cout << "Result: " << result << endl;
    cout << "Length: " << length << endl;
    
    return 0;
}
  
    
Structures and Classes

1. What are structures and classes in C++?

In C++, structures and classes are user-defined data types that allow you to group together variables of different data types under a single name. They can contain member variables and member functions.

2. What is the difference between structures and classes?

The main difference between structures and classes in C++ is the default access level. In structures, members are public by default, while in classes, members are private by default. Additionally, classes support inheritance, polymorphism, and access specifiers.

3. How to define a structure in C++?

You can define a structure in C++ using the `struct` keyword followed by the structure name and the list of member variables:

  
struct Person {
    string name;
    int age;
};
  
    

4. How to define a class in C++?

You can define a class in C++ using the `class` keyword followed by the class name and the list of member variables and member functions:

  
class Car {
private:
    string brand;
    int year;
    
public:
    void setBrand(string b) {
  brand = b;
    }
    void setYear(int y) {
  year = y;
    }
};
  
    

5. Example of using a class in C++

Here's an example of using a class in C++:

  
#include 
using namespace std;

class Car {
private:
    string brand;
    int year;
    
public:
    void setBrand(string b) {
  brand = b;
    }
    void setYear(int y) {
  year = y;
    }
    void display() {
  cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};

int main() {
    Car myCar;
    myCar.setBrand("Toyota");
    myCar.setYear(2022);
    myCar.display();
    return 0;
}
  
    
Inheritance

1. What is inheritance in C++?

Inheritance is a feature of object-oriented programming in C++ that allows you to create a new class (derived class) from an existing class (base class). The derived class inherits properties and behaviors (member variables and member functions) from the base class.

2. How to implement inheritance in C++?

You can implement inheritance in C++ using the `:` followed by the access specifier (`public`, `protected`, or `private`) and the base class name in the derived class declaration:

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

class Derived : public Base {
public:
    void show() {
  cout << "Derived class show" << endl;
    }
};
  
    

3. Types of inheritance in C++

C++ supports several types of inheritance, including:

  • Single inheritance
  • Multiple inheritance
  • Multilevel inheritance
  • Hierarchical inheritance
  • Hybrid inheritance

4. Example of inheritance in C++

Here's an example demonstrating inheritance in C++:

  
#include 
using namespace std;

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

class Derived : public Base {
public:
    void show() {
  cout << "Derived class show" << endl;
    }
};

int main() {
    Derived derivedObj;
    derivedObj.display(); // Accessing base class member function
    derivedObj.show();    // Accessing derived class member function
    return 0;
}
  
    
Polymorphism

1. What is polymorphism in C++?

Polymorphism is a fundamental concept in object-oriented programming that allows objects of different classes to be treated as objects of a common parent class. It enables you to perform a single action in different ways.

2. Types of polymorphism in C++

C++ supports two types of polymorphism:

  • Compile-time polymorphism (Static polymorphism)
  • Runtime polymorphism (Dynamic polymorphism)

3. Compile-time polymorphism in C++

Compile-time polymorphism is achieved using function overloading and operator overloading. It allows you to define multiple functions or operators with the same name but different parameter lists.

4. Runtime polymorphism in C++

Runtime polymorphism is achieved using virtual functions and function overriding. It allows you to redefine a base class function in a derived class, and the function to be called is determined at runtime based on the type of object.

5. Example of polymorphism in C++

Here's an example demonstrating runtime polymorphism using virtual functions:

  
#include 
using namespace std;

class Animal {
public:
    virtual void makeSound() {
  cout << "Animal makes a sound" << endl;
    }
};

class Dog : public Animal {
public:
    void makeSound() override {
  cout << "Dog barks" << endl;
    }
};

class Cat : public Animal {
public:
    void makeSound() override {
  cout << "Cat meows" << endl;
    }
};

int main() {
    Animal *animalPtr;
    Dog dog;
    Cat cat;
    
    animalPtr = &dog;
    animalPtr->makeSound(); // Output: Dog barks
    
    animalPtr = &cat;
    animalPtr->makeSound(); // Output: Cat meows
    
    return 0;
}
  
    
File Handling

1. What is file handling in C++?

File handling in C++ involves working with files on the disk. It allows you to read data from files, write data to files, and perform various operations such as opening, closing, creating, and deleting files.

2. File modes in C++

C++ supports several file modes for opening files, including:

  • `ios::in`: Open for input (reading)
  • `ios::out`: Open for output (writing)
  • `ios::binary`: Open in binary mode
  • `ios::app`: Append to the end of the file
  • `ios::ate`: Set the initial position to the end of the file
  • `ios::trunc`: Truncate the file if it exists

3. How to open a file in C++?

You can open a file in C++ using the `fstream` class:

  
#include 
#include 
using namespace std;

int main() {
    fstream file("example.txt", ios::out);
    if (file.is_open()) {
  cout << "File opened successfully." << endl;
  // Perform operations on the file
  file.close(); // Close the file when done
    } else {
  cout << "Failed to open the file." << endl;
    }
    return 0;
}
  
    

4. Reading from a file in C++

You can read data from a file in C++ using input stream (`ifstream`) objects:

  
#include 
#include 
using namespace std;

int main() {
    ifstream file("example.txt");
    if (file.is_open()) {
  string line;
  while (getline(file, line)) {
cout << line << endl; // Output each line of the file
  }
  file.close(); // Close the file when done
    } else {
  cout << "Failed to open the file." << endl;
    }
    return 0;
}
  
    

5. Writing to a file in C++

You can write data to a file in C++ using output stream (`ofstream`) objects:

  
#include 
#include 
using namespace std;

int main() {
    ofstream file("example.txt");
    if (file.is_open()) {
  file << "Hello, world!" << endl; // Write data to the file
  file.close(); // Close the file when done
    } else {
  cout << "Failed to open the file." << endl;
    }
    return 0;
}
  
    
Exceptions Handling

1. What is exception handling in C++?

Exception handling in C++ is a mechanism to handle runtime errors or exceptional situations that occur during program execution. It allows you to gracefully handle errors and prevent abnormal program termination.

2. Components of exception handling in C++

Exception handling in C++ involves three main components:

  • Try block: Contains the code that may throw an exception
  • Catch block: Handles the exception if it's thrown
  • Throw statement: Explicitly throws an exception

3. Syntax for exception handling in C++

The syntax for exception handling in C++ is as follows:

  
try {
    // Code that may throw an exception
}
catch(ExceptionType1 ex1) {
    // Handler for ExceptionType1
}
catch(ExceptionType2 ex2) {
    // Handler for ExceptionType2
}
catch(...) {
    // Default handler for any other exception
}
  
    

4. Example of exception handling in C++

Here's an example demonstrating exception handling in C++:

  
#include 
using namespace std;

int main() {
    try {
  int x = 10, y = 0;
  if (y == 0) {
throw "Division by zero error"; // Throw an exception
  }
  int result = x / y;
  cout << "Result: " << result << endl;
    }
    catch(const char* msg) {
  cout << "Exception caught: " << msg << endl; // Handle the exception
    }
    return 0;
}
  
    
Standard Template Library

1. What is the Standard Template Library (STL) in C++?

The Standard Template Library (STL) is a collection of generic algorithms and data structures provided as part of the C++ Standard Library. It consists of containers, iterators, algorithms, and function objects that can be used to perform various operations efficiently.

2. Components of the STL

The STL in C++ consists of the following main components:

  • Containers: Data structures such as vectors, lists, stacks, queues, sets, and maps
  • Iterators: Objects used to iterate over the elements of containers
  • Algorithms: Functions for performing common operations on containers, such as sorting, searching, and manipulating elements
  • Function objects: Objects that behave like functions and can be passed as arguments to algorithms

3. Example of using containers in the STL

Here's an example demonstrating the use of the vector container in the STL:

  
#include 
#include 
using namespace std;

int main() {
    // Declare and initialize a vector
    vector numbers = {1, 2, 3, 4, 5};
    
    // Add elements to the vector
    numbers.push_back(6);
    
    // Access elements of the vector using index
    cout << "Elements of the vector:" << endl;
    for (int i = 0; i < numbers.size(); ++i) {
  cout << numbers[i] << " ";
    }
    cout << endl;
    
    return 0;
}
  
    

4. Example of using algorithms in the STL

Here's an example demonstrating the use of the `sort` algorithm in the STL:

  
#include 
#include 
#include 
using namespace std;

int main() {
    // Declare and initialize a vector
    vector numbers = {5, 2, 7, 3, 1};
    
    // Sort the elements of the vector
    sort(numbers.begin(), numbers.end());
    
    // Output the sorted vector
    cout << "Sorted elements of the vector:" << endl;
    for (int num : numbers) {
  cout << num << " ";
    }
    cout << endl;
    
    return 0;
}
  
    

All Tutorial Subjects

Java Tutorial
Fortran Tutorial
COBOL Tutorial
Dlang Tutorial
Golang Tutorial
MATLAB Tutorial
.NET Core Tutorial
CobolScript Tutorial
Scala Tutorial
Python Tutorial
C++ Tutorial
Rust Tutorial
C Language Tutorial
R Language Tutorial
C# Tutorial
DIGITAL Command Language(DCL) Tutorial
Swift Tutorial
MongoDB Tutorial
Microsoft Power BI Tutorial
PostgreSQL Tutorial
MySQL Tutorial
Core Java OOPs Tutorial
Spring Boot Tutorial
JavaScript(JS) Tutorial
ReactJS Tutorial
CodeIgnitor Tutorial
Ruby on Rails Tutorial
PHP Tutorial
Node.js Tutorial
Flask Tutorial
Next JS Tutorial
Laravel Tutorial
Express JS Tutorial
AngularJS Tutorial
Vue JS Tutorial
©2024 WithoutBook