50 Multiple Choice C++ Questions with Answers

Introduction to C++

C++ is a general-purpose programming language, created by Bjarne Stroustrup at Bell Labs in 1979. It supports data abstraction, object-oriented programming, and generic programming. It runs on various platforms including Windows, MacOS, and UNIX.

Types in C++

C++ has two types of built-in types: primitive types and user-defined types. Primitive types (characters, integers, floating-point numbers, and so on) are defined by the language itself. On the other hand, user-defined types let us define our own data types. Primitive types can be further divided into two subtypes: arithmetic types (integral types, boolean values, etc.) and void (special type).

Variables in C++

In C++, a variable is a named storage that can be manipulated by a program. Every variable in C++ has a type, size, and memory layout, which determines the range of values that can be stored and manipulated in that variable. A variable definition is composed of a type specifier followed by one or more variable names separated by commas and ending with a semicolon.

Classes and Objects in C++

A class in C++ is a description or blueprint of an object, while an object is an instance of a class that contains data members (attributes, fields) and member functions (procedures, operations, services). Access specifiers (public, private, protected) grant access to the members of a class. There are four primary features of OOPS: data abstraction (data hiding), inheritance (reusability), polymorphism (object taking many forms), and encapsulation (data hiding).

Multiple-choice questions on C++:

1. What year was C++ created?
A. 1979
B. 1983
C. 1991
D. 2001

2. Which of the following is a primary feature of OOPS?
A. Modular programming
B. Data abstraction
C. Structured programming
D. Functional programming

3. What is a variable in C++?
A. A named storage manipulated by a program
B. A class instance
C. A function
D. A data type

4. What are the access specifiers in C++?
A. Public, static, protected
B. Public, private, protected
C. Private, const, volatile
D. Abstract, virtual, override


Identifying the Extension of User-Defined Header Files in C++

In C++, ".h" is the correct extension used for user-defined header files.


//Example of including a user-defined header file
#include "myheader.h"

Identifying Incorrect Constructor Types

In C++, there are four types of constructors:

- Default constructor - Parameterized constructor - Copy constructor - Special constructor (such as a conversion constructor)

It's important to note that a friend constructor is not a type of constructor. Instead, friend functions are used to allow access to private or protected class members from outside the class.

Therefore, the correct answer is:

Friend constructor is not a type of constructor.

Approach Used by C++

In C++, which is an object-oriented language, a bottom-up approach is used.

C++ vs C: Difference in Data Types

The boolean data type is supported in C++ but not in C. In C++, the boolean data type is defined as a dedicated type, whereas in C, the integer data type is typically used to represent boolean values, where 0 represents false and any non-zero value represents true.

The int, double, and float data types are supported in both C++ and C.

Here's a refresher on some of the basic data types in C++ and C:


// Integer data types
int myInt = 42;
short myShort = 32767;
long myLong = 2147483647;

// Floating-point data types
float myFloat = 3.14f;
double myDouble = 3.14159;

// Character data type
char myChar = 'A';

// Boolean data type (C++ only)
bool myBool = true;


Declaring Arrays in C++

In C++, to declare an array of integers with a size of 10, the correct syntax is:

int arr[10];

The variable name is "arr" and it can hold ten integers. The square brackets denote that this is an array with a fixed size.

Size of wchar_t

The size of the data type wchar_t depends on the number of bits in the system that the code is compiled on. This is because the compiler aims to optimize the code for efficiency in accessing the next value. Therefore, the size of wchar_t could be 2 or 4 bytes.

Understanding the "Address of" Operator

In C++ programming, the "&" symbol is commonly known as the "address of" operator. It is used to obtain the memory address of a variable in the program.


int num = 10;         //declaring a variable num
cout << &num;         //outputting the memory address of num using the address of operator

The output will be a hexadecimal number representing the memory address where the variable "num" is stored.

Pre-Increment Operator Example

The correct example for a pre-increment operator is

++n

.

Optimal Loop for Known Number of Iterations

The optimal loop for known number of iterations in programming is the "for loop." The for loop is useful when we know how many times we need to iterate through a block of code. Therefore, we can set the value of a loop counter, which is typically an integer, to the number of iterations required and loop until the counter reaches that value.

Other looping structures like while loop and do-while loop can also be used, but a for-loop is more appropriate as it provides a clear and concise structure for iteration. In contrast, the while-loop and do-while loops are better used when the number of iterations is not known in advance.

Code:


for (int i = 0; i < numIterations; i++) {
    // Block of code to be executed
}

In this example, `i` is the loop counter, which is initialized to zero. `numIterations` is the number of iterations required, and `i` is incremented after each iteration. The block of code inside the for loop is executed until the loop counter reaches the specified number of iterations.

Scope Resolution Operator

The scope resolution operator in C++ is represented by two colons (::) and it is used to specify the resolution of scope for a particular variable, method or class. It is used to access the elements (variables, methods, enums, etc.) of a namespace, class, or structure that are defined outside of the class or are static.Code:

Classification of goto statement

The goto statement in programming can be classified into one category:

Label: This is the most common and it is used for jumping to a particular section of code in a program.

Example code:


#include <stdio.h>

int main() {
   /* jump to label */
   goto mylabel;

   /* this print statement will be skipped as the control jumps to label */
   printf("This line will not be executed.\n");

   /* label */
   mylabel:
   printf("The code has jumped to the label.\n");

   return 0; 
}

In the example above, the control jumps from the 'goto' statement to the 'mylabel' label, skipping any statements between it. The program then continues executing from that point onward.

Definition of '*' Operator in Pointers

In C programming language, the '*' operator in pointers is used to dereference the pointer variable, which means to get the value at the memory address to which the pointer points. Therefore, the correct definition of the '*' operator in pointer is "value of address operator".

Option B: "Value of address operator" is the correct definition.

Replacing if-else statements with conditional operators

In some cases, the use of conditional operators can replace the need for if-else statements. The conditional operator is denoted by `? :` and it has the following syntax:


(condition) ? (expression1) : (expression2);

If condition is true, the expression1 is executed. Otherwise, expression2 is executed.

For example:


// Using if-else
int x = 10;
int y;
if (x > 0) {
    y = 1;
} else {
    y = -1;
}

// Using conditional operator
int x = 10;
int y = (x > 0) ? 1 : -1;

Both of the above code snippets will produce the same result. However, using the conditional operator can make the code more concise and can be easier to read in some cases.

Correct Default Return Value of a Function

In C/C++, the default return type of a function is int. This means that if we do not specify a return type, the function will return an integer value. However, it is always good practice to explicitly specify the return type of a function to avoid any confusion or errors in the code.

To specify the return type, we can use one of the following keywords: int, void, char, or float (among others). Choose the appropriate return type based on what the function is designed to do and what value it should return.

Representing 19.54 with a Data Type

Out of the given options, the appropriate data type to represent 19.54 would be a double.

double num = 19.54;

The double data type in Java can hold decimal values.

Inline Function Expansion

Inline functions get expanded during the compile time.

Starting Function in C++

In C++, the execution of the program always starts from the main() function.


  int main() {<br>
    // code goes here<br>
    return 0;<br>
  }


What is mandatory in a function?

In a function, both the return type and the function name are mandatory, so the correct option is D) Both a and c. These two components define what the function does and how it can be used in other parts of the code. Additionally, functions may also have parameters, which are input values that the function uses to perform its operations.In C++, constants are commonly referred to as literals.

Generating Exceptions in C++

In C++, the

throw

keyword is used to generate an exception. The syntax for using

throw

is as follows:

throw exceptionName;

Where

exceptionName

refers to the specific type of exception being thrown.

For example, consider the following code that throws an exception if a variable is equal to zero:

int a = 0;
if (a == 0) {
    throw "Variable 'a' cannot be equal to zero";
}

If the value of

a

is equal to zero, the exception "Variable 'a' cannot be equal to zero" will be thrown. The program will terminate if the exception is not handled using a

catch

block.

Identifying the Size of `int` Datatype in C++

In C++, the size of the `int` datatype depends on the compiler being used. It can be affected by a number of factors such as the operating system, the hardware architecture and the compiler implementation.

//Example of determining size of int datatype
#include<iostream>
using namespace std;

int main() {
   cout << "Size of int datatype: " << sizeof(int) << " bytes"<< endl;
   return 0;
}

The `sizeof()` operator can be used to determine the size of `int` datatype in bytes.

C++ Language Type

C++ is a statically typed language.

// No code needed for this task.


ASCII Value of '\0' Character

The ASCII value of the '\0' character is 0.

char nullChar = '\0';  //this will initialize nullChar with the character of value 0 or null


Identifying the Format String

The format string is a string that contains placeholders for values that will be substituted for those placeholders. Among the following options, the format string is:

%d

This is because the "%d" placeholder is used to represent an integer value that will be substituted into the string.

Explanation:

A do-while loop is also known as an exit control loop as it executes the code block at least once even if the given condition is false. The loop will continue to execute until the specified condition becomes false or the control of the program is transferred elsewhere.

Therefore, the correct answer is option (a) Exit control.


Syntax:
do{
    //code block to be executed
}while(condition);


Correct Range of Signed Char

In C programming, the range of signed char data type is from -128 to 127. Therefore, the correct answer is:

-128 to 127

It is important to understand the range of data types in programming to ensure that you are using them effectively and avoiding any unexpected behavior in your code.

Determining the size of a Struct

In the given struct, there are three variables of different data types: an int, a char, and a float. To determine the size of the struct, we need to consider the size of each of these variables and their respective data types.

- The size of an int is generally 2 bytes. - The size of a char is typically 1 byte. - The size of a float is usually 4 bytes.

Adding up the sizes of each of these variables, we get:

2 bytes for the int + 1 byte for the char + 4 bytes for the float = 7 bytes

Therefore, the answer is 7.

Identifying Logical AND Operator

&&

is the logical AND operator in Java.

Correct Subscript Operator

The correct subscript operator in C++ is

[ ]

. It is used to access individual elements of an array by their index. The curly braces

{ }

are used for list initialization of arrays, whereas the asterisk

*

is the pointer dereference operator and parentheses

( )

are used for function calls and grouping expressions.

Loop Types in Programming

In programming, several types of loops can be implemented depending on the situation. Out of these types of loops, one is guaranteed to execute at-least once.

do-while

loop is guaranteed to execute at-least once because it checks the condition after the loop has executed for the first time. If the condition is false, then it will exit the loop. On the other hand, all other loop types first check the condition and then execute the loop statement(s).

Therefore, the correct answer to the question is do-while.

Memory occupied by void in C

In C programming language,

void

is a data type that represents the absence of a value. It is used for indicating that a function does not return any value. As

void

does not store any value or data, it does not occupy any memory. Therefore, the answer is 0.

Explanation:

Comments

are not used to make the program run faster, increase the size of the executable program or make a program compile easier. They are solely used to provide additional information to the reader, usually other programmers, to understand the code and its purpose. This can include explanations of specific functionalities, algorithm explanations, and even reminders for future development or debugging.

Total Types of Errors in C++

In C++, there are three types of errors:

  1. Syntax errors
  2. Runtime errors
  3. Logic errors

Syntax errors occur when there is a mistake in the grammar or structure of the code.

Runtime errors happen during program execution and can be caused by various things such as division by zero, out-of-bounds array access, etc.

Logic errors occur when the code does not perform as intended and produces incorrect results.

Storage Classes with Global Visibility

The extern storage class is the only storage class with global visibility in C programming language.

The auto, register, and static storage classes have local visibility and are used within functions or blocks of code.

Here is an example:


#include <stdio.h><br>
 
// global variable
extern int num;
 
int main () {

   // local variable
   static int count = 0;

   printf("The value of num is %d\n", num);

   while (count < 5) {
      auto int i = 0; // local variable
      register int j = 0; // local variable

      printf("The value of i is %d and j is %d\n", i++, j++);
      count++;
   }

   return 0;
}

In this example, the extern keyword declares a global variable "num", and the static, auto, and register keywords declare local variables within the main function.

Identifying non-member of class

In C++, all functions that are members of a class have access to all the data members and member functions of that class. However, there are also non-member functions that may be associated with the class, but are not members of the class itself. Of the given choices, the option that is not a member of class is:

Friend function

A friend function is not a member of the class, but can access its private and protected members. The other options - Static function, Virtual function and Const function - are all member functions of a class in C++.

Types of Constructors in C++

In C++, there are three types of constructors - default constructor, parameterized constructor, and copy constructor. The code example below demonstrates using these types of constructors:

class MyClass { public: // Default constructor MyClass() { cout << "Default Constructor called!" << endl; } // Parameterized constructor MyClass(int x) { cout << "Parameterized Constructor called with value " << x << endl; } // Copy constructor MyClass(const MyClass &obj) { cout << "Copy Constructor called!" << endl; } }; int main() { // Object created using default constructor MyClass obj1; // Object created using parameterized constructor MyClass obj2(5); // Object created using copy constructor MyClass obj3 = obj1; return 0; }

In this example, the default constructor is called when obj1 is created. The parameterized constructor is called when obj2 is created with the argument value of 5. The copy constructor is called when obj3 is created and initialized with obj1.

Understanding Default Constructor Parameters

In Java, a default constructor is a constructor that is automatically created by the compiler when a class is created. This constructor has no parameters and is used to initialize the objects of a class with default values. Therefore, a default constructor requires zero parameters.

C++ Class Contents

A C++ class holds both functions and data.

In object-oriented programming, a class is a template for creating objects that encapsulate data and functions. The data and functions within a class can only be accessed by the class itself, making it a powerful tool for organizing code and preventing unwanted changes to data.

Within a class, the data usually represents the state of an object, while the functions represent the behavior of the object.

Understanding Class Data Members and Member Functions

In Object-Oriented Programming, a class is a blueprint for creating objects that have certain properties and behaviors. Data members and member functions are two important components of a class.

In C++, data members and member functions are private by default. This means that they can only be accessed within the same class and not from outside the class. However, you can change the access specifier of data members and member functions to public or protected if needed.

The statement "Data members and member functions of a class are always private by default" is true.

So, to access a private data member or member function from outside the class, we need to use public member functions, also known as getters and setters.


class MyClass { // defining a class
  private: // access specifier
    int myPrivateData;
    void myPrivateFunction();
  public:
    int getMyPrivateData(); // getter function
    void setMyPrivateData(int data); // setter function
};


Explanation:

In Object-Oriented Programming, inheritance is a key feature of the Pillar of OOPS. It allows a derived or child class to inherit properties and methods from a base or parent class.

Therefore, the relationship between the base class and derived class is an example of inheritance in OOPS.

Answer: Inheritance

Functions Inherited from Base Class

There are no functions that can be inherited from a base class. However, derived classes can have the same function names as the base class, effectively overwriting the base class functions with their own implementations.

Therefore, the correct answer is: None.This code is incomplete and has errors. It seems to be written in C++, but there is no `#include` for `iostream` and the `cout` statement is incomplete. Also, the variable type `Float` should be all lowercase `float` in C++. The switch statement is expecting an integer type, and `a` is a float.

Here's a corrected version of the code with a default case and a complete `cout` statement:

cpp
#include <iostream>
using namespace std;

int main(){
  float a = 5;
  switch(int(a)){
     case 5: cout << "a is equal to 5"; break;
     default: cout << "a is not equal to 5";
  }
  return 0;
}

The output of this program would be:


a is equal to 5

because the value of `a` is explicitly casted to an integer in the switch statement, and it matches the case `5`.This program is incomplete and will produce a syntax error if executed as is. It appears to be missing the necessary header files and the rest of the code to complete the function.

To show an example of code that could produce a similar output, assuming the missing code is in place, we could complete the program like this:

Code:

#include

using namespace std;

int main() {   int a = 10, b, c;   b = a++;   c = a;   cout << "a = " << a << endl; // Output: a = 11   cout << "b = " << b << endl; // Output: b = 10   cout << "c = " << c << endl; // Output: c = 11   return 0; } Output: a = 11 b = 10 c = 11 Explanation: The program declares three integer variables: a, b, and c. The initial value of a is 10. The line "b = a++" assigns the value of a to b (which is 10), then increments the value of a to 11. The line "c = a" assigns the current value of a (which is 11) to c. Finally, the program outputs the values of a, b, and c. So, the output of the program is: a = 11 b = 10 c = 11I'm sorry, but the given program is incomplete and cannot produce any output. The program ends abruptly with an incomplete `cout` statement. Please provide a complete program to allow me to assist you further.

Execution of print statement

This code snippet is not complete as there is no complete print statement within the 'main' function. It only includes the declaration and initialization of a variable 'i' as well as a label 'label'. Therefore, it is impossible to determine the number of times a print statement will be executed without further code.

However, if there were a print statement within the 'main' function, the number of times it will be executed will depend on the control flows and the values of variables used in the code.Unfortunately, the given program is incomplete and cannot be executed. It seems to be missing code after the "cout" statement. Please provide the complete program or the missing code to find the output of the program.Code:

C 
#include <stdio.h>  
int main()  
{  
    int a = 10/0;  // dividing integer by 0 gives arithmetic exception
    printf("%d\n", a); // this line is not executed due to exception
    return 0;  
}  

Program Output

The output of the program will be an exception, specifically "Floating point exception (core dumped)" or "Arithmetic exception (core dumped)" depending on the compiler and OS used.The correct escape sequence for a new line is "\n".Without a complete program or statement continuation, it's not possible to determine the output of the given program. The statement is incomplete as it lacks a semicolon (;) at the end and there's no continuation of code. Please provide complete code to determine the output.This program is incomplete as there is no ending semicolon for the `cout` statement. However, the code seems to assign the value of `3` to the variable `i` using the comma operator, which evaluates all expressions in a comma-separated sequence and returns the result of the last expression.

Therefore, the output of the program would be `3`.

Correct Identifier in Programming

In programming, an identifier is a name used to identify a variable, function, object, or any other user-defined item. A valid identifier should follow certain rules to be considered correct. Here are some examples:

- 2var_name: Incorrect identifier. Can't start with a number. - 2VAR_NAME: Incorrect identifier. Can't start with a number and it's recommended to avoid capital letters in identifiers. - $varname: Correct identifier. It can start with a special character and it's commonly used in some programming languages like PHP. - var_name12: Correct identifier. It starts with a lowercase letter and it includes only letters and digits.

Therefore, "var_name12" is the correct identifier according to the rules of most programming languages.

Identification of Inheritance Types

In object-oriented programming, inheritance is the process of creating new classes (derived classes) from existing classes (base classes). The derived classes inherit the properties and behavior of the base class. There are mainly three types of inheritance: Single, Multilevel, and Hierarchical.

Out of the options given, Distributed is not a type of inheritance. Therefore, option 3 is the answer.

Understanding Objects in C++

In C++, an object is an instance of a class. A class is like a blueprint or a template for creating objects. When an object is created, it takes on the characteristics of the class it belongs to.

For example, a class might be defined to represent a car. The class would specify the properties and behaviors of the car, such as its make, model, color, and speed. An object of the car class would be an actual car, with specific values for each of its properties.

Therefore, an object in C++ is not a function or a datatype of a class, but rather an instance of that class.

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.