0% found this document useful (0 votes)
14 views39 pages

C++ Final

The document discusses various concepts in C++ programming, including constant member functions, reference variables, copy constructors, static objects, nested classes, virtual destructors, base and derived class pointers, virtual functions, default arguments, and the differences between multilevel and hybrid inheritance. Each topic is explained with definitions, characteristics, and suitable examples to illustrate the concepts. Additionally, a program example is provided to demonstrate the use of virtual functions in counting objects across multiple classes.

Uploaded by

aram fatma
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)
14 views39 pages

C++ Final

The document discusses various concepts in C++ programming, including constant member functions, reference variables, copy constructors, static objects, nested classes, virtual destructors, base and derived class pointers, virtual functions, default arguments, and the differences between multilevel and hybrid inheritance. Each topic is explained with definitions, characteristics, and suitable examples to illustrate the concepts. Additionally, a program example is provided to demonstrate the use of virtual functions in counting objects across multiple classes.

Uploaded by

aram fatma
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/ 39

1

Q1. Discuss the constant member function with suitable example.


Ans: A constant member function in C++ is a member function declared with
the const keyword. It promises not to modify the object on which it is called.
This declaration enables the compiler to enforce this promise, preventing
unintended modifications to objects marked as const.
Here's an example to illustrate the concept:
#include <iostream>
class Circle {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double calculateArea() const {
return 3.14159 * radius * radius;
}
void setRadius(double r) {
radius = r;
}
};
int main() {
const Circle circle1(5.0);
std::cout << "Area of circle1: " << circle1.calculateArea() << std::endl;
return 0;
}
Q2. Define reference variable with its characteristics.
Ans: A reference is defined as an alias for another variable. In short, it is like
giving a di erent name to a pre-existing variable. Once a reference is
initialized to the variable, we can use either the reference name or the variable
to refer to that variable.
2

 Alias for an Existing Variable: A reference variable is essentially


another name for an existing variable. It doesn't have its own storage but
refers to the same memory location as the original variable.
 Declared using "&" Symbol: References are declared using the &
symbol.
 Must be Initialized: A reference variable must be initialized when
declared, and it cannot be changed to refer to another variable once
initialized.
 Cannot be NULL: Unlike pointers, references cannot be NULL. They
must always refer to a valid object.
 Useful for Function Parameters: References are commonly used in
function parameters to avoid unnecessary copying of objects. This is
often referred to as pass-by-reference.
 Simplifies Syntax: Using reference variables can lead to cleaner and
more concise code, especially when working with functions that modify
their arguments.
Q3. Discuss the copy constructor with suitable example.
Ans: A copy constructor in C++ is a special constructor used to create a new
object as a copy of an existing object. It is invoked when a new object is
initialized with an existing object of the same class, typically by either of the
following situations:
 Direct initialization: ClassName newObj = existingObj;
 Passing an object as a function argument by value.
 Returning an object from a function by value.
Here are some key characteristics of copy constructors:
 Signature: A copy constructor has the same name as the class and
takes a reference to an object of the same class as its parameter. It is
usually declared as ClassName(const ClassName &obj).
 Purpose: The primary purpose of a copy constructor is to initialize a
new object with the state of an existing object.
 Default Copy Constructor: If you don't provide a copy constructor in
your class, the compiler generates a default copy constructor for you.
However, if your class contains pointer members or any dynamically
allocated resources, you should define your own copy constructor to
perform a deep copy.
3

#include <iostream>
class MyClass {
private:
int* data;
int size;
public:
MyClass(int sz) : size(sz) {
data = new int[size];
for (int i = 0; i < size; ++i) {
data[i] = i;
}
}
MyClass(const MyClass &obj) : size(obj.size) {
data = new int[size];
for (int i = 0; i < size; ++i) {
data[i] = obj.data[i];
}
std::cout << "Copy constructor called" << std::endl;
}
~MyClass() {
delete[] data;
}
void display() {
for (int i = 0; i < size; ++i) {
std::cout << data[i] << " ";
}
std::cout << std::endl;
}
};
int main() {
MyClass obj1(5);
MyClass obj2 = obj1;
std::cout << "Contents of obj1: ";
obj1.display();
std::cout << "Contents of obj2: ";
obj2.display();
return 0;
}
4

Q4. What is static object? How it is di erent from normal object?


Ans: In C++, a static object refers to an object that is associated with the class
rather than with instances of the class. There are two main contexts in which
the term "static object" is used:
 Static Member Variables: These are variables declared with the static
keyword within a class. They are shared by all instances of the class and
exist independently of any particular instance. They are initialized once
when the program starts and destroyed when the program terminates.
Static member variables are accessed using the class name, not
through instances of the class.
 Static Local Variables: These are variables declared with the static
keyword inside a function. They retain their values between function
calls, but their scope is limited to the block in which they are defined.
Static local variables are initialized once when the program starts and
destroyed when the program terminates.
discuss the di erences between static objects and normal objects:
 Lifetime: Static objects have a lifetime that spans the entire execution
of the program, whereas normal objects have a lifetime tied to their
scope or their containing object's lifetime.
 Storage: Static objects are typically stored in a special static data
segment of memory, whereas normal objects are stored on the stack or
the heap depending on how they are allocated.
 Initialization: Static objects are initialized only once, typically before
the main() function is called, whereas normal objects are initialized
every time they are created.
 Access: Static member variables are accessed using the class name
and the scope resolution operator ::, while normal member variables
are accessed using object instances with the dot . or arrow -> operators.
 Shared State: Static member variables are shared among all instances
of the class, meaning changes to a static member variable will a ect all
instances. Normal member variables are unique to each instance of the
class.
Q5. Discuss the nested class with suitable program?
Ans: A nested class in C++ is a class declared within another class. It is a way
to logically group classes within the scope of another class. Nested classes
can have access to the private members of the enclosing class, e ectively
allowing them to serve as helper classes or components closely related to the
enclosing class. Here's an example program demonstrating nested classes:
5

#include <iostream>
class OuterClass {
private:
int outerData;
class InnerClass {
private:
int innerData;
public:
InnerClass(int data) : innerData(data) {}
void display() {
std::cout << "Inner data: " << innerData << std::endl;
}
};
public:
OuterClass(int data) : outerData(data) {}
void display() {
std::cout << "Outer data: " << outerData << std::endl;
}
void useInnerClass() {
InnerClass innerObj(42);
innerObj.display();
}
};
int main() {
// Creating an OuterClass object
OuterClass outerObj(10);
outerObj.display();
outerObj.useInnerClass();
return 0;}

Q6. Explain the virtual destructor.


Ans: In C++, when you have a base class with virtual functions and you intend
to use inheritance, it's often necessary to declare the destructor of the base
class as virtual. This is important because it ensures that the destructor of the
most derived class in the inheritance hierarchy is invoked when an object of
that class type is deleted through a pointer to the base class.
Here's why you might need a virtual destructor:
Proper Cleanup: When you have a hierarchy of classes where derived classes
add additional resources or perform specific cleanup operations in their
destructors, it's essential that these destructors are called in the correct
order. Declaring the base class destructor as virtual ensures that the
6

destructors are invoked in the correct order, starting from the most derived
class and going up the inheritance chain.
Avoid Memory Leaks: If you delete an object through a pointer to a base class
and the base class destructor is not virtual, then only the base class
destructor will be called. This could lead to memory leaks if the derived class
has dynamically allocated resources that need to be released. By making the
destructor virtual, the correct destructor for the most derived class will be
invoked, ensuring that all resources are properly cleaned up.
#include <iostream>
class Base {
public:
Base() { std::cout << "Base constructor called" << std::endl; }
virtual ~Base() { std::cout << "Base destructor called" << std::endl; }
};
class Derived : public Base {
private:
int* data;
public:
Derived() : data(new int[5]) { std::cout << "Derived constructor called" <<
std::endl; }
~Derived() override {
delete[] data;
std::cout << "Derived destructor called" << std::endl;
}
};
int main() {
Base* basePtr = new Derived();
delete basePtr;
return 0;
}

Q7. What is the di erence between a base class pointer and derived class
pointer.
Ans: Base Class: A base class is a class in Object-Oriented Programming
language, from which other classes are derived. The class which inherits the
base class has all members of a base class as well as can also have some
additional properties. The Base class members and member functions are
inherited to Object of the derived class. A base class is also called parent
class or superclass.
7

Derived Class: A class that is created from an existing class. The derived
class inherits all members and member functions of a base class. The derived
class can have more functionality with respect to the Base class and can
easily access the Base class. A Derived class is also called a child
class or subclass.

#include <iostream>
using namespace std;
class Base {
public:
int a;
};
class Derived : public Base {
public:
int b;
};
int main()
{
Derived geeks;
geeks.b = 3;
geeks.a = 4;
cout << "Value from derived class: "
<< geeks.b << endl;
cout << "Value from base class: "
<< geeks.a << endl;
return 0;
}
8

Q8. Discuss the role of virtual function.


Ans: Virtual functions play a crucial role in achieving runtime polymorphism
in C++. Polymorphism refers to the ability of di erent objects to respond to
the same message (i.e., function call) in di erent ways. The role of virtual
functions can be understood in several aspects:
 Dynamic Binding: Virtual functions enable dynamic binding, also
known as late binding or runtime binding. When a base class pointer or
reference is used to call a virtual function on an object of a derived
class, the actual function to be called is determined at runtime based
on the type of the object. This allows for flexible and dynamic behavior,
as the appropriate function implementation is selected based on the
actual object type rather than the type of the pointer or reference.
 Overriding: Virtual functions enable derived classes to provide their
own implementation of a function defined in the base class. This is
achieved through function overriding. When a virtual function is
redefined in a derived class, the derived class's version of the function is
called when invoked through a base class pointer or reference. This
allows for customization and specialization of behavior in derived
classes while maintaining a common interface through the base class.
 Base Class Interface: Virtual functions define a common interface for a
hierarchy of classes. By declaring certain functions as virtual in a base
class, you establish a contract that derived classes must adhere to by
providing their own implementation of those functions. This facilitates
code reuse, as algorithms written to operate on base class pointers or
references can work with objects of any derived class that implements
the virtual functions.
 Decoupling: Virtual functions help decouple the implementation
details of derived classes from the code that uses them. Clients
interacting with objects through base class interfaces do not need to
know the specific derived class implementations. This promotes
modularity and flexibility, as changes to derived class implementations
can be made without a ecting the code that uses the base class
interface.
Q9. Explain the features of default argument.
Ans: Default arguments in C++ provide the capability to define default values
for function parameters. When a function is called without providing a value
for a parameter with a default argument, the default value specified in the
function declaration is used. Here are the features of default arguments:
9

 Simplify Function Calls: Default arguments allow you to define


functions with a varying number of parameters while providing default
values for some of those parameters. This simplifies function calls by
allowing you to omit arguments that have default values.
 Flexibility: Default arguments provide flexibility in function usage. They
allow functions to have a variety of di erent forms, with some
parameters being optional. Users can choose to provide values only for
the parameters they need, relying on the defaults for the rest.
 Overloading Reduction: Default arguments can help reduce the need
for function overloading. Instead of defining multiple overloaded
versions of a function with di erent parameter lists, you can use default
arguments to achieve similar functionality in a single function definition.
 Maintainability: Default arguments can improve code maintainability
by reducing the number of function definitions needed for di erent
combinations of parameter values. This makes it easier to understand
and maintain code with fewer function variations.
 Declaration and Definition Separation: Default arguments are
specified in the function declaration, allowing you to separate the
function interface (declaration) from its implementation (definition).
This can improve code readability and organization.
Q10. What is the di erence between multilevel and hybrid inheritance?
Ans: Multilevel and hybrid inheritance are both forms of inheritance in object-
oriented programming, but they di er in how classes are organized and how
inheritance relationships are structured:
Multilevel Inheritance:
 In multilevel inheritance, there is a single base class and multiple levels
of derived classes.
 Each derived class serves as the base class for the next level of derived
classes, forming a hierarchical chain of inheritance.
 This creates a parent-child relationship between classes, where each
derived class inherits the members of its immediate base class, as well
as all the members of its ancestors up the inheritance hierarchy.
 Multilevel inheritance promotes code reuse and allows for the creation
of specialized classes by adding functionality to existing classes at
di erent levels of the hierarchy.
 Example: Class A is the base class, Class B is derived from A, and Class
C is derived from B. Here, B inherits from A, and C inherits from B,
creating a multilevel inheritance chain: A -> B -> C.
10

Hybrid Inheritance:
 Hybrid inheritance is a combination of multiple forms of inheritance,
including multiple, multilevel, or hierarchical inheritance.
 It involves the inheritance of classes from multiple base classes in
di erent ways, resulting in a more complex inheritance structure.
 This can include scenarios where a derived class inherits from multiple
base classes directly (multiple inheritance), as well as scenarios where
inheritance relationships form a hierarchical chain (multilevel
inheritance).
 Hybrid inheritance allows for greater flexibility in class organization and
relationship modeling, but it can also lead to issues such as the
diamond problem in multiple inheritance.
 Example: Class A is the base class, Class B and Class C are derived
from A, and Class D is derived from both B and C. Here, D inherits from
both B and C directly, creating a multiple inheritance relationship, and B
and C form a multilevel inheritance chain with A: A -> B, A -> C, B -> D, C
-> D.
Q11. Write a program to define classes A, B and C. The class C is derived
from A and B classes. Define count() member function in all the
classes as virtual. Count the number of object.
Ans: #include <iostream>
class A {
public:
static int objectCount;
A() {
objectCount++;
}
virtual void count() {
std::cout << "Class A Objects: " << objectCount << std::endl;
}
};
class B {
public:
static int objectCount;
B() {
objectCount++;
}
virtual void count() {
std::cout << "Class B Objects: " << objectCount << std::endl;
11

}
};
class C : public A, public B {
public:
static int objectCount;
C() {
objectCount++;
}
virtual void count() {
std::cout << "Class C Objects: " << objectCount << std::endl;
}
};
int A::objectCount = 0;
int B::objectCount = 0;
int C::objectCount = 0;
int main() {
A a1, a2;
B b1;
C c1, c2;
a1.count();
b1.count();
c1.count();
return 0;
}

Q12. What is constructor and destructor in C++? Describe advantages of


constructor and destructor in C++?
Ans: In C++, constructors and destructors are special member functions of a
class that are automatically invoked during object creation and destruction,
respectively. They serve the following purposes:
Constructor:
 A constructor is a member function with the same name as the class.
 It is automatically called when an object of the class is created.
 Constructors initialize the object's data members, allocate resources,
and perform any necessary setup tasks.
 Constructors can be overloaded, allowing multiple constructors with
di erent parameter lists to be defined for a class.
 If no constructor is explicitly defined in a class, the compiler generates a
default constructor, which initializes data members with default values.
12

 Constructors can be used to ensure that objects are always in a valid


state after creation.
Destructor:
 A destructor is a member function with the same name as the class
preceded by a tilde (~).
 It is automatically called when an object of the class is destroyed, either
explicitly using the delete operator or when the object goes out of
scope.
 Destructors are responsible for releasing resources acquired by the
object during its lifetime, such as dynamically allocated memory, file
handles, or database connections.
 Destructors can be used to perform cleanup tasks and ensure that
resources are properly released to avoid memory leaks or resource
leaks.
 If no destructor is explicitly defined in a class, the compiler generates a
default destructor, which performs no cleanup actions.
 Destructors can be virtual, allowing derived classes to properly release
resources allocated by their base classes when objects are destroyed
through base class pointers.
Advantages of constructors and destructors in C++:
 Initialization and Cleanup: Constructors ensure that objects are
properly initialized, while destructors ensure that resources are
released and cleanup tasks are performed when objects are no longer
needed. This helps in managing resources e iciently and prevents
memory leaks or resource leaks.
 Automatic Invocation: Constructors and destructors are automatically
invoked during object creation and destruction, respectively. This
ensures that initialization and cleanup tasks are performed consistently
and automatically, reducing the risk of errors caused by forgetting to
initialize or release resources.
 Encapsulation: Constructors and destructors are integral parts of the
class definition, allowing initialization and cleanup logic to be
encapsulated within the class itself. This promotes encapsulation and
helps in creating self-contained and modular code.
 Customization and Overloading: Constructors and destructors can be
customized to suit the specific needs of a class by overloading them
with di erent parameter lists or by providing user-defined
implementations. This allows classes to support di erent initialization
methods and cleanup procedures based on usage requirements.
13

 Resource Management: Destructors play a crucial role in managing


resources such as memory, file handles, or database connections. By
releasing resources in destructors, classes can ensure that resources
are properly managed and that system resources are not leaked or
wasted.
Q13. What is encapsulation on OOP? Discuss its importance with suitable
example in C++?
Ans: Encapsulation is one of the fundamental concepts in object-oriented
programming (OOP) that refers to the bundling of data and methods that
operate on that data into a single unit, called a class. Encapsulation hides the
internal state of an object from the outside world and only exposes the
necessary functionality through well-defined interfaces. This allows for better
control over how data is accessed and manipulated, improving code
modularity, security, and maintainability.
Two Important property of Encapsulation
 Data Protection: Encapsulation protects the internal state of an object
by keeping its data members private. Access to and modification of
these data members is restricted to the class’s public methods,
ensuring controlled and secure data manipulation.
 Information Hiding: Encapsulation hides the internal implementation
details of a class from external code. Only the public interface of the
class is accessible, providing abstraction and simplifying the usage of
the class while allowing the internal implementation to be modified
without impacting external code.
#include <iostream>
using namespace std;
class temp{
int a;
int b;
public:
int solve(int input){
a=input;
b=a/2;
return b;
}
};
int main() {
int n;
14

cin>>n;
temp half;
int ans=half.solve(n);
cout<<ans<<endl;
}

Q14. What is friend function? Discuss advantages of friend function with


suitable example in C++ ?
Ans: In C++, a friend function is a function that is not a member of a class but
has access to the private and protected members of the class as if it were a
member function. Friend functions are declared inside a class using the friend
keyword, and they are often used to provide special access to class internals
without violating encapsulation principles.
Advantages of friend functions:
 Access to Private Members: Friend functions can access the private
and protected members of a class, allowing them to manipulate class
internals directly. This can be useful in situations where certain
operations require access to private data members but cannot be
implemented as member functions.
 Improved Encapsulation: Although friend functions can access private
members, they are not members of the class itself. This allows for
selective exposure of class internals to specific functions or external
classes while still maintaining encapsulation. Friend functions can be
used to provide controlled access to class internals without
compromising data integrity.
 Simplicity and Convenience: Friend functions provide a simple and
convenient way to implement operations that require access to private
members of a class. They allow you to define standalone functions that
operate on class objects without the need to pass objects as arguments
or use accessor methods.
 Enhanced Flexibility: Friend functions can be defined outside the class
definition, providing flexibility in function implementation and
organization. They can be placed in separate source files or
namespaces, allowing for better code organization and maintainability.
 E iciency: Friend functions can improve performance in certain
scenarios by avoiding the overhead of function calls associated with
member functions. Since friend functions are not members of the class,
they do not require the implicit this pointer and can be more e icient in
terms of memory and execution time.
15

#include <iostream>
class MyClass {
private:
int value;
public:
MyClass(int v) : value(v) {}
friend void printValue(const MyClass& obj);
};
void printValue(const MyClass& obj) {
std::cout << "Value: " << obj.value << std::endl;
}
int main() {
MyClass obj(42);
printValue(obj); // Output: Value: 42
return 0;
}

Q15. What is reference object in C++ ? Discuss with suitable example.


Ans: In C++, a reference is an alias or alternative name for an existing object.
Unlike pointers, which can be reassigned to point to di erent objects,
references are bound to the object they are initialized with and cannot be
reassigned to refer to a di erent object after initialization. References are
commonly used to provide an alternative syntax for accessing objects and to
pass arguments to functions by reference.
#include <iostream>
int main() {
int x = 10;
int& ref = x;
std::cout << "Original value of x: " << x << std::endl;
std::cout << "Value of ref: " << ref << std::endl;
ref = 20;
std::cout << "Modified value of x: " << x << std::endl;
std::cout << "Value of ref after modification: " << ref << std::endl;
return 0;
}
Q16. What is polymorphism? Discuss with suitable example.
Ans: Polymorphism is a fundamental concept in object-oriented
programming (OOP) that refers to the ability of di erent objects to respond to
the same message (i.e., function call) in di erent ways. Polymorphism allows
objects of di erent classes to be treated as objects of a common superclass
16

through a common interface, enabling code to be written in a generic and


flexible manner.
There are two main types of polymorphism in C++: compile-time
polymorphism (achieved through function overloading and templates) and
runtime polymorphism (achieved through virtual functions and inheritance).
Runtime polymorphism is often associated with inheritance and is typically
implemented using virtual functions.
#include <iostream>
class Shape {
public:
virtual double calculateArea() const = 0;
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double calculateArea() const override {
return 3.14 * radius * radius;
}
};
class Rectangle : public Shape {
private:
double length;
double width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
double calculateArea() const override {
return length * width;
}
};
int main() {
Circle circle(5);
Rectangle rectangle(4, 6);
std::cout << "Area of the circle: " << circle.calculateArea() << std::endl;
std::cout << "Area of the rectangle: " << rectangle.calculateArea() <<
std::endl;
return 0;
}
17

Q17. What is namespace in C++? Write advantage of namespace in C++.


Ans: In C++, a namespace is a declarative region that provides a way to
logically group related code and prevent name conflicts between di erent
parts of a program. Namespaces help organize code into logical units, making
it easier to manage and maintain large codebases. They provide scope for
identifiers, such as variables, functions, classes, and enumerations, allowing
them to be uniquely identified within the namespace.
Advantages of namespaces in C++:
 Prevention of Name Collisions: One of the primary advantages of
namespaces is that they help prevent name conflicts by providing a
scope for identifiers. By placing related code within a namespace, you
can avoid naming conflicts between identifiers with the same name
defined in di erent parts of a program.
 Modularity and Organization: Namespaces allow you to organize code
into logical units based on functionality, domain, or module. This
promotes modularity and improves code organization, making it easier
to understand, navigate, and maintain large codebases.
 Encapsulation: Namespaces encapsulate code within a specific
scope, limiting the visibility of identifiers to only the parts of the program
where they are needed. This helps reduce the risk of unintended
dependencies and enhances code encapsulation, leading to better
code isolation and reusability.
 Aliasing and Renaming: Namespaces allow you to alias or rename
identifiers from other namespaces, providing a way to create shorter,
more concise names for commonly used functionality. This can improve
code readability and reduce the likelihood of naming conflicts.
 Avoidance of Global Namespace Pollution: Using namespaces helps
avoid polluting the global namespace with numerous identifiers,
reducing the risk of naming collisions and improving code clarity.
Identifiers declared within a namespace are accessible only within that
namespace unless explicitly specified otherwise.
18

Q18. What is inheritance in C++? Discuss types of inheritance in C++ with


suitable examples.
Ans: Inheritance is a fundamental concept in object-oriented programming
(OOP) that allows a class (called the derived class or child class) to inherit
properties and behaviors from another class (called the base class or parent
class). Inheritance facilitates code reuse, promotes modularity, and allows for
the creation of hierarchical class structures.
Types of Inheritance in C++
1. Single Inheritance: In single inheritance, a class is allowed to inherit from
only one class. i.e. one subclass is inherited by one base class only.

#include <iostream>
class Animal {
public:
void speak() {
std::cout << "Animal speaks" << std::endl;
}
};
class Dog : public Animal {
public:
void bark() {
std::cout << "Dog barks" << std::endl;
}
};
int main() {
Dog dog;
dog.speak();
dog.bark();
return 0;
}
2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class
can inherit from more than one class. i.e one subclass is inherited from more
than one base class.
19

#include <iostream>
class Parent1 {
public:
void function1() {
std::cout << "Function 1 from Parent1" << std::endl;
}
};

class Parent2 {
public:
void function2() {
std::cout << "Function 2 from Parent2" << std::endl;
}
};
class Child : public Parent1, public Parent2 {
public:
void function3() {
std::cout << "Function 3 from Child" << std::endl;
}
};
int main() {
Child obj;
obj.function1();
obj.function2();
obj.function3();
return 0;
}
3. Multilevel Inheritance: In this type of inheritance, a derived class is
created from another derived class.
20

#include <iostream>
class Animal {
public:
void speak() {
std::cout << "Animal speaks" << std::endl;
}
};
class Dog : public Animal {
public:
void bark() {
std::cout << "Dog barks" << std::endl;
}
};
class Puppy : public Dog {
public:
void play() {
std::cout << "Puppy plays" << std::endl;
}
};
int main() {
Puppy puppy;
puppy.speak();
puppy.bark();
puppy.play();
return 0;
}
4. Hierarchical Inheritance: In this type of inheritance, more than one
subclass is inherited from a single base class. i.e. more than one derived class
is created from a single base class.
21

#include <iostream>
class Animal {
public:
void speak() {
std::cout << "Animal speaks" << std::endl;
}
};
class Dog : public Animal {
public:
void bark() {
std::cout << "Dog barks" << std::endl;
}
};
class Cat : public Animal {
public:
void meow() {
std::cout << "Cat meows" << std::endl;
}
};
int main() {
Dog dog;
Cat cat;
dog.speak(); // Inherits from Animal class
dog.bark();
cat.speak(); // Inherits from Animal class
cat.meow();
return 0;
}
5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by
combining more than one type of inheritance. For example: Combining
Hierarchical inheritance and Multiple Inheritance.
22

#include <iostream>
class Animal {
public:
void speak() {
std::cout << "Animal speaks" << std::endl;
}
};
class Mammal {
public:
void feedMilk() {
std::cout << "Mammal feeds milk" << std::endl;
}
};
class Dog : public Animal, public Mammal {
public:
void bark() {
std::cout << "Dog barks" << std::endl;
}
};
int main() {
Dog dog;
dog.speak(); // Inherits from Animal class
dog.feedMilk();// Inherits from Mammal class
dog.bark();
return 0;
}
23

Q19. Discuss the types of constructor in C++ with suitable example.


Ans: In C++, constructors are special member functions of a class that are
automatically called when an object of the class is created. Constructors
initialize the object's data members and perform any necessary setup tasks.
There are several types of constructors in C++:
Default Constructor:
 A default constructor is a constructor that takes no arguments or has all
its parameters provided with default values.
 If a class does not explicitly define any constructors, the compiler
generates a default constructor automatically.
 The default constructor initializes data members with default values (if
any) or performs no initialization if the data members are not explicitly
initialized.
#include <iostream>
class MyClass {
public:
MyClass() {
std::cout << "Default constructor called" << std::endl;
}
};
int main() {
MyClass obj; // Default constructor called
return 0;
}
Parameterized Constructor:
 A parameterized constructor is a constructor that takes one or more
parameters to initialize the object's data members with user-specified
values.
 Parameterized constructors allow for custom initialization of objects
based on the values provided by the caller.
#include <iostream>
class Point {
private:
int x, y;
public:
Point(int xCoord, int yCoord) : x(xCoord), y(yCoord) {
std::cout << "Parameterized constructor called" << std::endl;
}
24

void display() {
std::cout << "Point: (" << x << ", " << y << ")" << std::endl;
}
};
int main() {
Point p1(3, 5);
p1.display();
return 0;
}
Copy Constructor:
 A copy constructor is a constructor that initializes an object by making a
copy of another object of the same class.
 It is called when an object is passed by value as an argument to a
function, returned by value from a function, or initialized with another
object of the same class.
#include <iostream>
class MyClass {
private:
int data;
public:
MyClass(int d) : data(d) {}
MyClass(const MyClass& other) {
data = other.data;
std::cout << "Copy constructor called" << std::endl;
}
void display() {
std::cout << "Data: " << data << std::endl;
}
};
int main() {
MyClass obj1(10);
MyClass obj2 = obj1;
obj1.display();
obj2.display();
return 0;
}
Destructor: Though not strictly a constructor, the destructor is a special
member function called when an object goes out of scope or is explicitly
deleted. It cleans up resources allocated by the object, such as memory or
file handles.
25

#include <iostream>
class MyClass {
public:
MyClass() {
std::cout << "Constructor called" << std::endl;
}
~MyClass() {
std::cout << "Destructor called" << std::endl;
}
};
int main() {
MyClass obj; // Constructor called
return 0;
}

Q20. What is exception? What are the mechanism to handle exception?


Explain try, catch keywords with suitable example.
Ans: An exception is an event that occurs during the execution of a program
that disrupts the normal flow of control. Exceptions can occur for various
reasons, such as errors in input data, resource exhaustion, or unexpected
conditions. When an exception occurs, the program can handle it gracefully
by transferring control to an appropriate exception handler, allowing for
recovery or termination of the program in a controlled manner.
C++ provides mechanisms to handle exceptions using the following
keywords:
 try: The try block is used to enclose the code that may potentially throw
an exception. If an exception occurs within the try block, the control is
transferred to the corresponding catch block.
 catch: The catch block is used to catch and handle exceptions thrown
within the associated try block. It specifies the type of exception that it
can handle, allowing for di erent catch blocks to handle di erent types
of exceptions.
 throw: The throw keyword is used to explicitly throw an exception within
the code. It can be used to raise an exception when an error condition is
encountered.
#include <iostream>
int main() {
try {
26

int divisor = 0;
int result = 10 / divisor; // Division by zero will cause an exception
std::cout << "Result: " << result << std::endl;
} catch (const std::exception& e) {
std::cerr << "Exception caught: " << e.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception caught" << std::endl;
}
return 0;
}
Q21. Why abstraction is important in OOP? Discuss its importance with
suitable example.
Ans: Abstraction is a fundamental concept in object-oriented programming
(OOP) that involves simplifying complex systems by representing essential
features while hiding unnecessary details. It allows developers to focus on the
relevant aspects of a system, making it easier to understand, maintain, and
extend. Abstraction plays a crucial role in OOP for several reasons:
 Simplification of Complex Systems: Abstraction enables developers
to focus on high-level concepts and ignore irrelevant details, thus
simplifying the understanding and management of complex systems. By
hiding implementation details, abstraction allows programmers to work
with simplified models of real-world objects or systems.
 Modularity and Encapsulation: Abstraction promotes modularity by
encapsulating related data and behavior into a single unit, such as a
class. This allows for the creation of reusable components with well-
defined interfaces, reducing code duplication and improving code
organization and maintainability.
 Enhanced Code Reusability: Abstraction encourages the creation of
reusable components with well-defined interfaces, making it easier to
reuse code across di erent parts of a system or in di erent projects. By
designing classes and interfaces that abstract away implementation
details, developers can create libraries and frameworks that can be
easily integrated into other projects.
 Flexibility and Adaptability: Abstraction allows for the creation of
flexible and adaptable systems that can evolve over time. By designing
27

classes and interfaces that abstract away implementation details,


developers can make changes to the underlying implementation
without a ecting the external interfaces, thus minimizing the impact of
changes on other parts of the system.
 Improved Problem Solving: Abstraction helps developers focus on
solving higher-level problems rather than getting bogged down in
implementation details. By working with abstract representations of
objects or systems, developers can analyze and solve problems at a
higher level of abstraction, leading to more e ective and e icient
solutions.
#include <iostream>
class Car {
public:
void startEngine() {
std::cout << "Engine started" << std::endl;
}
void accelerate() {
std::cout << "Car is accelerating" << std::endl;
}
void brake() {
std::cout << "Car is braking" << std::endl;
}
void turn() {
std::cout << "Car is turning" << std::endl;
}
};
int main() {
Car myCar;
myCar.startEngine();
myCar.accelerate();
myCar.brake();
myCar.turn();
return 0;
}
Q22. How is polymorphism achieved at (1) compile time and (2) run time?
Ans: Polymorphism, the ability of objects to take on multiple forms, can be
achieved in C++ at both compile time and runtime using di erent
mechanisms:
Compile-time Polymorphism: Compile-time polymorphism is achieved
through function overloading and templates.
28

 Function Overloading: In function overloading, multiple functions can


have the same name but with di erent parameter lists. The compiler
selects the appropriate function to call based on the number and types
of arguments provided at the call site.
#include <iostream>
void display(int num) {
std::cout << "Integer: " << num << std::endl;
}
void display(double num) {
std::cout << "Double: " << num << std::endl;
}
int main() {
display(5);
display(3.14);
return 0;
}
Run-time Polymorphism: Run-time polymorphism is achieved through
virtual functions and inheritance.
 Virtual Functions: A virtual function is a member function declared
within a base class that can be overridden by derived classes. The
appropriate function to call is determined at runtime based on the
dynamic type of the object.
#include <iostream>
class Base {
public:
virtual void display() {
std::cout << "Base class display()" << std::endl;
}
};
class Derived : public Base {
public:
void display() override {
std::cout << "Derived class display()" << std::endl;
}
};
int main() {
Base* ptr = new Derived();
ptr->display();
delete ptr;
29

return 0;
}
Q23. Describe various stream classes for console I/O operations.
Ans: In C++, console input and output operations are performed using stream
classes provided by the C++ Standard Library, namely iostream. These
classes allow data to flow between the program and the console (standard
input/output streams).
Here are the main stream classes for console I/O operations:
std::cin:
 The std::cin stream is the standard input stream, which is used to read
data from the console (keyboard) into the program.
 It is associated with the standard input device (keyboard) by default.
 It is typically used with extraction operators (>>) to read di erent types
of data from the console.
#include <iostream>
int main() {
int num;
std::cout << "Enter a number: ";
std::cin >> num;
std::cout << "You entered: " << num << std::endl;
return 0;
}
std::cout:
 The std::cout stream is the standard output stream, which is used to
write data from the program to the console (standard output).
 It is associated with the standard output device (console) by default.
 It is typically used with insertion operators (<<) to write di erent types of
data to the console.
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl; // Write "Hello, World!" to console
return 0;
}
std::cerr:
 The std::cerr stream is the standard error stream, which is used to
output error messages and diagnostic information to the console.
 It is similar to std::cout, but it is typically used for error reporting.
30

 Error messages written to std::cerr are not bu ered, so they appear


immediately on the console.
#include <iostream>
int main() {
std::cerr << "Error: Something went wrong!" << std::endl;
return 1;
}
Q24. What do you mean by dynamic binding? How is it useful in OOP ?
Explain with an example.
Ans: Dynamic binding, also known as late binding or runtime polymorphism,
is a mechanism in object-oriented programming (OOP) where the selection of
a method to call is determined at runtime based on the actual type of the
object rather than the declared type of the pointer or reference to that object.
In other words, dynamic binding allows for the invocation of overridden
methods of derived classes through base class pointers or references.
Dynamic binding is useful in OOP because it allows for the implementation of
polymorphic behavior, where objects of di erent derived classes can respond
di erently to the same method call based on their actual runtime types. This
enhances flexibility, extensibility, and maintainability of the code by enabling a
single interface to be used for di erent implementations.
#include <iostream>
class Shape {
public:
virtual void draw() const {
std::cout << "Drawing a shape" << std::endl;
}
};
class Circle : public Shape {
public:
void draw() const override {
std::cout << "Drawing a circle" << std::endl;
}
};
class Rectangle : public Shape {
public:
void draw() const override {
std::cout << "Drawing a rectangle" << std::endl;
31

}
};
int main() {
Circle circle;
Rectangle rectangle;
Shape* ptrShape1 = &circle;
Shape* ptrShape2 = &rectangle;
ptrShape1->draw(); // Output: Drawing a circle
ptrShape2->draw(); // Output: Drawing a rectangle
return 0;
}
Q25. Describe the basic structure of a C++ program with all necessary
blocks.
Ans: A basic structure of a C++ program typically consists of several
essential blocks, including:
 Preprocessor Directives: These are instructions to the compiler that
begin with a # symbol. They are processed before the actual
compilation of the code and are used to include header files, define
constants, and perform other preprocessing tasks.
 Namespace Declaration: A namespace is a declarative region that
provides a scope for identifiers. It helps organize code and avoid naming
conflicts. The namespace keyword is used to define namespaces.
 Main Function: Every C++ program must contain a main() function,
which serves as the entry point of the program. It is where the execution
of the program begins.
 Variable Declarations: Variables are used to store data values. They
must be declared before they can be used in the program. Variable
declarations typically occur within functions or at the beginning of a
code block.
 Executable Statements: Executable statements perform actions or
computations within the program. They can include assignments,
function calls, control flow statements (e.g., if, for, while), and other
expressions.
 Function Definitions: Functions are named blocks of code that
perform specific tasks. They can be declared and defined within the
program to encapsulate functionality and promote code reuse.
 Return Statement: The return statement is used to terminate the
execution of a function and return a value (if applicable) to the caller. In
the main() function, it indicates the successful execution of the
program.
32

#include <iostream>
using namespace std;
void greet();
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "You entered: " << age << endl;
greet();
return 0;
}
void greet() {
cout << "Hello!" << endl;
}

Q26. Explain what are the methods used to create changes in subclasses.
Discuss with suitable example.
Ans: In object-oriented programming (OOP), changes in subclasses can be
made using inheritance, method overriding, and method overloading. These
techniques allow subclasses to modify or extend the behavior of their
superclass, providing flexibility and customization in class hierarchies.
 Inheritance: Inheritance allows subclasses to inherit properties and
behaviors from their superclass. Subclasses can override inherited
methods, add new methods, or access superclass methods and
properties.
#include <iostream>
class Animal {
public:
void makeSound() const {
std::cout << "Animal makes a sound" << std::endl;
}
};
class Dog : public Animal {
public:
void makeSound() const {
std::cout << "Dog barks" << std::endl;
}
};
int main() {
33

Dog dog;
dog.makeSound();
return 0;
}
 Method Overriding: Method overriding allows subclasses to provide
their own implementation for a method defined in the superclass. This
enables polymorphic behavior, where the appropriate method to call is
determined at runtime based on the actual type of the object.
#include <iostream>
class Animal {
public:
virtual void makeSound() const {
std::cout << "Animal makes a sound" << std::endl;
}
};
class Dog : public Animal {
public:
void makeSound() const override {
std::cout << "Dog barks" << std::endl;
}
};
int main() {
Animal* animal = new Dog();
animal->makeSound();
delete animal;
return 0;
}
Q27. Discuss the inline function with suitable example. Also write down
the limitations.
Ans: An inline function in programming is a function that is expanded in-line at
the point of call, rather than being executed through a function call
mechanism. This means that the compiler replaces the function call with the
actual code of the function, thereby potentially improving performance by
eliminating the overhead of a function call.
#include <iostream>
inline int add(int a, int b) {
return a + b;
}
int main() {
34

int result = add(5, 3);


std::cout << "Result: " << result << std::endl;
return 0;
}
Limitations of inline functions are:
 Code Bloat: Since the compiler replaces the function call with the
actual code, if the function is large or called multiple times, it can lead
to code bloat, increasing the size of the executable.
 Compilation Time: Inlining functions can increase compilation time
because the compiler has to duplicate the function's code at every call
site.
 Limited Optimization Opportunities: Inline functions may restrict
certain optimization opportunities for the compiler since the function's
code is directly inserted at the call site.
 Debugging: Debugging inline functions can be more challenging
because the function's code is spread across multiple locations in the
program.
 Header Files: If an inline function is defined in a header file and included
in multiple source files, it can violate the one definition rule and lead to
linker errors.
Q28. Di erentiate between overloading and overriding function.
Ans:

Function Overloading Function Overriding

Function Overriding is the


Function Overloading provides
redefinition of base class
multiple definitions of the function
function in its derived class with
by changing signature.
same signature.

An example of compile time An example of run time


polymorphism. polymorphism.

Function signatures should be Function signatures should be


different. the same.

Overloaded functions are in same Overridden functions are in


scope. different scopes.
35

Overloading is used when the Overriding is needed when


same function has to behave derived class function has to do
differently depending upon some different job than the base
parameters passed to them. class function.

A function has the ability to load A function can be overridden


multiple times. only a single time.

In function overloading, we don’t In function overriding, we need


need inheritance. an inheritance concept.

Q29. Define the stream class hierarchy.


Ans: In C++, the stream class hierarchy is a key component of the Standard
Template Library (STL) used for input/output operations. It consists of various
classes that facilitate reading from and writing to di erent types of data
sources, such as standard input/output devices, files, and memory bu ers.
The stream class hierarchy is typically organized into two main categories:
input streams and output streams. Here's a basic overview:
Input Stream Classes:
 istream: The base class for input streams. It provides functionality for
reading data from input sources.
 ifstream: Input file stream, used for reading data from files.
 istringstream: Input string stream, used for reading data from strings.
 istream_iterator: Iterator for sequential input operations on a stream.
 istreambuf_iterator: Iterator for reading characters from the underlying
bu er of a stream.
Output Stream Classes:
 ostream: The base class for output streams. It provides functionality for
writing data to output destinations.
 ofstream: Output file stream, used for writing data to files.
 ostringstream: Output string stream, used for writing data to strings.
 ostream_iterator: Iterator for sequential output operations on a stream.
 ostreambuf_iterator: Iterator for writing characters to the underlying
bu er of a stream.
36

Bidirectional Stream Classes:


 iostream: The base class for bidirectional streams, which support both
input and output operations.
 fstream: Bidirectional file stream, used for both reading from and
writing to files.
 stringstream: Bidirectional string stream, used for both reading from
and writing to strings.
Q30.Compare the features of object-oriented programming with
procedural oriented programming.
Ans:
Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the In object-oriented programming,


program is divided into small parts the program is divided into small
called functions. parts called objects.

Procedural programming follows Object-oriented programming


a top-down approach. follows a bottom-up approach.

Object-oriented programming
There is no access specifier in
has access specifiers like private,
procedural programming.
public, protected, etc.

Adding new data and functions is Adding new data and function is
not easy. easy.

Procedural programming does not Object-oriented programming


have any proper way of hiding provides data hiding so it is more
data so it is less secure. secure.

In procedural programming, Overloading is possible in object-


overloading is not possible. oriented programming.

In procedural programming, there In object-oriented programming,


is no concept of data hiding and the concept of data hiding and
inheritance. inheritance is used.
37

Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the In object-oriented programming,


function is more important than data is more important than
the data. function.

Procedural programming is based Object-oriented programming is


on the unreal world. based on the real world.

Examples: C, FORTRAN, Pascal, Examples: C++, Java, Python, C#,


Basic, etc. etc.

Q31. Discuss input/output operation of file in binary mode.


Ans: Input/output operations on files in binary mode involve reading from or
writing to files without any interpretation or translation of the data. In binary
mode, data is read or written as-is, byte by byte, without any conversion. This
mode is useful when dealing with non-text files, such as images, audio, video,
or binary data files.
Here's how input/output operations in binary mode work in C++:
Opening a File in Binary Mode:
 To perform input/output operations in binary mode, you need to open
the file in binary mode explicitly by adding "ios::binary" flag when
opening the file.
#include <iostream>
#include <fstream>
int main() {
std::ifstream inputFile("binary_data.bin", std::ios::binary);
std::ofstream outputFile("output_data.bin", std::ios::binary |
std::ios::out);
inputFile.close();
outputFile.close();
return 0;
}
Reading from a Binary File:
 To read from a binary file, you can use methods like read() to read a
specified number of bytes directly into a bu er.
38

#include <iostream>
#include <fstream>
int main() {
std::ifstream inputFile("binary_data.bin", std::ios::binary);
if (inputFile.is_open()) {
char bu er[100];
inputFile.read(bu er, sizeof(bu er));
inputFile.close();
} else {
std::cerr << "Error opening file for reading." << std::endl;
}
return 0;
}
Writing to a Binary File:
 To write to a binary file, you can use methods like write() to write binary
data directly from a bu er.
#include <iostream>
#include <fstream>
int main() {
std::ofstream outputFile("output_data.bin", std::ios::binary |
std::ios::out);
if (outputFile.is_open()) {
char bu er[] = "This is binary data.";
outputFile.write(bu er, sizeof(bu er) - 1); // Exclude null terminator
outputFile.close();
} else {
std::cerr << "Error opening file for writing." << std::endl;
}
return 0;
}
Seeking within a Binary File:
 You can use methods like seekg() and seekp() to move the file pointer to
a specific position within the file for reading or writing.
#include <iostream>
#include <fstream>
int main() {
std::ifstream inputFile("binary_data.bin", std::ios::binary);
if (inputFile.is_open()) {
inputFile.seekg(10, std::ios::beg);
39

char bu er[100];
inputFile.read(bu er, sizeof(bu er));
inputFile.close();
} else {
std::cerr << "Error opening file for reading." << std::endl;
}
return 0;
}
Q32. What is operator overloading? Discuss unary operator overloading
with suitable example.
Ans: Operator overloading is a feature in object-oriented programming
languages that allows operators to be redefined or overloaded so that they
can be used with user-defined data types. This enables objects of a class to
behave like built-in data types regarding the use of operators.
Unary operator overloading specifically involves overloading unary operators,
which are operators that act on a single operand. Examples of unary operators
include ++, --, +, -, !, and ~.
Here's a discussion of unary operator overloading with a suitable example
in C++:
Unary Operator Overloading:
Unary operators are overloaded by defining member functions or friend
functions that take no arguments for the object on which they are invoked. The
unary operator functions can be defined as member functions or global
functions (friend functions) depending on whether they need access to private
members of the class.
#include <iostream> std::cout << "Count: " << count
class Counter { << std::endl;
private: }
int count; };
public:
Counter(int c = 0) : count(c) {} int main() {
Counter& operator++() { Counter c1(5);
++count; ++c1;
return *this; c1.display();
} return 0;
void display() { }

You might also like