0% found this document useful (0 votes)
4 views17 pages

SAMPLE CPP Question Answers

The document provides a comprehensive question bank on C++ concepts, covering topics such as classes, objects, inheritance, polymorphism, encapsulation, and memory management. Each question is followed by a concise answer that explains the concept in detail, making it a useful resource for understanding object-oriented programming in C++. Additionally, it includes design patterns, containers, and exception handling, offering a well-rounded overview of C++ programming principles.

Uploaded by

fifaforyou92
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views17 pages

SAMPLE CPP Question Answers

The document provides a comprehensive question bank on C++ concepts, covering topics such as classes, objects, inheritance, polymorphism, encapsulation, and memory management. Each question is followed by a concise answer that explains the concept in detail, making it a useful resource for understanding object-oriented programming in C++. Additionally, it includes design patterns, containers, and exception handling, offering a well-rounded overview of C++ programming principles.

Uploaded by

fifaforyou92
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

C++ Question Bank with Answers (50 Words Each)

1. What is a class?
A class in C++ is a user-defined type that encapsulates data and functions. It serves as a blueprint
for creating objects. Classes support object-oriented features such as encapsulation, inheritance,
and polymorphism. It organizes related variables and functions into one entity, allowing modular,
reusable, and organized code structures in software development.

2. What is an object?
An object in C++ is an instance of a class. It represents a specific entity with attributes (data) and
behaviors (methods). Objects are created using a class, and each object has its own copy of class
members. They are the core units in object-oriented programming for modeling real-world
concepts.

3. What is the difference between an object and a class?


A class is a blueprint or template, while an object is an instance of that class. The class defines
properties and behaviors, but does not occupy memory. Objects are created from the class and
represent real entities with allocated memory. Multiple objects can be created from a single class
definition.

1. What is a class?
A class in C++ is a user-defined type that encapsulates data and functions. It serves as a
blueprint for creating objects. Classes support object-oriented features such as
encapsulation, inheritance, and polymorphism. It organizes related variables and
functions into one entity, allowing modular, reusable, and organized code structures in
software development.

2. What is an object?
An object in C++ is an instance of a class. It represents a specific entity with attributes
(data) and behaviors (methods). Objects are created using a class, and each object has its
own copy of class members. They are the core units in object-oriented programming for
modeling real-world concepts.

3. What is the difference between an object and a class?


A class is a blueprint or template, while an object is an instance of that class. The class
defines properties and behaviors, but does not occupy memory. Objects are created from
the class and represent real entities with allocated memory. Multiple objects can be
created from a single class definition.
4. What is the difference between class and structure?
In C++, both class and structure can contain data and functions. However, the default
access modifier for class members is private, while for structure, it is public. Classes are
commonly used for complex data handling in object-oriented design, while structures are
typically used for simpler data groupings or representations.

5. What is public, protected, and private?


They are access specifiers in C++. Public members are accessible from anywhere.
Protected members are accessible within the class and its derived classes. Private
members are accessible only within the class. These specifiers help enforce encapsulation
and control access levels for class members to maintain data integrity and security.

6. What are virtual functions?


Virtual functions are member functions in a base class that can be overridden in a derived
class. They support runtime polymorphism using dynamic dispatch. When invoked
through a base class pointer or reference, the derived class’s overridden function is
called. This enables flexible and extendable code structures during inheritance.

7. What is friend function?


A friend function is a non-member function that has access to a class’s private and
protected members. It is declared using the friend keyword within the class. Though it is
not a class member, it can operate on class internals, making it useful for operator
overloading or accessing multiple classes.

8. Difference between friend function & static function?


A friend function is not a class member but can access private members. A static function
is a class member shared by all instances, and it can only access static members. Static
functions require object-independent usage, whereas friend functions often handle
external access and inter-class interactions in specific contexts.

9. What is a scope resolution operator?


The scope resolution operator :: is used in C++ to access global variables, define
functions outside classes, or refer to class members explicitly. It helps disambiguate
names when local and global variables have the same names. It is also used to define
class functions outside the class body.

10. What do you mean by inheritance? Give example.


Inheritance allows a class (derived) to acquire properties and behaviors of another class
(base). It promotes reusability and hierarchical classification. For example, a Car class
can inherit from Vehicle class. This means Car will have all the attributes and functions
of Vehicle, and can add its own specialized features.

11. What is abstraction?


Abstraction is the process of hiding internal implementation details and showing only
relevant features to users. In C++, it is achieved using classes and access specifiers.
Abstraction helps in reducing complexity and increasing efficiency by exposing only
necessary functionalities, while keeping background processes hidden from external
access or manipulation.

12. What is polymorphism? Types & Explain with an example.


Polymorphism allows objects to be treated as instances of their parent class. It comes in
two types: compile-time (function/operator overloading) and runtime (virtual functions).
For example, a base class Shape with a virtual function draw() can be overridden in
Circle and Rectangle, allowing dynamic behavior through base pointers.

13. What is encapsulation?


Encapsulation is the concept of binding data and functions into a single unit, typically a
class. It restricts direct access to data using private/protected access specifiers, allowing
controlled access via public methods. Encapsulation promotes modularity, security, and
maintainability by hiding internal state and exposing only necessary interfaces.

14. What do you mean by binding of data and functions?


Binding of data and functions means grouping related variables and methods inside a
class. This relationship enforces object-oriented principles like encapsulation. Functions
operate on the class’s data, ensuring integrity. This design pattern allows efficient and
secure access to an object’s behavior, supporting modular code and easier software
maintenance.
15. What is function overloading and operator overloading?
Function overloading allows multiple functions with the same name but different
parameters. Operator overloading enables redefining operators like +, -, etc., for user-
defined types. Both provide polymorphic behavior. For example, int add(int a, int b) and
float add(float a, float b) are function overloads that perform similar operations.

16. What is virtual class and friend class?


A virtual class is used in virtual inheritance to prevent duplication of base class members
in multiple inheritance. A friend class is given access to another class’s private and
protected members. While virtual classes solve ambiguity, friend classes facilitate tightly
coupled relationships where external class access is necessary.

17. What do you mean by inline function?


An inline function is a function whose code is expanded in line at the point of invocation,
reducing function call overhead. Declared using the inline keyword, it is suitable for
short, frequently used functions. However, excessive use can increase binary size,
reducing performance benefits due to code duplication.

18. What do you mean by public, private, protected and friendly?


Public: accessible from anywhere. Private: accessible only within the class. Protected:
accessible within the class and derived classes. Friend: not a specifier but allows access
via friend functions or classes. These access controls determine how class members are
visible and interact with other parts of the program.

19. When an object created and what is its lifetime?


An object’s lifetime depends on its storage type. A local object (automatic storage) is
created when the block is entered and destroyed when it exits. A dynamically allocated
object (new) exists until deleted. A global/static object is created at program start and
destroyed at termination, supporting persistent application state.

20. What do you mean by multiple inheritance and multilevel inheritance?


Differentiate between them?
Multiple inheritance means a class inherits from more than one base class. Multilevel
inheritance means a class inherits from a derived class, forming a hierarchy. Multiple
inheritance can cause ambiguity (solved with virtual inheritance), while multilevel shows
transitive property. Both enhance code reuse and represent complex hierarchical
relationships in systems.

21. Difference between realloc() and free()?


realloc() resizes memory previously allocated by malloc() or calloc(). It returns a pointer
to the new memory block. free() deallocates memory allocated dynamically. realloc() can
extend or shrink memory without losing data, while free() simply releases memory,
preventing leaks. Both are crucial for efficient memory management in C++.

22. What is a template?


A template in C++ is a feature that allows functions or classes to operate with generic
types. It supports generic programming by allowing code reusability. Function and class
templates are created using the template keyword. They enable writing flexible and
reusable code without rewriting for every data type required.

23. What are the main differences between procedure oriented languages and object
oriented languages?
Procedure-oriented languages focus on functions and procedures, with data flowing
freely. Object-oriented languages encapsulate data and functions into objects. OOP
promotes abstraction, inheritance, and polymorphism. Procedural programming is
suitable for simple tasks, while OOP is more scalable and modular, supporting software
development practices and reusable, maintainable code structures.

24. What is RTTI?


RTTI (Run-Time Type Information) in C++ allows determining the type of an object
during runtime. It is used mainly with polymorphic types through mechanisms like typeid
and dynamic_cast. RTTI helps perform safe downcasting or type checking, especially
when base class pointers are used to reference derived class objects.

25. What are generic functions and generic classes?


Generic functions and classes use templates to define operations with data types specified
later. They support type-independent programming, increasing reusability. For example,
a generic class Stack<T> works for int, float, or user-defined types. Generic functions
can perform operations like swap() for any type. Templates achieve compile-time
polymorphism.
26. What is namespace?
A namespace in C++ is a declarative region used to group identifiers like classes, objects,
and functions under a name. It helps avoid name conflicts, especially in large projects or
libraries. Declared using the namespace keyword, it allows better organization and
encapsulation of code elements with identical names.

27. What is the difference between pass by reference and pass by value?
In pass by value, a copy of the variable is passed, and changes don’t affect the original. In
pass by reference, an alias is passed, so changes affect the original variable. Pass by
reference allows more efficient memory usage and is often used when large objects or
modifications are needed.

28. Why do we use virtual functions? Give an example.


Virtual functions enable runtime polymorphism by allowing derived class methods to
override base class methods when accessed via base class pointers. For example, a base
class Shape with virtual draw() can be overridden in Circle. A pointer of type Shape*
calling draw() on Circle executes the circle’s function.

29. What do you mean by pure virtual functions?


A pure virtual function is declared using = 0 syntax in a base class and must be
overridden in derived classes. The class containing it becomes abstract and cannot be
instantiated. Pure virtual functions enforce a contract in derived classes to provide
specific functionality and support interface-like behavior.

30. What are virtual classes?


In C++, virtual classes refer to classes inherited using virtual inheritance. This prevents
multiple instances of a base class when multiple inheritance is used. It resolves the
diamond problem by ensuring only one instance of the common base class is shared
among derived classes. It promotes consistent and conflict-free inheritance.

31. Does C++ support multilevel and multiple inheritance?


Yes, C++ supports both multilevel and multiple inheritance. Multilevel inheritance
involves a class derived from another derived class. Multiple inheritance allows a class to
inherit from more than one base class. While powerful, multiple inheritance can introduce
ambiguity and complexity, often managed using virtual inheritance and careful design.

32. What are the advantages of inheritance?


Inheritance promotes code reusability by allowing new classes to reuse existing class
features. It supports hierarchical classification, extensibility, and modularity. Derived
classes can override or extend base class behaviors, improving maintainability and
reducing redundancy. Inheritance also enables polymorphism, allowing base class
pointers to handle multiple derived class types dynamically.

33. When is memory allocated to a class?


Memory is allocated to a class when an object of the class is created. Class definitions
themselves do not consume memory. For static members, memory is allocated once
regardless of the number of objects. Memory for non-static members is allocated per
object instance, supporting encapsulated storage of object-specific data.

34. What is the difference between declaration and definition?


A declaration tells the compiler about the name and type of a variable or function,
without allocating memory. A definition allocates memory or provides implementation.
For example, int a; is both declaration and definition. extern int a; is only a declaration.
Functions must be defined for usage, after declaration.

35. What is virtual constructors/destructors?


C++ does not support virtual constructors since object construction must be deterministic.
However, destructors can be virtual. A virtual destructor ensures the correct destructor is
called for derived objects when deleted through a base class pointer. This avoids resource
leaks and ensures proper cleanup in inheritance hierarchies.

36. In C++ there are only virtual destructors, no constructors. Why?


Constructors initialize objects and their types must be known at creation. Hence,
constructors cannot be virtual. Virtual functions require an object’s vtable, which is set
up after the constructor runs. Destructors, however, can be virtual to ensure derived
destructors are called correctly when deleting objects through base class pointers.
37. What is late bound function call and early bound function call? Differentiate.
Early binding occurs at compile time, where the function to be called is known. Late
binding occurs at runtime using virtual functions. Early binding is faster, but lacks
flexibility. Late binding allows polymorphism, enabling base class pointers to call
derived functions dynamically, offering more extensible and reusable program structures.

38. How is exception handling carried out in C++?


C++ uses try, catch, and throw keywords for exception handling. Code that may throw an
exception is placed inside try. If an exception occurs, control is transferred to the
matching catch block. The throw keyword raises the exception. This mechanism
separates error handling from regular code logic cleanly.

39. Explain OOPS concept with its features & volatile specifier.
OOP features include encapsulation, abstraction, inheritance, and polymorphism. They
promote modular, reusable, and organized code. Volatile is a keyword indicating a
variable can be changed unexpectedly (e.g., hardware updates), preventing compiler
optimizations. OOP enhances large system design, while volatile ensures correct behavior
in concurrent or low-level programming scenarios.

40. When will a constructor executed?


A constructor is executed automatically when an object is created. It initializes the
object’s members. Constructors can be default, parameterized, or copy constructors. If
not explicitly defined, C++ provides a default constructor. Constructors ensure objects
are in a valid state before use, allowing customized initialization for different object
instances.

41. What is Dynamic Polymorphism? How is it achieved?


Dynamic polymorphism allows invoking derived class methods through base class
pointers or references at runtime. It is achieved using virtual functions. The function to
call is determined using a vtable and vpointer, enabling flexible, extensible designs. This
allows code to work with different object types using the same interface.

42. Write a macro for swapping integers.


#define SWAP(x, y) { int temp = x; x = y; y = temp; }

This macro swaps two integer values using a temporary variable. Macros perform text
substitution and are expanded at compile time. They are faster but lack type checking, so
caution is needed when using them in complex expressions or with functions, as
unexpected behaviors may arise due to side effects.

43. Write any 4 design patterns in C++?

1. Singleton – ensures only one instance.

2. Factory – creates objects without exposing the creation logic.

3. Observer – notifies multiple objects of changes.

4. Strategy – selects algorithm at runtime.

These patterns solve common design problems, improve code structure, and promote
reusability and maintainability in C++ applications.

44. Write any 4 containers.

1. vector – dynamic array.

2. list – doubly linked list.

3. map – key-value pairs with sorted keys.

4. set – unique sorted elements.

These Standard Template Library (STL) containers provide efficient ways to store,
retrieve, and manipulate collections of data with built-in algorithms and iterator
support.

45. A ________ has no type name and can be accessed directly by name.
A namespace has no type name and can be accessed directly by name. It is used to avoid
naming conflicts and organize code elements logically. With a using namespace
statement, its members can be accessed directly without scope resolution. This improves
readability and simplifies referencing variables and functions.
46. Trees, sorting algorithms
Trees are hierarchical data structures with parent-child relationships used in search,
hierarchical storage, and decision making. Sorting algorithms like quicksort, mergesort,
and heapsort organize data in a specific order. Both trees and sorting are essential in
efficient data management, enhancing access time, and ensuring faster retrieval in
programming tasks.

47. Singleton object


A Singleton object restricts a class to a single instance and provides a global point of
access. It ensures only one object is created using private constructors and a static
method. Singleton is used where exactly one object is needed, such as configuration
management, logging, or connection pooling in applications.

48. Copy constructors


A copy constructor creates a new object by copying another existing object. It is invoked
when objects are passed by value, returned from functions, or explicitly copied. If not
defined, C++ provides a default copy constructor. Custom copy constructors handle deep
copying to manage dynamic resources safely and correctly.

49. Base class, derived class, abstract class.


A base class provides common functionality. A derived class inherits from a base class
and may extend or override behavior. An abstract class contains at least one pure virtual
function and cannot be instantiated. Abstract classes enforce interface contracts, allowing
polymorphic behavior and extensible software design through inheritance.

50. What are the object-oriented concepts? Explain each.


OOP concepts include:

1. Encapsulation – combining data and methods.

2. Abstraction – hiding internal details.

3. Inheritance – deriving classes from existing ones.

4. Polymorphism – using one interface for multiple forms.


These concepts promote modular, reusable, and maintainable code structures,
enabling scalable, object-centric software development practices in C++.

51. Difference between data abstraction & data encapsulation.


Data abstraction hides implementation details and exposes only relevant functionalities.
Encapsulation binds data and methods within a class, restricting access via access
specifiers. Abstraction focuses on “what” a system does, while encapsulation focuses on
“how” it’s done, ensuring security, modularity, and reduced complexity in object-
oriented software systems.

52. How does function overloading occur in C++?


Function overloading in C++ occurs when multiple functions have the same name but
differ in parameters (type, number, or order). The compiler determines the correct
function to call during compilation based on arguments. It supports compile-time
polymorphism and enables developers to write intuitive, reusable, and type-safe code
structures.

53. Write a function for overloading “<<” operator?

class Sample {
int x;
public:
Sample(int val) : x(val) {}
friend std::ostream& operator<<(std::ostream &out, const Sample &s) {
out << s.x;
return out;
}
};

This overloads << for Sample class. It enables using cout << s; to print the object’s value
cleanly.
54. Write difference between C & C++ structures?
In C, structures can only contain data. In C++, structures can contain data, functions,
constructors, destructors, and access specifiers. The default access is public in structures.
C++ structures support object-oriented features like inheritance and polymorphism,
whereas C structures are used primarily for grouping related variables under a single
name.

55. How to implement Operator overloading with an e.g. a+2 & 2+a, where a is an
object to a class.

class Number {
int value;
public:
Number(int v) : value(v) {}
Number operator+(int n) { return Number(value + n); }
friend Number operator+(int n, Number obj) {
return Number(n + obj.value);
}
};

This allows a+2 and 2+a using member and friend functions for operator overloading.

56. Static variables & static function (why required)?


Static variables maintain their value across function calls and are shared among all
objects of a class. Static functions are class-level functions that can access only static
members. They are required for managing shared data and behavior that doesn’t depend
on object instances, promoting memory efficiency and functional encapsulation.

57. Order of construction & destruction.


In C++, base class constructors are called before derived class constructors. Destructors
are called in the reverse order—derived class first, then base class. Within a class,
member constructors are called in the order of declaration. This order ensures consistent
initialization and cleanup in complex object hierarchies using inheritance.

58. Write a program to simulate a pay scale distribution pgm depending on category
(temporary, contract, permanent).

class Employee {
public:
virtual void displayPay() = 0;
};
class Temporary : public Employee {
void displayPay() { cout << "Pay: 10000"; }
};
class Contract : public Employee {
void displayPay() { cout << "Pay: 20000"; }
};
class Permanent : public Employee {
void displayPay() { cout << "Pay: 30000"; }
};

59. Differences between macro & inline functions.


Macros are preprocessor directives replaced at compile-time. Inline functions are
expanded by the compiler where called. Macros don’t check type safety and can cause
bugs. Inline functions are type-checked and debugged. Inline is preferred over macros for
performance and safety when defining short, frequently used, reusable function-like
constructs.

60. Difference between abstract class & interfaces.


C++ doesn’t have interfaces like Java, but abstract classes with pure virtual functions act
similarly. Abstract classes can have data and implementation, whereas interfaces (if
implemented via pure virtual classes) only declare methods. Abstract classes allow partial
implementation, while interfaces enforce implementation of all declared methods by
derived classes.

61. Difference between identifier & keyword.


Identifiers are user-defined names for variables, functions, classes, etc. Keywords are
reserved words predefined by the language (e.g., int, class, if) and cannot be used as
identifiers. Identifiers follow naming rules and enable meaningful references, while
keywords provide syntactic structure and control flow in the C++ programming language.

62. What is re-entrant function? Where do you use?


A re-entrant function can be interrupted during execution and safely re-entered before the
previous execution completes. It does not rely on shared or static data and uses only local
variables. Re-entrant functions are used in multi-threaded environments, signal handlers,
or interrupt routines where concurrent access is possible and required.

63. Is passing by reference & passing by address the same? Give example.
No. Passing by address uses pointers and requires dereferencing, while passing by
reference uses aliases. Both modify the original variable.
Example:

void fun(int* a); // pass by address


void fun(int &a); // pass by reference

References are safer and easier to use, avoiding pointer syntax.

64. What does C++ support - pass by value, address or reference?


C++ supports all three:

• Pass by value (copy is passed)

• Pass by address (pointer passed)

• Pass by reference (alias is passed)


Developers choose based on need: value for safety, reference or address for efficiency
or when modifying the original variable. Reference is preferred for object
manipulation.

65. Difference between virtual function & pure virtual function.


A virtual function is defined in the base class and optionally overridden. A pure virtual
function has no definition and is declared using = 0. It makes the class abstract. Virtual
functions enable polymorphism. Pure virtual functions enforce derived classes to
implement the behavior, ensuring interface-like design enforcement.

66. Protected keyword?


Protected is an access specifier in C++. Members declared as protected are accessible
within the class and by derived classes, but not by outside functions or classes. It allows
subclass access to base class members while still restricting external access, supporting
inheritance and secure object-oriented programming practices.

67. What is more suitable in Fibonacci series, iterative, recursive or depending upon
the input values?
Iterative is more efficient for large inputs due to constant space and time complexity.
Recursive is elegant but leads to redundant calls unless optimized with memoization.
Choice depends on problem size and performance needs. Iteration is preferred in practice,
while recursion demonstrates divide-and-conquer and conceptual clarity for small inputs.

68. What are applets?


Applets are small Java programs that run in web browsers. C++ does not directly support
applets. In general terms, applets refer to lightweight applications that perform specific
tasks. They require a plugin or environment like Java Virtual Machine (JVM). Applets
are outdated and replaced by modern web technologies today.

69. What is the difference between overriding and overloading?


Overloading means defining multiple functions with the same name but different
parameters within a class. Overriding means redefining a base class’s virtual function in a
derived class. Overloading is compile-time polymorphism; overriding is runtime
polymorphism. Overloading allows function versatility, while overriding allows
specialized behavior in derived classes.
70. What are containers, iterators and algorithms?
Containers store collections (vector, map), iterators traverse containers, and algorithms
(sort, find) perform operations. STL provides these three components for generic
programming. Containers manage data, iterators provide access, and algorithms
manipulate data. Together, they enable efficient, reusable, and abstract data operations
without manual implementation of common patterns.

71. What is virtual abstract base class?


A virtual abstract base class in C++ is an abstract class (with pure virtual functions)
inherited virtually. It avoids duplication in multiple inheritance and ensures only one
instance in the hierarchy. It serves as a common interface while resolving ambiguity,
supporting modular design and clean interface-driven class hierarchies.

72. Explain dynamic polymorphism using the concept of V table & V pointer?
Dynamic polymorphism uses virtual functions resolved at runtime. A V-table stores
function pointers for virtual functions. Each object has a V-pointer pointing to its class’s
V-table. When a virtual function is called through a base pointer, the V-pointer accesses
the correct function via the V-table, ensuring runtime binding.

73. How do you achieve data hiding in C++?


Data hiding is achieved using access specifiers like private and protected. These restrict
direct access to class members, exposing functionality via public methods. Encapsulation
supports this, ensuring internal implementation is not visible externally. This enforces
modular design, reduces risk of misuse, and maintains control over data modifications.

74. Write a program to show the dynamic polymorphism concept?

class Base {
public:
virtual void display() { cout << "Base class"; }
};
class Derived : public Base {
public:
void display() override { cout << "Derived class"; }
};
Base* b = new Derived();
b->display(); // Output: Derived class

This demonstrates runtime polymorphism using base class pointers and virtual functions.

You might also like