0% found this document useful (0 votes)
20 views29 pages

OOSD IMP QUESTIONS

OOSD with CPP important topic..

Uploaded by

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

OOSD IMP QUESTIONS

OOSD with CPP important topic..

Uploaded by

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

UNIT-3

Q1. Structured Analysis and Structured Design(SA/SD)


Structured Analysis and Structured Design (SA/SD) is a diagrammatic notation that is
designed to help people understand the system. The basic goal of SA/SD is to improve quality
and reduce the risk of system failure. It establishes concrete management specifications and
documentation. It focuses on the solidity, pliability, and maintainability of the system.
Structured Analysis and Structured Design (SA/SD) is a software development method that
was popular in the 1970s and 1980s. The method is based on the principle of structured
programming, which emphasizes the importance of breaking down a software system into
smaller, more manageable components.
In SA/SD, the software development process is divided into two phases: Structured Analysis
and Structured Design. During the Structured Analysis phase, the problem to be solved is
analyzed and the requirements are gathered. The Structured Design phase involves designing
the system to meet the requirements that were gathered in the Structured Analysis phase.
Structured Analysis and Structured Design (SA/SD) is a traditional software development
methodology that was popular in the 1980s and 1990s. It involves a series of techniques for
designing and developing software systems in a structured and systematic way. Here are some
key concepts of SA/SD:
1. Functional Decomposition: SA/SD uses functional decomposition to break down a
complex system into smaller, more manageable subsystems. This technique involves
identifying the main functions of the system and breaking them down into smaller functions
that can be implemented independently.
2. Data Flow Diagrams (DFDs): SA/SD uses DFDs to model the flow of data through the
system. DFDs are graphical representations of the system that show how data moves
between the system’s various components.
3. Data Dictionary: A data dictionary is a central repository that contains descriptions of all
the data elements used in the system. It provides a clear and consistent definition of data
elements, making it easier to understand how the system works.
4. Structured Design: SA/SD uses structured design techniques to develop the system’s
architecture and components. It involves identifying the major components of the system,
designing the interfaces between them, and specifying the data structures and algorithms
that will be used to implement the system.
5. Modular Programming: SA/SD uses modular programming techniques to break down the
system’s code into smaller, more manageable modules. This makes it easier to develop, test,
and maintain the system.
Some advantages of SA/SD include its emphasis on structured design and documentation,
which can help improve the clarity and maintainability of the system. However, SA/SD has
some disadvantages, including its rigidity and inflexibility, which can make it difficult to adapt
to changing business requirements or technological trends. Additionally, SA/SD may not be
well-suited for complex, dynamic systems, which may require more agile development
methodologies.
The following are the steps involved in the SA/SD process:
1. Requirements gathering: The first step in the SA/SD process is to gather requirements from
stakeholders, including users, customers, and business partners.
2. Structured Analysis: During the Structured Analysis phase, the requirements are analyzed
to identify the major components of the system, the relationships between those
components, and the data flows within the system.
3. Data Modeling: During this phase, a data model is created to represent the data used in the
system and the relationships between data elements.
4. Process Modeling: During this phase, the processes within the system are modeled using
flowcharts and data flow diagrams.
5. Input/Output Design: During this phase, the inputs and outputs of the system are designed,
including the user interface and reports.
6. Structured Design: During the Structured Design phase, the system is designed to meet the
requirements gathered in the Structured Analysis phase. This may include selecting
appropriate hardware and software platforms, designing databases, and defining data
structures.
7. Implementation and Testing: Once the design is complete, the system is implemented and
tested.

Basically, the approach of SA/SD is based on the Data Flow Diagram. It is easy to understand
SA/SD but it focuses on well-defined system boundary whereas the JSD approach is too
complex and does not have any graphical representation.
SA/SD is combined known as SAD and it mainly focuses on the following 3 points:
1. System
2. Process
3. Technology
SA/SD involves 2 phases:
1. Analysis Phase: It uses Data Flow Diagram, Data Dictionary, State Transition diagram
and ER diagram.
2. Design Phase: It uses Structure Chart and Pseudo Code.

1. Analysis Phase:
Analysis Phase involves data flow diagram, data dictionary, state transition diagram, and
entity-relationship diagram.
Data Flow Diagram:
In the data flow diagram, the model describes how the data flows through the system. We can
incorporate the Boolean operators and & or link data flow when more than one data flow may
be input or output from a process.
For example, if we have to choose between two paths of a process we can add an operator or
and if two data flows are necessary for a process we can add an operator. The input of the
process “check-order” needs the credit information and order information whereas the output
of the process would be a cash-order or a good-credit-order.

Data Dictionary:
The content that is not described in the DFD is described in the data dictionary. It defines the
data store and relevant meaning. A physical data dictionary for data elements that flow
between processes, between entities, and between processes and entities may be included. This
would also include descriptions of data elements that flow external to the data stores.
A logical data dictionary may also be included for each such data element. All system names,
whether they are names of entities, types, relations, attributes, or services, should be entered in
the dictionary.

3. State Transition Diagram:


State transition diagram is similar to the dynamic model. It specifies how much time the
function will take to execute and data access triggered by events. It also describes all of the
states that an object can have, the events under which an object changes state, the
conditions that must be fulfilled before the transition will occur and the activities were
undertaken during the life of an object.

4. ER Diagram:
ER diagram specifies the relationship between data store. It is basically used in database
design. It basically describes the relationship between different entities .
2. Design Phase:
Design Phase involves structure chart and pseudocode.
1. Structure Chart:
It is created by the data flow diagram. Structure Chart specifies how DFS’s processes are
grouped into tasks and allocated to the CPU. The structured chart does not show the
working and internal structure of the processes or modules and does not show the
relationship between data or data flows. Similar to other SASD tools, it is time and cost-
independent and there is no error-checking technique associated with this tool. The modules
of a structured chart are arranged arbitrarily and any process from a DFD can be chosen as
the central transform depending on the analysts’ own perception. The structured chart is
difficult to amend, verify, maintain, and check for completeness and consistency.
2. Pseudo Code: It is the actual implementation of the system. It is an informal way of
programming that doesn’t require any specific programming language or technology .
Advantages of Structured Analysis and Structured Design (SA/SD):
1. Clarity and Simplicity: The SA/SD method emphasizes breaking down complex systems
into smaller, more manageable components, which makes the system easier to understand
and manage.
2. Better Communication: The SA/SD method provides a common language and framework
for communicating the design of a system, which can improve communication between
stakeholders and help ensure that the system meets their needs and expectations.
3. Improved maintainability: The SA/SD method provides a clear, organized structure for a
system, which can make it easier to maintain and update the system over time.
4. Better Testability: The SA/SD method provides a clear definition of the inputs and outputs
of a system, which makes it easier to test the system and ensure that it meets its
requirements.
Disadvantages of Structured Analysis and Structured Design (SA/SD):
1. Time-Consuming: The SA/SD method can be time-consuming, especially for large and
complex systems, as it requires a significant amount of documentation and analysis.
2. Inflexibility: Once a system has been designed using the SA/SD method, it can be difficult
to make changes to the design, as the process is highly structured and documentation-
intensive.
3. Limited Iteration: The SA/SD method is not well-suited for iterative development, as it is
designed to be completed in a single pass.

Q2. What is the difference between SA/SD and OMT?


Sr.
SA/SD OMT
No.
It manages system around real
1 It manages a system around procedures.
world objects.
More importance is on object
More importance is on functional model and less
2 model and less on functional
on object model.
model.
Dominance order is functional, dynamic and Dominance order is object,
3
object. dynamic and functional.
4 It is a historical approach. It is much advanced approach.
It clearly marks the system boundaries across System boundries can be easily
5 which software procedures should communicate extending by adding new objects,
with real world. It is difficult to extend boundries. relationships.
Decomposition of process to sub-process is not Decompsition is based on objects
6 standardized. Different people provide different so different people provide similar
decomposition. decomposition.
Reusablity of components across
Reusability of components across projects is less
7 projects is more as compared to
as compared to in OMT.
SA/AD.
8 Not easily modifiable and extensible. Easily modifiable and extensible.
Used when functions are more important than Used when data is more
9
data. important than functions.
Difficult to merge programming code organized It better integrates data with
10 about functions while database is organized programming code as database is
around data. organized around data.

Q3. Structured vs. Object-oriented Analysis


Below are the differences between structures and object oriented analysis:
Structured Analysis Object-Oriented Analysis

The main focus is on the process and The main focus is on data structure and
procedures of the system. real-world objects that are important.
Structured Analysis Object-Oriented Analysis

It uses System Development Life


Cycle (SDLC) methodology for
It uses Incremental or Iterative
different purposes like planning,
methodology to refine and extend our
analyzing, designing, implementing,
design.
and supporting an information
system.

It is suitable for well-defined projects It is suitable for large projects with


with stable user requirements. changing user requirements.

Risk while using this analysis


Risk while using this analysis technique is
technique is high and reusability is
low and reusability is also high.
also low.

Structuring requirements include Requirement engineering includes the


DFDs (Data Flow Diagram), Use case model (find Use cases, Flow of
Structured Analysis, ER (Entity events, Activity Diagram), the Object
Relationship) diagram, CFD (Control model (find Classes and class relations,
Flow Diagram), Data Dictionary, Object interaction, Object to ER
Decision table/tree, and the State mapping), Statechart Diagram, and
transition diagram. deployment diagram.

This technique is old and is not This technique is new and is mostly
preferred usually. preferred.

Q4. Jackson System Development (JSD)


Jackson System Development (JSD) is a method of system development that covers the
software life cycle either directly or by providing a framework into which more specialized
techniques can fit. This article focuses on discussing JSD in detail.
What is Jackson System Development (JSD)?
Jackson system development is a linear system development approach that lets one describe
and model the real world. JSD can start from the stage in a project when there is only a general
statement of requirements.
However many projects that have used JSD started slightly later in the life cycle, doing the first
steps largely from existing documents rather than directly with the users.
The later steps of JSD produce the code of the final system.
The output of the earlier steps is a set of program design problems.
Phases of Jackson System Development (JSD)
1. Modelling Phase
In the modelling phase of JSD, the designer creates a collection of entity structure diagrams
and identifies the entities in the system, the actions they perform, the attributes of the actions
and the time order of the actions in the life of the entities.
2. Specification Phase
This phase focuses on actually what is to be done? Previous phase provides the basic for this
phase. An sufficient model of a time-ordered world must itself be time-ordered. Major goal is
to map progress in the real world on progress in the system that models it.
3. Implementation Phase
In the implementation phase JSD determines how to obtain the required functionality.
Implementation way of the system is based on the transformation of the specification into an
efficient set of processes. The processes involved in it should be designed in such a manner
that it would be possible to run them on available software and hardware.
Jackson System Development (JSD) Steps
Initially there were six steps when it was originally presented by Jackson, they were as below:
Entity/action step
Initial model step
Interactive function step
Information function step
System timing step
System implementation step
Later some steps were combined to create method with only three steps:
1. Modelling Step
In this step, the designer creates a collection of entity structure diagrams. The designer
identifies the entities in the system, actions they perform, the time-ordering of the actions in
the life of the entities, and the attributes of the actions and entities. Purpose is to create a good
full description of the aspects of the system and the organization and the developer has to
decide which things are important and which are not. Thus, aiding in good communication
between developers and the users of the new system.
2. Network Step
The network step involves modelling the system as a whole and representing as a System
Specification Diagram (SSD) also known as Network Diagram. It shows processes and how
they communicate with each other. Here, each entity becomes a process. The purpose of these
processes is to process the input, calculate output, and to keep the entity process up-to date .
3. Implementation Step
In the implementation stage, the abstract network model of the system is converted to the
physical system, represented as a system implementation diagram (SID). The SID shows the
scheduler process that calls modules that implement the processes. The goal here is the
optimization of the system. It is necessary here to reduce the number of processes as it is
impossible to provide each process contained in the specification its own virtual processor. The
processes are combined to limit the number of processors.
Benefits of JSD
1. It is designed to solve the real-time problems.
2. JSD modelling focuses on time.
3. It considers simultaneous processing and timing.
4. Provides functionality in the real world.
5. It is a better approach for microcode applications .

Limitations of JSD
1. It is a poor methodology for high level analysis and database design.
2. JSD is a complex methodology due to pseudo code representation.
3. It is less graphically oriented as compared to SA/SD or OMT.
4. It is a bit complex and difficult to understand.

Q5. Differences between Procedural and


Object Oriented Programming
Procedural Programming

Procedural Programming can be defined as a programming model which is derived from


structured programming, based upon the concept of calling procedure. Procedures, also known
as routines, subroutines or functions, simply consist of a series of computational steps to be
carried out. During a program’s execution, any given procedure might be called at any point,
including by other procedures or itself.
Languages used in Procedural Programming:
FORTRAN, ALGOL, COBOL,
BASIC, Pascal and C.
Object-Oriented Programming

Object-oriented programming can be defined as a programming model which is based upon the
concept of objects. Objects contain data in the form of attributes and code in the form of
methods. In object-oriented programming, computer programs are designed using the concept
of objects that interact with the real world. Object-oriented programming languages are various
but the most popular ones are class-based, meaning that objects are instances of classes, which
also determine their types.
Languages used in Object-Oriented Programming:
Java, C++, C#, Python,
PHP, JavaScript, Ruby, Perl,
Objective-C, Dart, Swift, Scala.

Procedural Programming vs Object-Oriented Programming

Below are some of the differences between procedural and object-oriented programming:

Procedural Oriented Programming Object-Oriented Programming

In object-oriented programming, the


In procedural programming, the program is
program is divided into small parts
divided into small parts called functions.
called objects.

Procedural programming follows a top-down Object-oriented programming follows


approach. a bottom-up approach.

There is no access specifier in procedural Object-oriented programming has access


programming. specifiers like private, public, protected, etc.

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

Procedural programming does not have any Object-oriented programming provides data
proper way of hiding data so it is less secure. hiding so it is more secure.
Procedural Oriented Programming Object-Oriented Programming

In procedural programming, overloading is Overloading is possible in object-oriented


not possible. programming.

In procedural programming, there is no In object-oriented programming, the concept


concept of data hiding and inheritance. of data hiding and inheritance is used.

In procedural programming, the function is In object-oriented programming, data is


more important than the data. more important than function.

Procedural programming is based on Object-oriented programming is based on


the unreal world. the real world.

Procedural programming is used for designing Object-oriented programming is used for


medium-sized programs. designing large and complex programs.

Procedural programming uses the concept of Object-oriented programming uses the


procedure abstraction. concept of data abstraction.

Code reusability absent in procedural Code reusability present in object-oriented


programming, programming.

Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.

UNIT-4
Q1. What are Macros?
In C++, a macro is part of code that is expanded to its value. Macros are defined using the
#define directive. They provide a way to create symbolic constants and code snippets that can
be reused throughout a program. Macros are processed by the C++ preprocessor, which runs
before the actual compilation. During preprocessing, macros are replaced with their
corresponding values, making it an effective tool for code generation and simplification.
Syntax
The syntax for defining a macro in C++ is as follows:
#define MACRO_NAME macro_definition
 MACRO_NAME: It is the name we give to the macro, that’s usually in uppercase to
differentiate it from ordinary C++ identifiers.
 macro_definition: It is the code that the preprocessor will substitute whenever the macro
is used.
Example of Macro
Let’s explore a simple example of a macro in C++. Suppose we want to create a macro to
calculate the square of a number. Here’s how we can define and use a macro:
// C++ program to illustrate the macro definition
#include <iostream>
using namespace std;
// Define a macro to calculate the square of a number
#define SQUARE(x) (x * x)
int main()
{
int n = 7;
int result = SQUARE(n); // Expands to: (n * n)
cout << "Square of " << n << " is " << result;
return 0;
}
Output
Square of 7 is 49

Difference between Inline and Macro in C++


1. Inline :
An inline function is a normal function that is defined by the inline keyword. An inline
function is a short function that is expanded by the compiler. And its arguments are evaluated
only once. An inline functions are the short length functions that are automatically made the
inline functions without using the inline keyword inside the class.
Syntax of an Inline function:
inline return_type function_name ( parameters )
{
// inline function code
}
Example of an Inline function:
1. Inline :
An inline function is a normal function that is defined by the inline keyword. An inline
function is a short function that is expanded by the compiler. And its arguments are evaluated
only once. An inline functions are the short length functions that are automatically made the
inline functions without using the inline keyword inside the class.
Syntax of an Inline function:
inline return_type function_name ( parameters )
{
// inline function code
}
Example of an Inline function:
#include <iostream>
using namespace std;

// Inline function
inline int Maximum(int a, int b)
{
return (a > b) ? a : b;
}

// Main function for the program


int main()
{
cout << "Max (100, 1000):" << Maximum(100, 1000) << endl;
cout << "Max (20, 0): " << Maximum(20, 0) << endl;

return 0;
}
Output:
Max (100, 1000): 1000
Max (20, 0): 20
2. Macro :
It is also called preprocessors directive. The macros are defined by the #define keyword.
Before the program compilation, the preprocessor examines the program whenever the
preprocessor detects the macros then preprocessor replaces the macro by the macro definition.
Syntax of Macro:
#define MACRO_NAME Macro_definition

Example of Macro:
#include <iostream>
using namespace std;

// macro with parameter


#define MAXIMUM(a, b) (a > b) ? a : b

// Main function for the program


int main()
{
cout << "Max (100, 1000):";
int k = MAXIMUM(100, 1000);
cout << k << endl;

cout << "Max (20, 0):";


int k1 = MAXIMUM(20, 0);
cout << k1;

return 0;
}
Output:
Max (100, 1000):1000
Max (20, 0):20

Difference between Inline and Macro in C++ :


S.NO Inline Macro

An inline function is defined by Whereas the macros are defined by


1.
the inline keyword. the #define keyword.

Through inline function, the class’s Whereas macro can’t access the class’s data
2.
data members can be accessed. members.

3. In the case of inline function, the Whereas in the case of macros, the program
S.NO Inline Macro

program can be easily debugged. can’t be easily debugged.

Whereas in the case of macro, the arguments


In the case of inline, the arguments are
4. are evaluated every time whenever macro is
evaluated only once.
used in the program.

In C++, inline may be defined either Whereas the macro is all the time defined at
5.
inside the class or outside the class. the beginning of the program.

In C++, inside the class, the short


6. length functions are automatically While the macro is specifically defined.
made the inline functions.

7. Inline is not as widely used as macros. While the macro is widely used.

Inline is not used in competitive While the macro is very much used in
8.
programming. competitive programming.

Inline function is terminated by the While the macro is not terminated by any
9.
curly brace at the end. symbol, it is terminated by a new line.

Q2. Function Overloading


With function overloading, multiple functions can have the same name with
different parameters:

Example
int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)

Consider the following example, which have two functions that add numbers of
different type:
Example
int plusFuncInt(int x, int y) {
return x + y;
}

double plusFuncDouble(double x, double y) {


return x + y;
}

int main() {
int myNum1 = plusFuncInt(8, 5);
double myNum2 = plusFuncDouble(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}

Instead of defining two functions that should do the same thing, it is better to
overload one.

In the example below, we overload the plusFunc function to work for


both int and double:

Example
int plusFunc(int x, int y) {
return x + y;
}

double plusFunc(double x, double y) {


return x + y;
}

int main() {
int myNum1 = plusFunc(8, 5);
double myNum2 = plusFunc(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
Q3. Default Arguments in C++
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.
1) The following is a simple C++ example to demonstrate the use of default arguments. Here, we
don’t have to write 3 sum functions; only one function works by using the default values for 3rd
and 4th arguments.
// CPP Program to demonstrate Default Arguments
#include <iostream>
using namespace std;

// A function with default arguments,


// it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z = 0, int w = 0) //assigning default values to z,w as 0
{
return (x + y + z + w);
}

// Driver Code
int main()
{
// Statement 1
cout << sum(10, 15) << endl;

// Statement 2
cout << sum(10, 15, 25) << endl;

// Statement 3
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
Output
25
50
80

Q4. Virtual Function in C++


A virtual function (also known as virtual methods) is a member function that is declared within
a base class and is re-defined (overridden) by a derived class. When you refer to a derived
class object using a pointer or a reference to the base class, you can call a virtual function for
that object and execute the derived class’s version of the method.
 Virtual functions ensure that the correct function is called for an object, regardless of the
type of reference (or pointer) used for the function call.
 They are mainly used to achieve Runtime polymorphism .
 Functions are declared with a virtual keyword in a base class.
 The resolving of a function call is done at runtime.
Rules for Virtual Functions
The rules for the virtual functions in C++ are as follows:
1. Virtual functions cannot be static.
2. A virtual function can be a friend function of another class.
3. Virtual functions should be accessed using a pointer or reference of base class type to
achieve runtime polymorphism.
4. The prototype of virtual functions should be the same in the base as well as the derived
class.
5. They are always defined in the base class and overridden in a derived class. It is not
mandatory for the derived class to override (or re-define the virtual function), in that case,
the base class version of the function is used.
6. A class may have a virtual destructor but it cannot have a virtual constructor.

Compile time (early binding) VS runtime (late binding)


behavior of Virtual Functions
Consider the following simple program showing the runtime behavior of virtual functions.
// C++ program to illustrate
// concept of Virtual Functions

#include <iostream>
using namespace std;

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() { 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;
}

Q5. C++ Classes/Objects


C++ is an object-oriented programming language.

Everything in C++ is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and
brake.

Attributes and methods are basically variables and functions that belongs
to the class. These are often referred to as "class members".

A class is a user-defined data type that we can use in our program, and it
works as an object constructor, or a "blueprint" for creating objects.

Create a Class
To create a class, use the class keyword:

Example
Create a class called "MyClass":

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

Example explained
 The class keyword is used to create a class called MyClass.
 The public keyword is an access specifier, which specifies that
members (attributes and methods) of the class are accessible from
outside the class. You will learn more about access specifiers later.
 Inside the class, there is an integer variable myNum and a string
variable myString. When variables are declared within a class, they are
called attributes.
 At last, end the class definition with a semicolon ;.

Create an Object
In C++, an object is created from a class. We have already created the
class named MyClass, so now we can use this to create objects.

To create an object of MyClass, specify the class name, followed by the


object name.

To access the class attributes (myNum and myString), use the dot syntax
(.) on the object:

Example
Create an object called "myObj" and access the attributes:

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

int main() {
MyClass myObj; // Create an object of MyClass

// Access attributes and set values


myObj.myNum = 15;
myObj.myString = "Some text";

// Print attribute values


cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}

UNIT-5
Q1. Difference between Public and Private
Public Private

The class members declared as


All the class members declared under
private can be accessed only by
public will be available to everyone.
the functions inside the class.

Only the member functions or


The data members and member functions
the friend functions are allowed
declared public can be accessed by other
to access the private data
classes too.
members of a class.

The public members of a class can be


They are not allowed to be
accessed from anywhere in the program
accessed directly by any object
using the direct member access operator
or function outside the class.
(.) with the object of that class.

Q2. C++ Constructor


In C++, constructor is a special method which is invoked automatically at the time of
object creation. It is used to initialize the data members of new object generally. 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
name. When an object is completed, the constructor is called. Because it creates the
values or gives data for the thing, it is known as a constructor.

The Constructors prototype looks like this:


<class-name> (list-of-parameters);

The following syntax is used to define the class's constructor:


<class-name> (list-of-parameters) { // constructor definition }
The following syntax is used to define a constructor outside of a class:

<class-name>: :<class-name> (list-of-parameters){ // constructor definition}


Constructors lack a return type since they don't have a return value.

There can be two types of constructors in C++.

o Default constructor
o Parameterized constructor

C++ Default Constructor


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

Let's see the simple example of C++ default Constructor.

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

Default Constructor Invoked


Default Constructor Invoked

C++ Parameterized Constructor


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

Let's see the simple example of C++ Parameterized Constructor.

#include <iostream>
using namespace std;
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;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Em
ployee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Output:

101 Sonoo 890000


102 Nakul 59000

Copy Constructor in C++


A copy constructor is a type of constructor 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.
The process of initializing members of an object through a copy constructor is
known as copy initialization. It is also called member-wise
initialization because the copy constructor initializes one object with the existing
object, both belonging to the same class on a member-by-member copy basis.

Syntax of Copy Constructor in C++


Copy constructor takes a reference to an object of the same class as an
argument:
className (const ClassName &obj)
{
member1 = obj.member1;
// for dynamic resources

......
}
Here, the const qualifier is optional but is added so that we do not modify the obj
by mistake.

Example 1: User Defined Copy Constructor


// C++ program to illustrate the use of copy constructor
#include <iostream>
#include <string.h>
using namespace std;

// Class definition for 'student'


class student {
int rno;
string name;
double fee;

public:
// Parameterized constructor
student(int, string, double);
// Copy constructor
student(student& t)
{
rno = t.rno;
name = t.name;
fee = t.fee;
cout << "Copy Constructor Called" << endl;
}
// Function to display student details
void display();
};

// Implementation of the parameterized constructor


student::student(int no, string n, double f)
{
rno = no;
name = n;
fee = f;
}

// Implementation of the display function


void student::display()
{
cout << rno << "\t" << name << "\t" << fee << endl;
}

int main()
{
// Create student object with parameterized constructor
student s(1001, "Manjeet", 10000);
s.display();

// Create another student object using the copy


// constructor
student manjeet(s);
manjeet.display();

return 0;
}

Output
1001 Manjeet 10000
Copy Constructor Called
1001 Manjeet 10000

Q3. C++ Operators Overloading


Operator overloading is a compile-time polymorphism in which the operator is
overloaded to provide the special meaning to the user-defined data type. Operator
overloading is used to overload or redefines most of the operators available in C++.
It is used to perform the operation on the user-defined data type. For example, C++
provides the ability to add the variables of the user-defined data type that is applied
to the built-in data types.

The advantage of Operators overloading is to perform different operations on the


same operand.

Operator that cannot be overloaded are as follows:

o Scope operator (::)


o Sizeof
o member selector(.)
o member pointer selector(*)
o ternary operator(?:)

Syntax of Operator Overloading


1. return_type class_name : : operator op(argument_list)
2. {
3. // body of the function.
4. }

Where the return type is the type of value returned by the function.

class_name is the name of the class.

operator op is an operator function where op is the operator being overloaded, and


the operator is the keyword.
Rules for Operator Overloading
o Existing operators can only be overloaded, but the new operators
cannot be overloaded.
o The overloaded operator contains atleast one operand of the user-
defined data type.
o We cannot use friend function to overload certain operators. However,
the member function can be used to overload those operators.
o When unary operators are overloaded through a member function take
no explicit arguments, but, if they are overloaded by a friend function,
takes one argument.
o When binary operators are overloaded through a member function takes
one explicit argument, and if they are overloaded through a friend
function takes two explicit arguments.

program to overload the unary operator ++.

#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){} //Constructor to initialize count to 8
void operator ++() {
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}
The Count is: 10

Q4. Differences between function


overloading and operator overloading
Function overloading means using a single name and giving more
functionality to it. Operator overloading means adding extra
functionality for a certain operator. When an operator is overloaded,
the operator has different meanings, which depend on the type of its
operands.

Function Overloading Operator Overloading

Involves having multiple functions


Involves defining new behaviors for
with the same name but different
existing operators with specific types.
parameters.

Distinguished by the number and Defined for specific types, often within t
types of parameters. class definition of those types.

Enhances code readability and allows


Improves code readability and
objects of user-defined types to behave
function utilization.
like fundamental types.

Q5. What is Ineritance? Explain types of inheritance in C++


with program.

Q6. Type Conversion in C++


Implicit Type Conversion Also known as ‘automatic type conversion’.

 Done by the compiler on its own, without any external trigger from the user.
 Generally takes place when in an expression more than one data type is present.
In such condition type conversion (type promotion) takes place to avoid lose of
data.
 All the data types of the variables are upgraded to the data type of the variable
with largest data type.

// An example of implicit conversion

#include <iostream>
using namespace std;

int main()
{
int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to int. ASCII


// value of 'a' is 97
x = x + y;

// x is implicitly converted to float


float z = x + 1.0;

cout << "x = " << x << endl


<< "y = " << y << endl
<< "z = " << z << endl;

return 0;
Output
x = 107
y = a
z = 108

Explicit Type Conversion: This process is also called type casting and it is user-
defined. Here the user can typecast the result to make it of a particular data type. In
C++, it can be done by two ways:
 Converting by assignment: This is done by explicitly defining the required type
in front of the expression in parenthesis. This can be also considered as forceful
casting. Syntax:
(type) expression
where type indicates the data type to which the final result is
converted. Example:
// C++ program to demonstrate
// explicit type casting

#include <iostream>
using namespace std;

int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

cout << "Sum = " << sum;

return 0;
}
Output
Sum = 2
Conversion using Cast operator: A Cast operator is an unary operator which
forces one data type to be converted into another data type. C++ supports four types
of casting:

1. Static Cast
2. Dynamic Cast
3. Const Cast
4. Reinterpret Cast

#include <iostream>
using namespace std;
int main()
{
float f = 3.5;

// using cast operator


int b = static_cast<int>(f);

cout << b;
}
Output
3
Advantages of Type Conversion:
 This is done to take advantage of certain features of type hierarchies or type
representations.
 It helps to compute expressions containing variables of different data types.

You might also like