0% found this document useful (0 votes)
5 views55 pages

Oopc++ Question Bank

The document is a question bank for a course on Object Oriented Programming in C++ at Parul Institute of Engineering and Technology. It covers various units including principles of OOP, functions, classes, constructors, inheritance, and pointers with detailed questions and answers. Each unit contains specific topics aimed at enhancing understanding of C++ and its object-oriented features.

Uploaded by

2403031287002
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)
5 views55 pages

Oopc++ Question Bank

The document is a question bank for a course on Object Oriented Programming in C++ at Parul Institute of Engineering and Technology. It covers various units including principles of OOP, functions, classes, constructors, inheritance, and pointers with detailed questions and answers. Each unit contains specific topics aimed at enhancing understanding of C++ and its object-oriented features.

Uploaded by

2403031287002
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/ 55

PARUL INSTITUTE OF

ENGINEERING AND TECHNOLOGY -


(DIPLOMA STUDIES)

COMPUTER ENGINEERING
DEPARTMENT

OBJECT ORIENTED PROGRAMMING


IN C++
(03606213)

QUESTION BANK
OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

QUESTION BANK

UNIT-1
PRINCIPLES OF OBJECT ORIENTED PROGRAMMIG
1. What is Object Oriented Programming Language?
2. List out the applications of Object Oriented Programming in detail.
3. Explain the principles of Object oriented programming language.
4. Explain advantages and disadvantages of Object Oriented Programming.
5. Explain structure of C++ with example.
6. Describe all datatypes used in C++.
7. How we can declare variable in C++?Explain with an example.
8. Describe dynamic initialization of variable in C++.
9. Explain reference variable in C++.
10. Explain scope resolution operator.
11. Differentiate OOP & POP.
12. What is the meaning of access specifier? Explain it with example.

UNIT-2
FUNCTIONS,CLASS AND OBJECTS
1. Define function with function prototype, function declaration & function calling.
2. Define an inline function & Explain How to implement an inline function with example.
3. Explain default and constant arguments with example.
4. Explain Function Overloading with example.
5. Define class & object.
6. Define Member Function & Nesting of Member Function.
7. Define Private Member Function.
8. What is Friend Function? Explain with example.
9. WAP using friend function to find maximum number between two numbers, two numbers are
the private data of two different class.
10. WAP which illustrate the use of object and class concept using to show student’s detail as output.

UNIT-3
CONSTRUCTOR AND DECONSTRUCTOR
1. What is constructor? Explain in brief with example.
2. Explain default constructor with program.
3. How to use a copy constructor? Justify with program.
4. Explain parameterized constructor with example.
5. Differentiate Constructor & Destructor.
6. What is Destructor? Give example.
7. Write a C++ Program to enter student details by Passing parameters to constructors.
8. Write a C++ program to perform operator overloading using constructor.

PIET -DS(CE) PAGE NO:2


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

UNIT-4
INHERITANCE
1. Explain Inheritance in C++ and also list out its types.
2. What are derived classes in C++?
3. Explain Single Inheritance with an example.
4. What is Multiple Inheritance? Explain it with an example.
5. What is Multilevel Inheritance? Explain it with an example.
6. What is Hybrid Inheritance? Explain it with an example.
7. What is Function Overriding in C++?Explain it with example.
8. Differentiate between Function Overloading and Function Overriding.
9. What is a Virtual Base Class? Explain it with an example.
10. Explain Abstract Classes in C++.

UNIT-5
POINTERS & VIRTUAL FUNCTIONS
1. Explain Pointers to Objects in C++.
2. How do you declare and initialize a pointer to an object in C++?
3. What is a Pointer to a Derived Class in C++?
4. Define Virtual Functions in C++.
5. Explain the concept of Pointer to Virtual Functions in C++.
6. What is the 'this' Pointer in C++?
7. What is the difference between a virtual function and a non-virtual function?

PIET -DS(CE) PAGE NO:3


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

ANSWERS

UNIT-1
PRINCIPLES OF OBJECT ORIENTED PROGRAMMIG

1. What is Object Oriented Programming Language?


Answer:
 Object-oriented programming (OO) is a programming language model that organizes programs
around objects and classes, rather than logic and actions.
 Object-oriented programming aims to implement real-world entities like inheritance, hiding,
polymorphism, etc in programming. The main aim of OOP is to bind together the data and the
functions that operate on them so that no other part of the code can access this data except that
function.

Benefits of OOP
 Modular, scalable, extensible, reusable, and maintainable.
 It models the complex problem in a simple structure.
 Object can be used across the program.
 Code can be reused.
 We can easily modify, append code without affecting the other code blocs.
 Provides security through encapsulation and data hiding features.
 Beneficial to collaborative development in which a large project is divided into groups.
 Debugging is easy.

Limitations of OOP
 Solving problems takes more time as compared to Procedure Oriented Programming.
 The size of the programs created using this approach may become larger than the programs
written using the procedure-oriented programming approach.
 OOP code is difficult to understand if you do not have the corresponding class documentation.
 In certain scenarios, these programs can consume a large amount of memory.
 Not suitable for small problems.
 Takes more time to solve problems.

2. List out the applications of Object Oriented Programming in detail.


Answer:
Object-Oriented Programming (OOP) finds applications in various domains. Here's a detailed list of
some of its common applications:
 Software Development: OOP is extensively used in software development across different
industries due to its modular, scalable, and maintainable nature. It's employed in developing
desktop applications, web applications, mobile apps, and enterprise systems.

 Graphical User Interface (GUI) Development: OOP is well-suited for creating GUI
applications because it allows developers to represent GUI components (such as buttons,
windows, and menus) as objects. Frameworks like Java Swing, JavaFX, Qt (C++), and Tkinter
(Python) leverage OOP principles for GUI development.
PIET -DS(CE) PAGE NO:4
OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

 Game Development: Many game development frameworks and engines, such as Unity (C#),
Unreal Engine (C++), and Godot Engine (GDScript), are based on OOP principles. OOP
facilitates the creation of game objects, characters, environments, and interactions, making it
easier to manage complex game logic.

 Database Systems: Object-Relational Mapping (ORM) frameworks, such as Hibernate (Java)


and Entity Framework (C#), enable developers to interact with databases using OOP principles.
ORM maps database tables to classes and objects, simplifying database operations and enhancing
code readability.

 Artificial Intelligence and Machine Learning: OOP is applied in building AI and ML systems,
including machine learning models, neural networks, and intelligent agents. OOP facilitates the
organization of code into reusable components, making it easier to develop and maintain complex
AI algorithms.

 Internet of Things (IoT): OOP is used in IoT development to model and control interconnected
devices and sensors. Object-oriented languages like Python and C++ are commonly used for IoT
programming, enabling developers to create modular and scalable IoT applications.

 Financial and Banking Systems: OOP is employed in developing financial software, banking
systems, and trading platforms. OOP principles such as encapsulation, inheritance, and
polymorphism help in modeling financial instruments, transactions, and business logic.

 E-commerce and Content Management Systems: OOP is widely used in building e-commerce
platforms, content management systems (CMS), and online marketplaces. OOP facilitates the
creation of reusable components for managing products, orders, users, and content.

 Embedded Systems: OOP is utilized in embedded systems development for controlling


hardware devices, sensors, and microcontrollers. Object-oriented languages like C++ are
commonly used in embedded programming to create modular and maintainable firmware.

3. Explain the principles of Object oriented programming language.


Answer:
The principles of Object oriented programming language are as follows:
 Object
 Class
 Encapsulation
 Inheritance
 Polymorphism
 Abstraction

Object
 An object is a real-world entity that has attributes, behavior, and properties. It is referred to as an
instance of the class.
 It contains member functions, variables that we have defined in the class.

PIET -DS(CE) PAGE NO:5


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

 It occupies space in the memory. Different objects have different states or attributes, and
behaviors.

Class
 A class is a blueprint or template of an object. It is a user-defined data type. Inside a class, we
define variables, constants, member functions, and other functionality.
 It binds data and functions together in a single unit. It does not consume memory at run time.
Classes are not considered as a data structure.
 It is a logical entity. It is the best example of data binding. Note that a class can exist without an
object but vice-versa is not possible.

Encapsulation:
 Encapsulation means bundling the data (properties) and methods (functions) that operate on the
data into a single unit called an object.
 This allows for the hiding of internal implementation details and providing a controlled interface
for interacting with the object.
 Encapsulation helps in achieving data security, as access to the object's data can be restricted to
only the necessary methods.

Inheritance:
 Inheritance allows a new class (subclass or derived class) to inherit properties and methods from
an existing class (superclass or base class).
 This promotes code reuse and establishes a hierarchical relationship between classes. Subclasses
can extend or modify the behavior of the superclass, leading to more modular and extensible code.

Polymorphism:
 Polymorphism refers to the ability of objects to take on different forms or behaviors based on the
context in which they are used.
 There are two types of polymorphism: compile-time polymorphism (method overloading) and
runtime polymorphism (method overriding).
 Polymorphism enables code flexibility and extensibility by allowing objects of different classes
to be treated uniformly through a common interface.

Abstraction:
 Abstraction involves focusing on essential properties and behaviors while hiding unnecessary
implementation details.
 It allows developers to create models that represent real-world entities in a simplified manner.
Abstraction helps in managing complexity by providing a clear and concise interface for
interacting with objects, thereby enhancing code readability and maintainability.

4. Explain advantages and disadvantages of Object Oriented Programming.


Answer:
The advantages and Disadvantages of Object Oriented Programming Language are as follows:

Advantages:
 Modularity: OOP promotes modularity by breaking down complex systems into smaller,

PIET -DS(CE) PAGE NO:6


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

manageable modules (objects). This makes it easier to understand, maintain, and update the
codebase, as changes made to one part of the system are less likely to affect other parts.
 Reusability: OOP encourages code reuse through inheritance and composition. Objects and
classes can be reused in different parts of the program or even in entirely different programs,
reducing redundancy and promoting code efficiency.
 Scalability: OOP supports scalability by allowing developers to extend existing classes to create
new ones with additional features or behaviors. This facilitates building upon existing code rather
than starting from scratch, making it easier to accommodate changes and add new functionality
as the project grows.
 Maintainability: OOP promotes code maintainability through encapsulation, inheritance, and
abstraction. Encapsulation hides internal implementation details, inheritance facilitates code
reuse, and abstraction focuses on essential properties and behaviors, making it easier to
understand and modify the code over time.
 Flexibility and Extensibility: OOP enables code flexibility and extensibility through
polymorphism. Polymorphism allows objects of different classes to be treated uniformly through
a common interface, enabling developers to write more flexible and adaptable code that can
accommodate changes and variations in requirements.

Disadvantages:
 Complexity: OOP can introduce complexity, especially for beginners or when used
inappropriately. Understanding the relationships between classes, managing inheritance
hierarchies, and designing effective class structures require careful planning and can be
challenging in large-scale projects.
 Overhead: OOP can introduce overhead in terms of memory and processing resources. Objects
and classes consume memory, and dynamic dispatch mechanisms used for method calls can incur
performance overhead compared to procedural programming approaches.
 Learning Curve: OOP has a steep learning curve for beginners due to its abstract concepts and
terminology. Understanding concepts such as inheritance, polymorphism, and object
relationships requires time and practice, making it challenging for newcomers to grasp initially.
 Performance: In certain scenarios, OOP may not be the most efficient choice in terms of
performance. Dynamic dispatch mechanisms, such as virtual function calls in languages like C++,
can incur runtime overhead, impacting performance in performance-critical applications.
 Design Overhead: Designing effective class structures and object relationships requires careful
planning and foresight. Poorly designed class hierarchies or overly complex inheritance structures
can lead to code that is difficult to understand, maintain, and extend over time.

5. Explain structure of C++ with example.


Answer:
The structure of C++ program contains below sections:
 Documentation section
 Link section
 Definition section
 Global declaration section
 Function definition section
 Main function

PIET -DS(CE) PAGE NO:7


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

Documentation Section:
 This section comes first and is used to document the logic of the program that the programmer
going to code.
 It can be also used to write for purpose of the program.
 Whatever written in the documentation section is the comment and is not compiled by the
compiler.

Linking Section:
The linking section contains two parts:
1.Header Files:
 Generally, a program includes various programming elements like built-in functions, classes,
keywords, constants, operators, etc. that are already defined in the standard C++ library.
 In order to use such pre-defined elements in a program, an appropriate header must be
included in the program.
 Standard headers are specified in a program through the preprocessor directive #include. In
Figure, the iostream.h header is used. When the compiler processes the instruction
#include<iostream.h>, it includes the contents of the stream in the program. This enables the
programmer to use standard input, output, and error facilities that are provided only through
the standard streams defined in <iostream.h>. These standard streams process data as a stream
of characters, that is, data is read and displayed in a continuous flow. The standard streams
defined in <iostream.h> are listed here.

#include<iostream.h>

2.Namespaces:
 A namespace permits grouping of various entities like classes, objects, functions, and various
C++ tokens, etc. under a single name.
 Any user can create separate namespaces of its own and can use them in any other program.
 In the below snippets, namespace std contains declarations for cout, cin, endl, etc. statements.
 Namespaces can be accessed in multiple ways:

using std :: cout;

Definition Section:
 It is used to declare some constants and assign them some value.
 In this section, anyone can define your own datatype using primitive data types.
 It uses #define keyword to declare constants in C++

Global Declaration Section:


 The variables and the class definitions which are going to be used in the program are declared
to make them global.
 The scope of the variable declared in this section lasts until the entire program terminates.
 These variables are accessible within the user-defined functions also.

Function Declaration Section:


 It contains all the functions which our main functions need.
 Usually, this section contains the User-defined functions.
 This part of the program can be written after the main function but for this, write the function

PIET -DS(CE) PAGE NO:8


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

prototype in this section for the function which for you are going to write code after the main
function.

Main Function:
 The main function tells the compiler where to start the execution of the program. The
execution of the program starts with the main function.
 All the statements that are to be executed are written in the main function.
 The compiler executes all the instructions which are written in the curly braces {} which
encloses the body of the main function.
 Once all instructions from the main function are executed, control comes out of the main
function and the program terminates and no further execution occur.

// Preprocessor directives
#include <iostream.h> // Include the standard input/output stream library

// Global declarations
// Use the standard namespace

//Global declaration section


// Function declaration (prototype)
void greet();

// Main function
int main() {
// Statements
cout << "Hello, world!" << endl;

// Function call
greet();

return 0; // Return statement


}

// Function definition
void greet() {
// Function body
cout << "Greetings from the greet() function!" << endl;
}

PIET -DS(CE) PAGE NO:9


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

6. Describe all datatypes used in C++.


Answer:
DATA
TYPES

User
Primitive Derived
defined

Integer Function Class

Character Array Structure

Boolean Pointer Union

Floating Point Reference Enum

Double Floating
Typedef
Point

Void

Wide character

1.Primitive datatype
integer (int)
 In order to identify integers, the int keyword is utilized.
 Usually, it is 4 bytes in size.
 It can therefore store values between -2147483648 and 2147483647.
 Example:-int = 344

Character (char)
 Characters are referred to by the term char.
 It has a 1 byte size.
 In C++, characters are encased in single quotes.
 Example:- ‘m’

Boolean (bool)
 True or false are the only two valid values for the bool data type.

 Loops and conditional statements both employ booleans (which we will learn in later chapters).
 Example:-bool = ‘true’;

Floating Point (float)


 Floating-point numbers are stored in the float and double formats (decimals and exponentials).

PIET -DS(CE) PAGE NO:10


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

 Floats are 4 bytes in size, while doubles are 8 bytes.


 Example:-float = 12.7, 79.06

Double
 To store floating-point integers with double precision, use the keyword double (including
decimals and exponentials).
 The double variable takes up 8 bytes.
 Example:-double = 5556.78;

Void
 It is argued that anything has no worth if it is empty.
 The void data type represents a valueless entity.
 The declaration of variables is not permitted for the void type.
 It just uses functions and doesn’t return any data.
 Example:-void function(void);

Wide Character (wchar)


 Similar to the char data type, the wide character wchar t has a size of two bytes as opposed to
one.
 It is used to represent characters that need more memory than a single char to represent them.
 Example:-wchar =L’p’

2.Derived datatype
Function
 A function is a reusable block of code that performs a specific task. It is a derived data type
because you can define functions to work with other data types and can even return values of
different data types.
Arrays:
 A collection of elements of the same data type arranged in contiguous memory locations.
Arrays are declared using square brackets [], e.g., int numbers[5];.
Pointers:
 Variables that store memory addresses of other variables. Pointers are declared using an
asterisk *, e.g., int* ptr;.
References:
 Alias to an existing variable. References are declared using an ampersand &, e.g., int a = 10;
int& ref = a;.

3.User Defined Datatype


Classes:
 Similar to structures but with additional features such as member functions and access
specifiers. Classes are declared using the class keyword.

Structures:
 A composite data type that groups together variables of different data types under a single
name. Structs are declared using the struct keyword.

Union:
 A union is a user-defined data type that allows you to store different data types in the same

PIET -DS(CE) PAGE NO:11


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

memory location. Unlike structures, which allocate memory for all members, unions share
memory among their members.

Enumeration Types:
 Enumerations (enum): A user-defined data type used to define named constants. Enumerations
are declared using the enum keyword.

Typedef:
 typedef is a keyword that allows you to create aliases for existing data types, making your code
more readable and providing abstraction. It's not a new data type but a way to create alternative
names for existing ones.

7. How we can declare variable in C++?Explain with an example.


Answer:
 A variable provides us with named storage that our programs can manipulate. Each variable in
C++ has a specific type, which determines the size and layout of the variable's memory; the range
of values that can be stored within that memory; and the set of operations that can be applied to
the variable.
 The name of a variable can be composed of letters, digits, and the underscore character.
 It must begin with either a letter or an underscore.
 Upper and lowercase letters are distinct because C++ is case-sensitive.

Variable Definition in C++


 A variable definition tells the compiler where and how much storage to create for the variable.
 A variable definition specifies a data type, and contains a list of one or more variables of that
type as follows −

datatype variable_name;
Here, datatype must be a valid C++ data type including char, w_char, int, float, double, bool or any
user-defined object, etc., and variable_list may consist of one or more identifier names separated by
commas. Some valid declarations are shown here.

int i;
float a=3.72;

8. Describe dynamic initialization of variable in C++.


Answer:
Dynamic initialization of variables in C++ refers to initializing variables at runtime rather than at
compile time. This allows the value of the variable to be determined based on conditions or user input
during program execution. There are several ways to achieve dynamic initialization in C++,
including:

1.User Input: You can prompt the user to enter a value, which is then assigned to the variable. This
is commonly done using input/output stream functions like std::cin.

PIET -DS(CE) PAGE NO:12


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

Example:
#include <iostream.h>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
std::cout << "You entered: " << number << std::endl;
return 0;
}

2.Function Calls:
We can initialize variables using values returned by functions. This allows for more complex
initialization logic to be encapsulated within functions.

Example:
#include <iostream.h>
int getUserInput() {
int input;
std::cout << "Enter a number: ";
std::cin >> input;
return input;
}
int main() {
int number = getUserInput();
std::cout << "You entered: " << number << std::endl;
return 0;
}

3.Initialization with Expressions:


We can initialize variables using expressions that are evaluated at runtime. This allows for dynamic
computation of initial values.

Example:
#include <iostream.h>
int main() {
int x = 5;
int y = x * 2; // Dynamic initialization based on expression
cout << "Value of y: " << y << endl;
return 0;
}

4.Conditional Initialization:
We can initialize variables conditionally based on certain criteria or conditions.

Example:
#include <iostream.h>

PIET -DS(CE) PAGE NO:13


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

int main() {
int x;
bool condition = true;
if (condition) {
x = 10;
} else {
x = 20;
}
cout << "Value of x: " << x << endl;
return 0;
}

Dynamic initialization allows for greater flexibility and adaptability in C++ programs, enabling
variables to be initialized based on runtime conditions or user input. This can be useful in scenarios
where the initial value of a variable is not known until the program is executed.

9. Explain reference variable in C++.


Answer:
 In C++, a reference variable is an alias or an alternative name for an existing variable.
 Once a reference variable is initialized with a variable, it becomes another name for that
variable, and any changes made through the reference variable affect the original variable.
 References provide a way to access the same memory location using different identifiers.

Here's how you declare and use reference variables in C++:

Example::
#include <iostream.h>
int main() {
int originalVariable = 62;
// Declaration of reference variable
int& referenceVariable = originalVariable;
cout << "Original variable value: " << originalVariable << std::endl;
cout << "Reference variable value: " << referenceVariable << std::endl;

// Modifying the value using the reference variable


referenceVariable = 100;
cout << "Original variable value after modification: " << originalVariable << endl;
return 0;
}

Output:

PIET -DS(CE) PAGE NO:14


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

Key points about reference variables:


 Reference variables must be initialized when declared, and they cannot be changed to refer to
another variable once initialized.
 References cannot be NULL, meaning they must always refer to a valid object.
 References are often used as function parameters to pass variables by reference, enabling
functions to modify the original variables directly.
 Unlike pointers, references cannot be reseated or made to refer to a different object once
initialized. They provide a safer alternative to pointers for some use cases, as they cannot be
null or accidentally dereferenced to access invalid memory locations.

10.Explain scope resolution operator.


Answer:
 The scope resolution operator ( :: ) is used for several reasons. For example: If the global
variable name is same as local variable name, the scope resolution operator will be used to
call the global variable.
 It is also used to define a function outside the class and used to access the static variables of
class.
 Here an example of scope resolution operator in C++ language,

Example
#include <iostream.h>
char a = 'm';
static int b = 50;

int main() {
char a = 's';
cout << "The static variable : "<< ::b;
cout << "\nThe local variable : " << a;
cout << "\nThe global variable : " << ::a;
return 0;
}

Output:

PIET -DS(CE) PAGE NO:15


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

11.Differentiate OOP & POP.


Answer:
Procedure Oriented Programming Object-Oriented Programming
In POP, the program is divided into small In OOP, the program is divided into parts
parts called functions. called objects.
In POP, functions and the order of Because it works in the actual world, data
operations to be performed take takes priority over procedures and
precedence over data. functions in OOP.
POP follows the Top-Down approach. OOP follows the Bottom-Up approach.
POP does not have any access specifier. OOP has access specifiers named Public,
Private, Protected, etc.
In POP, Data can move freely from In OOP, objects can move and
function to function in the system. communicate with each other through
member functions.
To add new data and functions in POP is OOP provides an easy way to add new
not so easy. data and functions.
Most functions in POP employ global Data in OOP cannot simply flow from one
data for sharing, which can be accessed function to function; it can be kept public
freely from one function to the next. or private, allowing us to regulate data
access.
POP does not have any proper way for OOP provides Data Hiding so provides
hiding data so it is less secure. more security.
In POP, Overloading is not possible. In OOP, Overloading is possible in the
form of Operator Overloading and
Function Overloading.
Examples of POP are C, VB, Examples of OOP are C++, JAVA,
FORTRAN, Pascal. VB.NET, C#.NET.

12.What is the meaning of access specifier?


Answer:
Access specifiers in C++ are used to define the level of access that a class member variable or function
can have.
In C++, there are three access specifiers: public, private, and protected.

Public:
 The public access specifier is used to specify that a class member can be accessed from
anywhere, both inside and outside the class.
 This means that any function or object can access the public members of the class.
 The public members of a class are typically used to represent the interface of the class.

Private:
 The private access specifier is used to specify that a class member can only be accessed from

PIET -DS(CE) PAGE NO:16


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

within the class.


 This means that any function or object outside the class cannot access the private members of
the class.
 The private members of a class are typically used to represent the implementation of the class
and are hidden from the outside world.

Protected:
 The protected access specifier is used to specify that a class member can be accessed from
within the class and its derived classes.
 This means that any function or object outside the class hierarchy cannot access the protected
members of the class.
 The protected members of a class are typically used to represent the implementation of a class
that should be accessible to its derived classes.

PIET -DS(CE) PAGE NO:17


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

UNIT-2
FUNCTIONS, CLASS AND OBJECTS

1. Define function with function prototype, function declaration &amp; function


calling.
Answer:
 A function is a block of code that performs some operation. A function can optionally define input
parameters that enable callers to pass arguments into the function. A function can optionally return
a value as output.
 A function prototype provides the compiler with a description of a function that will be defined
and used at a later point in the program. It should be before the first call of the function. The
prototype includes a return type indicating the type of variable that the function will return. It also
includes the function name, which should describe what the function does.

 A function declaration tells the compiler about a function name and how to call the function. The
actual body of the function can be defined separately.
 Syntax :
return_type function_name( parameter list );
 Example:
int sum(int, int );

 Calling or invoking the function locates the function in the memory, furnishing it with arguments
and causing it to execute. When a function is called then the control passed to the function where
it is actually defined.
 Syntax :
variable= function_name(arg1,arg2,…,argn);
 Example:
result= sum(num1, num2);

2. Define an inline function & Explain How to implement an inline function with
example.
Answer:
 An inline function is a function that is expanded in line when it is called. When the inline function
is called whole code of the inline function gets inserted or substituted at the point of the inline
function call.
 This substitution is performed by the C++ compiler at compile time. An inline function may
increase efficiency if it is small.
 Syntax :
inline return-type function-name(parameters)
{
// function code
}
 If a function member is defined entirely in the class specification body (typically in .h header file)
then, it is considered as an in-line function.

PIET -DS(CE) PAGE NO:18


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

Example::
#include <iostream.h>
inline int cube(int s)
{
return s * s * s;
}
int main()
{
cout << "The cube of 2 is: " << cube(2) << "\n";
return 0;
}

Output:

3. Explain default and constant arguments with example.


Answer:
Default argument:
 A default argument is a value provided in a function declaration that is automatically assigned by
the compiler if the calling function doesn’t provide a value for the argument.
 In case any value is passed, the default value is overridden.
 A default argument is a value in the function declaration automatically assigned by the compiler
if the calling function does not pass any value to that argument.

Example::
#include<iostream.h>
int sum(int x, int y, int z=0, int w=0)
{
return (x + y + z + w);
}
int main()
{
cout << sum(10, 20)<<"\n";
cout << sum(10, 20,30)<<"\n";
cout << sum(10, 20,30, 50)<<"\n";
return 0;
}

Output:

PIET -DS(CE) PAGE NO:19


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

Constant arguments:
 The constant argument turns out to be most useful when the calling of the functions takes place
by reference.
 A constant argument is the one whose modification cannot take place by the function.
Furthermore, in order to make an argument constant to a function, the use of a keyword const can
take place like- int sum (const int a, const int b).

Example::
#include<iostream.h>

// Function that takes constant arguments


void printValues(const int x, const double y)
{
cout << "x: " << x << ", y: " << y;
// Attempting to modify x or y will result in a compilation error
// x = 10; // Error: assignment of read-only parameter 'x'
// y = 20.5; // Error: assignment of read-only parameter 'y'
}

int main()
{
int a = 5;
double b = 10.5;
// Call the function with constant arguments
printValues(a, b);
return 0;
}

Output:

4. Explain Function Overloading with example.


Answer:
 Function overloading is a feature of object-oriented programming where two or more functions
can have the same name but different parameters.
 When a function name is overloaded with different jobs it is called Function Overloading.
 In Function Overloading “Function” name should be the same and the arguments should be
different.
 In function overloading, the function is redefined by using either different types of arguments or
a different number of arguments.
 It is only through these differences compiler can differentiate between the functions.
 The advantage of Function overloading is that it increases the readability of the program because
you don't need to use different names for the same action.

PIET -DS(CE) PAGE NO:20


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

Example:
#include<iostream.h>
// Function to add two integers
int add(int a, int b)
{
return a + b;
}

// Function to add three integers


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

// Function to add two doubles


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

int main() {
// Call the overloaded functions
cout << "Sum of 2 and 3: " << add(2, 3) << endl;
cout << "Sum of 2, 3, and 4: " << add(2, 3, 4) << endl;
cout << "Sum of 2.5 and 3.7: " << add(2.5, 3.7) << endl;
return 0;
}

Output:

5. Define class & object.


Answer:
Class:
 Class is a group of similar objects. It is a template from which objects are created. It can have
fields, methods, constructors etc.
 A class is used to specify the form of an object and it combines data representation and methods
for manipulating that data into one neat package. The data and functions within a class are called
members of the class.
 Syntax :
class className
{
// some data
// some functions

PIET -DS(CE) PAGE NO:21


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

};
 Example:
class Room
{
public:
double length;
double breadth;
double height;
double calculateArea()
{
return length * breadth;
}
double calculateVolume()
{
return length * breadth * height;
}
};

Object:
 An object is a single instance of a class.When a class is defined, only the specification for the
object is defined; no memory or storage is allocated.
 To use the data and access functions defined in the class, we need to create objects.
 Syntax :
className objectVariableName;
 Ex:
void sampleFunction()
{
Room room1, room2;
}
int main()
{
Room room3, room4;
}

6. Define Member Function & Nesting of Member Function.


Answer:
Member function:
 A member function of a class is a function that has its definition or its prototype within the class
definition like any other variable.
 It operates on any object of the class of which it is a member, and has access to all the members
of a class for that object.

Nesting of member function:


 A member function called into another member function is referred to as nesting of member
functions.

PIET -DS(CE) PAGE NO:22


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

Example:
#include <iostream.h>
class average
{
int a,b;
public:
void read();
void print();
int avg();
};
void average::read()
{
cout<<"\n enter a and b: ";
cin>>a>>b;
}
void average::print()
{
cout<<"value of a: "<<a;
cout <<"\nvalue of b: "<<b;
cout<<"\naverage is : "<<avg();
}
int average::avg()
{
return (a+b)/2; }
main() {
average A;
A.read();
A.print(); }

Output:

7. Define Private Member Function.


Answer:
 A function declared inside the class's private section is known as "private member function".
 A private member function is accessible through the only public member function.
 The private member function is protection of data wherever necessary, it is for the data protection.
 Unlike public functions the restricted access ensure that only required members can access the
data, which may happen with nested functions.

PIET -DS(CE) PAGE NO:23


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

8. What is Friend Function? Explain with example.


Answer:
 If a function is defined as a friend function in C++, then the protected and private data of a class
can be accessed using the function.
 By using the keyword friend compiler knows the given function is a friend function.
 For accessing the data, the declaration of a friend function should be done inside the body of a
class starting with the keyword friend.
 Syntax:
class class_name
{
friend data_type function_name(argument/s);
};

Example:
#include <iostream.h.h>
class Box
{
private:
int length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function
};
int printLength(Box b)
{
b.length += 10;
return b.length; }
int main()
{
Box b;
cout <<"Length of box: "<< printLength(b)<<std::endl;
return 0;
}

Output:

9. WAP using friend function to find maximum number between two numbers,
two numbers are the private data of two different class.
Answer:
Example:
#include <iostream.h>
// Forward declaration of second class
class SecondClass;

PIET -DS(CE) PAGE NO:24


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

// First class declaration


class FirstClass {
private:
int num1;
public:
FirstClass(int n) : num1(n) {}

// Declare friend function


friend int findMax(const FirstClass&, const SecondClass&);
};

// Second class declaration


class SecondClass {
private:
int num2;
public:
SecondClass(int n) : num2(n) {}
// Declare friend function
friend int findMax(const FirstClass&, const SecondClass&);
};

// Friend function definition


int findMax(const FirstClass& first, const SecondClass& second) {
return (first.num1 > second.num2) ? first.num1 : second.num2;
}

int main() {
FirstClass first(10);
SecondClass second(20);
cout << "Maximum number is: " << findMax(first, second) << std::endl;
return 0;
}

Output:

10.WAP which illustrate the use of object and class concept using to show
student’s detail as output.
Answer:
#include <iostream.h>
PIET -DS(CE) PAGE NO:25
OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

#include <conio.h>

class student
{
private:
char name[30];
int rollNo;
int total;
float perc;

public:
//member function to get student's details
void getDetails(void);
//member function to print student's details
void putDetails(void);
};

//member function definition, outside of the class


void student::getDetails(void)
{
cout << "Enter name: ";
cin >> name;
cout << "Enter roll number: ";
cin >> rollNo;
cout << "Enter total marks outof 500: ";
cin >> total;
perc = (float)total / 500 * 100;
}

//member function definition, outside of the class


void student::putDetails(void)
{
cout << "Student details:\n";
cout << "Name:" << name << ",Roll Number:" << rollNo << ",Total:" << total << ",Percentage:"
<< perc;
}

int main()
{
student std; //object creation
std.getDetails();
std.putDetails();
return 0;
}

PIET -DS(CE) PAGE NO:26


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

Output:

PIET -DS(CE) PAGE NO:27


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

UNIT-3
CONSTRUCTOR AND DESTRUCTOR

1. What is constructor? Explain in brief with example.


Answer:
 In C++, constructor is a special method which is invoked automatically at the time of object
creation.
 The constructor in C++ has the same name as class or structure.
 In brief, A particular procedure called a constructor is called automatically when an object is
created in C++.
 In general, it is employed to create the data members of new things.
 In C++, the class or structure name also serves as the constructor’s name.
 When an object is completed, the constructor is called.
 It has three types:
1. copy constructor
2. parameterized constructor
3. default constructor

Example:
#include <iostream.h>

class Person {
string name;
int age;
public:
// Constructor
Person(string n, int a) {
name = n;
age = a;
}
void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main() {
Person person1("abc ", 30);
person1.display();
return 0;
}

Output:

PIET -DS(CE) PAGE NO:28


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

2. Explain default constructor with program.


Answer:
A constructor which has no argument is known as default constructor. It is invoked at the time of
creating object.

Example:
#include <iostream.h>

class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}

Output:

3. How to use a copy constructor? Justify with program.


Answer:
 A copy constructor is a member function that initializes an object using another object of the same
class.
 In simple terms, a constructor which creates an object by initializing it with an object of the same
class, which has been created previously is known as a copy constructor.
 Copy constructor is used to initialize the members of a newly created object by copying the
members of an already existing object.

Example:
#include <iostream.h>
#include<conio.h>

class A
{
public:
int x;

PIET -DS(CE) PAGE NO:29


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

A(int a)// parameterized constructor.


{
x=a;
}
A(A & i)// copy constructor
{
x = i.x;
}
};
int main()
{
A a1(20);// Calling the parameterized constructor.
A a2(a1);// Calling the copy constructor.
cout<<a2.x;
return 0;
}

Output:

4. Explain parameterized constructor with example.


Answer:
 A constructor which has parameters is called parameterized constructor.
 It is used to provide different values to distinct objects.

Example:
#include <iostream.h>
#include<conio.h>
class Employee
{
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};

PIET -DS(CE) PAGE NO:30


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

int main(void) {
Employee e1 =Employee(101, "Meera", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}

Output:

5. Differentiate Constructor & Destructor.


Answer:
Constructor Destructor
Constructor helps to initialize the object of Whereas destructor is used to destroy the
a class. instances.
It is declared as className( arguments if Whereas it is declared as ~ className( no
any ){Constructor’s Body }. arguments ){ }.
Constructor can either accept arguments or While it can’t have any arguments.
not.
A constructor is called when an instance or It is called while object of the class is freed
object of a class is created. or deleted.
Constructor is used to allocate the memory While it is used to deallocate the memory of
to an instance or object. an object of a class.
Constructor can be overloaded. While it can’t be overloaded.
The constructor’s name is same as the class Here, its name is also same as the class name
name. preceded by the tiled (~) operator.
In a class, there can be multiple While in a class, there is always a single
constructors. destructor.
There is a concept of copy constructor While here, there is no copy destructor
which is used to initialize an object from concept.
another object.
They are often called in successive order. They are often called in reverse order of
constructor.

6. What is Destructor? Give example.


Answer:
 A destructor works opposite to constructor; it destructs the objects of classes. It can be defined
only once in a class. Like constructors, it is invoked automatically.
 A destructor is defined like constructor. It must have same name as class. But it is prefixed
with a tilde sign (~).

PIET -DS(CE) PAGE NO:31


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

Example:
#include<iostream.h>
#include<conio.h>
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}

Output:

7. Write a C++ Program to enter student details by Passing parameters to


constructors.
Answer:
Example:
#include <iostream.h>
//#include<conio.h>
class Student {
public:
int id;
string name;//data member(also instance variable)
float salary;
Student(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()

PIET -DS(CE) PAGE NO:32


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void)
{
Student e1 =Student(101, "Sonoo", 890000); //creating an object of Employee
Student e2=Student(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}

Output:

8. Write a C++ program to perform operator overloading using constructor.


Answer:
Example:
#include<iostream.h>
#include<conio.h>

class Arithmetic {
private:
int value;

public:
// Constructor
Arithmetic(int val = 0) {
value = val;
}

// Overloading addition operator '+'


Arithmetic operator+(const Arithmetic &obj) {
Arithmetic temp;
temp.value = value + obj.value;
return temp;
}

// Overloading subtraction operator '-'


Arithmetic operator-(const Arithmetic &obj) {
Arithmetic temp;
temp.value = value - obj.value;
return temp;
}

PIET -DS(CE) PAGE NO:33


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

// Overloading multiplication operator '*'


Arithmetic operator*(const Arithmetic &obj) {
Arithmetic temp;
temp.value = value * obj.value;
return temp;
}

// Overloading division operator '/'


Arithmetic operator/(const Arithmetic &obj) {
if (obj.value != 0) {
Arithmetic temp;
temp.value = value / obj.value;
return temp;
} else {
cout << "Error: Division by zero!" << endl;
return Arithmetic();
}
}

// Function to display value


void display() {
cout << "Value: " << value << endl;
}
};

int main() {
Arithmetic a(10);
Arithmetic b(5);

// Addition
Arithmetic addition = a + b;
cout << "Addition: ";
addition.display();

// Subtraction
Arithmetic subtraction = a - b;
cout << "Subtraction: ";
subtraction.display();

// Multiplication
Arithmetic multiplication = a * b;
cout << "Multiplication: ";
multiplication.display();

// Division
Arithmetic division = a / b;
cout << "Division: ";

PIET -DS(CE) PAGE NO:34


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

division.display();

return 0;
}

Output:

PIET -DS(CE) PAGE NO:35


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

UNIT-4
INHERITANCE

1. Explain Inheritance in C++ and also list out its types.


Answer:
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class
(derived class or subclass) to inherit properties and behaviors from an existing class (base class or
superclass).

Inheritance promotes code reuse, extensibility, and modularity by allowing the derived class to inherit
and extend the functionality of the base class.

Here's how inheritance works in C++:


 Base Class (Superclass): The base class is the existing class from which other classes derive.
It defines the common properties and behaviors shared by the derived classes. The base class
serves as a blueprint for creating new classes.

 Derived Class (Subclass): The derived class is the new class that inherits properties and
behaviors from the base class. It extends or modifies the functionality of the base class by
adding new members or overriding existing ones.

Syntax for Inheritance:


In C++, inheritance is declared using the class keyword followed by the name of the derived class, a
colon :, and the access specifier (public, protected, or private) followed by the name of the base class.

Example:
class BaseClass {
// Base class members
};

class DerivedClass : access-specifier BaseClass {


// Derived class members
};
PIET -DS(CE) PAGE NO:36
OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

C++ supports five types of inheritance:


 Single inheritance
 Multiple inheritance
 Hierarchical inheritance
 Multilevel inheritance
 Hybrid inheritance

2. What are derived classes in C++?


Answer:
In C++, a derived class is a class that inherits properties and behaviors from another class, known as
the base class or superclass. The derived class extends or specializes the functionality of the base
class by adding new members or overriding existing ones. Derived classes provide a way to reuse
code and promote modularity and extensibility in object-oriented programming.

Syntax:
class BaseClass
{
// Base class members
};

class DerivedClass : access-specifier BaseClass


{
// Derived class members
};

Code:
#include <iostream.h>
#include<conio.h>

// Declare Base Class


class Base
{
public:
int a;
};

// Declare Derived Class


class Derived : public Base
{
public:
int b;
};

PIET -DS(CE) PAGE NO:37


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

// Driver Code
int main()
{
// Initialise a Derived class geeks
Derived cpp;

// Assign value to Derived class variable


cpp.b = 3;

// Assign value to Base class variable


// via derived class
cpp.a = 4;
cout << "Value from derived class: "<< cpp.b << endl;
cout << "Value from base class: "<< cpp.a << endl;
return 0;
}

Output:

3. Explain Single Inheritance with an example.


Answer:
Single inheritance is a type of inheritance in object-oriented programming where a derived class
inherits properties and behaviors from only one base class. This means that a derived class extends
the functionality of a single base class.

Example:
#include <iostream.h>

class Base {
public:
void display() {
cout <<"This is the Base class" << endl;

PIET -DS(CE) PAGE NO:38


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

}
};

class Derived : public Base {


public:
void show() {
cout << "This is the Derived class" << endl;
}
};

int main() {
Derived d;
d.display(); // Accessing Base class function
d.show(); // Accessing Derived class function
return 0;
}

Output:

4. What is Multiple Inheritance? Explain it with an example.


Answer:
Multiple inheritance is a feature in object-oriented programming where a derived class inherits
properties and behaviors from multiple base classes. In other words, a derived class can have more
than one direct base class, allowing it to combine features from multiple parent classes.

Syntax:
class A
{
... .. ...
};
class B
{
... .. ...
};

PIET -DS(CE) PAGE NO:39


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

class C: public A,public B


{
... ... ...
};

Example:
#include<iostream.h>
#include<conio.h>

// create a base class1


class Base_class
{
// access specifier
public:
// It is a member function
void display()
{
cout << " It is the first function of the Base class " << endl;
}
};

// create a base class2


class Base_class2
{
// access specifier
public:
// It is a member function
void display2()
{
cout << " It is the second function of the Base class " << endl;
}
};

/* create a child_class to inherit features of Base_class and Base_class2 with access specifier. */
class child_class: public Base_class, public Base_class2
{

// access specifier
public:
void display3() // It is a member function of derive class
{
cout << " It is the function of the derived class " << endl;
}

};
PIET -DS(CE) PAGE NO:40
OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

int main ()
{
// create an object for derived class
child_class cc;
cc.display(); // call member function of Base_class1
cc.display2(); // call member function of Base_class2
cc.display3(); // call member function of child_class
}

Output:

5. What is Multilevel Inheritance? Explain it with an example.


Answer:
Multilevel inheritance is a type of inheritance in object-oriented programming where a derived class
serves as the base class for another derived class. This creates a chain of inheritance, with each
derived class inheriting properties and behaviors from its immediate superclass, as well as from all
its ancestor classes up the inheritance hierarchy.

Syntax:
class A // base class
{
...........
};
class B : access_specifier A // derived class
{
...........
};
class C : access_specifier B // derived from derived class B
{

PIET -DS(CE) PAGE NO:41


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

...........
};

Example:
#include<iostream.h>
#include<conio.h>

class Grandfather
{
public:
void Print1()
{
cout<<"Process of Grandfather Class.\n";
}
};
class Father: public Grandfather
{
public:
void Print2()
{
cout<<"Process of Father Class.\n";
}
};
class Son: public Father
{
public:
void Print3()
{
cout<<"Process of Son Class.\n";
}
};
int main()
{
Son obj;
obj.Print1();
obj.Print2();
obj.Print3();
return 0;
}

Output:

PIET -DS(CE) PAGE NO:42


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

6. What is Hybrid Inheritance? Explain it with an example.


Answer:
Hybrid inheritance, also known as virtual inheritance, is a combination of multiple and multilevel
inheritance. It allows a derived class to inherit from multiple base classes, while also preventing the
problems associated with multiple inheritance, such as the diamond problem.

In hybrid inheritance, one or more base classes are inherited virtually, which means that only one
instance of the virtual base class is created in the derived class hierarchy, ensuring that there are no
duplicate instances of the virtual base class.

Syntax:
Class A
{
statement(s)
}:
Class B: public A
{
statement(s);
};
Class C
{
statement(s);
};
Class D: public B, public C
{
statement(s);
};

Example:
#include<iostream.h>
#include<conio.h>

class A
{
public:
int a;

PIET -DS(CE) PAGE NO:43


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

};

class B : public A // single inheritance


{
public:
B()
{
a = 36; //initialise a
}
};

class C
{
public:
int c;
C()
{
c = 14; //initialise c
}
};

class D : public B, public C //Multiple inheritance


{
public:
void sum()
{
cout << "Sum = " << a + c;
}
};

int main()
{
D obj1;
obj1.sum();
}

Output:

PIET -DS(CE) PAGE NO:44


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

7. What is Function Overriding in C++?Explain it with example.


Answer:
Function overriding is a feature in C++ that allows a derived class to provide a new implementation
for a method that is already defined in its base class. When a method in the derived class has the same
name, return type, and parameters as a method in its base class, it overrides the base class method.

Example:
#include <iostream>
using namespace std;

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

class B:public A
{
public:
void display()
{
cout<<"Derived Class";
}
};

int main()
{
B obj;
obj.display();
return 0;
}

Output:

Function overriding is particularly useful for implementing polymorphism, where objects of different
classes can be treated as objects of the same base class type, allowing for dynamic method dispatch
at runtime based on the actual type of the object.

PIET -DS(CE) PAGE NO:45


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

8. Differentiate between Function Overloading and Function Overriding.


Answer:
Function Overloading Function Overriding
In function overloading, two or more Function overriding permit us to redefine a
functions can own the same name, but the method with the same name and signature
parameters will be different.
There is no requirement of the inheritance In function overriding, we need an
concept here. inheritance concept.
In the case of function overloading, the In the case of function overriding, the
signatures should be different. signatures should be the same.
We can use it as an example of compile time We can use it as an example of run time
polymorphism. polymorphism.
It happens during compile time. It occurs during the run time.
A function has the ability to load multiple A function can be overridden only a single
times. time.

9. What is a Virtual Base Class? Explain it with an example.


Answer:
A virtual base class is a class that is intended to be inherited virtually by multiple derived classes.
When a base class is declared as virtual, it ensures that only one instance of the base class is shared
among all the derived classes, even if they are multiple levels deep in the inheritance hierarchy. This
helps to prevent the diamond problem, where ambiguity arises due to multiple inheritance paths
leading to the same base class.

Example:
#include<iostream.h>
#include<conio.h>
class B {
public: int b;
};

class D1 : virtual public B


{
public: int d1;
};

class D2 : virtual public B


{
public: int d2;
};

class D3 : public D1, public D2


{

PIET -DS(CE) PAGE NO:46


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

public: int d3;


};

int main()
{
D3 obj;

obj.b = 40; // statement 3


obj.b = 30; // statement 4
// D3 have only one copy of B and statement 4 will overwrite the value of b, given in statement 3
obj.d1 = 60;
obj.d2 = 70;
obj.d3 = 80;

cout<< "\n B : "<< obj.b;


cout<< "\n D1 : "<< obj.d1;
cout<< "\n D2 : "<< obj.d2;
cout<< "\n D3 : "<< obj.d3;
}

Output:

10.Explain Abstract Classes in C++.


Answer:
An abstract class in C++ is a class that cannot be instantiated on its own because it contains at least
one pure virtual function. A pure virtual function is a virtual function that is declared in the base class
but has no implementation. Instead, it is intended to be overridden in derived classes. Abstract classes
are designed to serve as base classes providing an interface for derived classes to implement.

Example:
#include <iostream.h>
#include<conio.h>

class base_class
{
public:
virtual void display() = 0;
};

PIET -DS(CE) PAGE NO:47


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

class derived_class : public base_class


{
public:
void display()
{
cout<<"This is simple illustration of abstract class and pure virtual function";
}
};

int main()
{
derived_class obj;
obj.display();
return 0;
}

Output:

PIET -DS(CE) PAGE NO:48


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

UNIT-5
POINTERS & VIRTUAL FUNCTIONS

1. Explain Pointers to Objects in C++.


Answer:
 In C++, a pointer to an object is a variable that holds the memory address of an object in
computer memory.
 This pointer can be used to access the object's properties and methods, or to pass the object
as a parameter to other functions.
 To create a pointer to an object in C++, you can use the "new" keyword to dynamically
allocate memory for the object, and then use the "address of" operator "&" to obtain a pointer
to the object.

Example:
#include <iostream.h>
#include <string.h>
class Person
{
public: string name;
int age;
void say_hello()
{
cout << "Hello, my name is " << name << endl;
}
};
int main()
{
// Create a pointer to a Person object
Person *p = new Person();
// Access the object's properties and methods using the pointer
p->name = "OOP";
p->age = 25;
p->say_hello();
// Deallocate memory when the object is no longer needed delete p;
return 0;
}

Output:

PIET -DS(CE) PAGE NO:49


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

2. How do you declare and initialize a pointer to an object in C++?


Answer:
Syntax: ClassName *pointerName = new ClassName();

Here's what each part of the syntax does:


1)ClassName: Replace this with the name of the class you're creating an object of.
2)*pointerName: This declares a pointer to an object of type ClassName. The * denotes that
pointerName is a pointer.
3)new ClassName(): This dynamically allocates memory for an object of type

ClassName and returns a pointer to it. The new keyword is used for dynamic memory allocation,
and ClassName() is the constructor call to create the object.

3. What is a Pointer to a Derived Class in C++?


Answer:
 We can use pointers not only in the base class objects but also to the objects of derived
classes.
 Pointers to the objects of a base class are type compatible with pointers to the objects of a
derived class.

Example:
#include<iostream.h>
#include<conio.h>
class base
{
public:
void show()
{
cout<<"base class";
}
};
class derive: public base
{
public:
void show()
{
cout<<"derive class";
}
};
int main()
{
derive d;
derive *dp;

PIET -DS(CE) PAGE NO:50


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

dp = &d;
dp -> show();
return 0;
}

Output:

4. Define Virtual Functions in C++.


Answer:
 If we create a base class pointer and assign address of derived class object to it then also it
will call a base class function, not call a derived class function and this problem can be solved
by using of virtual function.
 Virtual means existing in effect but not in reality.
 A function is said to be a virtual when the same function name is used in both base and derived
class, and the keyword virtual is written before the return type of function in the base class
definition.
 A virtual function is a function that is declared as virtual in base class and redefined in derive
class.

5. How do you declare a virtual function in C++?


Answer:
In C++, you declare a virtual function in a base class by using the virtual keyword in front of the
function declaration.

Example:
#include<iostream.h>
#include<conio.h>
class A
{
public:
virtual void display()
{
cout<<"base class called";
}
};
class B: public A
{
public:
void display()
{

PIET -DS(CE) PAGE NO:51


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

cout<<"Derived class called";


}
};

int main()
{
A*a;
B b;
a = &b;
a -> display();
return 0;
}

Output:

6. Explain the concept of Pointer to Virtual Functions in C++.


Answer:
 By using virtual function , we can call derived class member function through base class
pointer.
 A virtual function determine which function to use at run time based on the type of object
pointed to by the base pointer.

Example:
#include <iostream.h>
class base {
public:
virtual void print()
{
cout << "print base class\n";
}

void show()
{
cout << "show base class\n";
}
};

class derived : public base


{
public:
void print()
{
PIET -DS(CE) PAGE NO:52
OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

cout << "print derived class\n";


}

void show()
{
cout << "show derived class\n";
}
};

int main()
{
base* bptr;
derived d;
bptr = &d;

// Virtual function, binded at runtime


bptr->print();

// Non-virtual function, binded at compile time


bptr->show();

return 0;
}

Output:

7. What is the 'this' Pointer in C++?


Answer:
 In C++ programming, this is a keyword that refers to the current instance of the class. There
can be 3 main usage of this keyword in C++.
 It can be used to pass current object as a parameter to another method and to refer current
class instance variable and also used to declare indexers.

Example:
#include <iostream.h>

class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;

PIET -DS(CE) PAGE NO:53


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

Employee(int id, string name, float salary)


{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Object", 890000); //creating an object of Employee
Employee e2=Employee(102, "Oriented", 59000); //creating an object of Employee
e1.display();
e2.display();
return 0;
}

Output:

8. What is the difference between a virtual function and a non-virtual function?


Answer:
VIRTUAL FUNCTION NON-VIRTUAL FUNCTION
A virtual function is a member function of A pure virtual function is a member
base class which can be redefined by function of base class whose only
derived class. declaration is provided in base class and
should be defined in derived class
otherwise derived class also becomes
abstract.
Classes having virtual functions are not Base class containing pure virtual
abstract. function becomes abstract.
Definition is given in base class. No definition is given in base class.
Base class having virtual function can be Base class having pure virtual function
instantiated i.e. its object can be made. becomes abstract i.e. it cannot be
instantiated.
If derived class do not redefine virtual If derived class do not redefine virtual
function of base class, then it does not function of base class, then no
affect compilation. compilation error but derived class also
becomes abstract just like the base class.

PIET -DS(CE) PAGE NO:54


OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)

All derived class may or may not redefine All derived class must redefine pure
virtual function of base class. virtual function of base class otherwise
derived class also becomes abstract just
like base class.
Syntax: Syntax:
virtual<func_type><func_name>() virtual<func_type><func_name>()
{ = 0;
// code
}

PIET -DS(CE) PAGE NO:55

You might also like