0% found this document useful (0 votes)
90 views40 pages

OOP Lecture Notes: Concepts & Legacy Systems

This document discusses object-oriented concepts and programming. It describes what objects are, the differences between procedural and object-oriented programming, and the benefits of OOP. It also covers key OOP concepts like inheritance, encapsulation, abstraction, and polymorphism.

Uploaded by

amogh1391
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)
90 views40 pages

OOP Lecture Notes: Concepts & Legacy Systems

This document discusses object-oriented concepts and programming. It describes what objects are, the differences between procedural and object-oriented programming, and the benefits of OOP. It also covers key OOP concepts like inheritance, encapsulation, abstraction, and polymorphism.

Uploaded by

amogh1391
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/ 40

1

INSTITUTE OF AERONAUTICAL ENGINEERING


(Autonomous)
Dundigal, Hyderabad - 500 043

Lecture Notes:

OBJECT ORIENTED PROGRAMMING (ACSD01)

Drafted by :
Dr. J Sirisha Devi (IARE10566)
Associate Professor

Department of Computer Science and Engineering


Institute of Aeronautical Engineering
November 18, 2023
Contents

Contents 1

1 OBJECT-ORIENTED CONCEPTS 1
1.1 Objects . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . 1
1.2 Legacy systems . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 Procedural versus Object-oriented programming . . . . . . . . . . . . . . . 2
1.4 Top-down and bottom-up approaches . . . . . . . . . . . . . . . . . . . . . 3
1.5 Benefits of OOP . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 Applications of OOP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.7 Features of OOP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.7.1 Inheritance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.7.2 Encapsulation. . . . . . . . .. . . . . . . . . . . . . . . . . . . . . 6
1.7.3 Abstraction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.7.4 Polymorphism. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.7.5 Method Overriding. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.7.6 Method Overloading. . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2 ABSTRACTION 9
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2 Layers of Abstraction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2.1 Physical or Internal level . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2.2 Logical or Conceptual level . . . . . . . . . . . . . . . . . . . . . . . . 10
2.2.3 View or External level . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.3 Forms of Abstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.4 Abstraction Mechanism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3 CLASSES AND OBJECTS 12
3.1 Classes and objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.2 Object data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.3 Object behaviors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.4 Creating Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.5 Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.6 Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.7 Messages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.8 Creating Class Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.9 Class Diagram Example: GUI. . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.10 Access Specifiers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.11 Accessing Members and Methods. . . . . . . . . . . . . . . . . . . . . . . . . 20
3.11.1 Private Access Modifier. . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.11.2 Default Access Modifier. . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.11.3 Protected Access Modifier. . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.11.4 Public Access Modifier. . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.12 Static Member. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.13 Accessing Static Members without any Object. . . . . . . . . . . . . . . . . .. 28
3.14 Static Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4 SPECIAL MEMBER FUNCTIONS AND OVERLOADING 30
4.1 Constructors and Destructors. . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.2 Need for Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.3 Types of Constructors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.3.1 Copy Constructor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.3.2 Dynamic Constructor. . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
4.3.3 Parameterized Constructor. . . . . . . . . . . . . . . . . . . . . . . . . 33
4.4 Destructors with Static Members. . . . . . . . . . . . . . . . . . . . . . . . . 35
4.5 Virtual Destructors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
MODULE – I

1. OBJECT-ORIENTED CONCEPTS

1.1 Objects
As the name object-oriented implies, objects are key to understanding object-oriented technology. You
can look around you now and see many examples of real-world objects: your dog, your desk, your
television set, your bicycle.
These real-world objects share two characteristics: they all have state and they all have behavior. For
example, dogs have state (name, color, breed, hungry) and dogs have behavior (barking, fetching, and
slobbering on your newly cleaned slacks). Bicycles have state (current gear, current pedal cadence, two
wheels, number of gears) and behavior (braking, accelerating, slowing down, changing gears).
Software objects are modeled after real-world objects in that they, too, have state and behavior. A
software object maintains its state in variables and implements its behavior with methods.
Definition: An object is a software bundle of variables and related methods.

1.2 Legacy systems


A legacy system is a computer platform, programming language, or software application that continues
to be used to support critical business functions, even though there are newer alternatives. In this
context, the label “legacy” means that the technology has become so ingrained in an organization’s
workflow processes and culture that replacing it would not be cost-effective at this time.
If a legacy system is still reliable and does its job well, the direct and indirect costs of replacing a
legacy system may just not be worth it.

Rip-and-replace and other modernization efforts can be costly in terms of both time and money. In
fact, the change management challenges of replacing established systems that still work well can be
so daunting that many organizations find themselves embracing the old adage, “If it’s not broke, don’t
fix it.”

Legacy platforms and applications often remain operational because they are deeply embedded in an
organization’s business processes. Some examples include:

• Windows XP: Despite Microsoft ending official support for Windows XP in 2014, there are
still instances of businesses and industries using it, often because of application compatibility
issues.
• Older Database Systems: Some companies still rely on old versions of Oracle Database,
Microsoft SQL Server, or IBM DB2 databases because migration to a new database
management system (DBMS) could be costly and time-consuming.
• Legacy Enterprise Resource Planning (ERP) Systems: Older versions of ERP systems like SAP
R/3 or Oracle E-Business Suite can still be found running in some organizations.
• Medical Systems: Devices like MRI machines, ultrasound machines, and other diagnostic
equipment often run on older operating systems or software because of their long lifespan and
high cost of replacement.
• Industrial Control Systems: Many factories and utilities are still using Supervisory Control and
Data Acquisition (SCADA) systems that are decades old.

1
• Point of Sale Systems: Some smaller retail establishments still use older point-of-sale (POS)
systems because they still work, and it’s not worth the cost to upgrade them.
• Bank ATM Software: Some ATMs still run on Windows XP Embedded.
• Older Office Software: Some businesses might still use older versions of Microsoft Office
because they rely on macros and plugins that aren’t compatible with newer versions of the
productivity suite.
• Legacy Telecommunication Systems: Many businesses around the world still rely on
older PBX systems for telephony instead of adopting newer VoIP services.
• Aircraft Systems: Avionics and other in-flight systems sometimes run on legacy software and
hardware because of long testing and certification cycles.
Legacy programming languages are not as popular as they once were, but their use is so ingrained in
certain systems and applications that it’s too complicated to replace them.

For example, many automated teller machines (ATMs) today interface with backend banking systems
that still process transactions on mainframes running COBOL.

Completely phasing out COBOL has been a challenge due to the complexities and high costs of data
migration and the dwindling number of COBOL programmers who would know how to transition these
legacy systems to modern platforms.

Other legacy programming languages still in use today include:

• FORTRAN (Formula Translation): FORTRAN continues to be used in scientific and


engineering contexts, especially in high-performance computing.
• Assembly languages: Assembly is still used in situations requiring low-level hardware access
or optimization. It’s also taught in some computer science courses to give students an
understanding of how computers work at a low level.
• PL/I (Programming Language One): PL/I use over the years has declined significantly, but it
may still be found in some legacy IBM systems.
• RPG (Report Program Generator): RPG is still in use, especially within the IBM i platform
(formerly AS/400).
• ADA: While its popularity has waned in the general software development world, ADA
remains in use in safety-critical and real-time systems, especially in aerospace and defense.
• Prolog: Prolog remains in use for specific tasks in artificial intelligence (AI), expert systems,
and other logic-based domains.
• Lisp: Lisp and Scheme (a LISP dialect) are still used in research and some specialized areas,
especially artificial intelligence.

1.3 Procedural versus Object-oriented programming


Procedural Programming can be defined as a programming model that 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.

Object-oriented programming can be defined as a programming model which is based on the concept

2
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.

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

Procedural Oriented Programming Object-Oriented Programming


In procedural programming, the program is In object-oriented programming, the program is
divided into small parts called functions. divided into small parts called objects.
Procedural programming follows a top-down Object-oriented programming follows a bottom-
approach. 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.
In procedural programming, overloading is not Overloading is possible in object-oriented
possible. programming.
In procedural programming, there is no concept In object-oriented programming, the concept of
of data hiding and inheritance. data hiding and inheritance is used.
In procedural programming, the function is more In object-oriented programming, data is more
important than the data. important than function.
Procedural programming is based on the unreal Object-oriented programming is based on
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 concept
procedure abstraction. 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.

1.4 Top-down and bottom-up approaches


In the top-down model, an overview of the system is formulated without going into detail about any
part of it. Each part of it is then refined into more detail, defining it in yet more detail until the entire
specification is detailed enough to validate the model. if we glance at a haul as a full, it’s going to
appear not possible as a result of it being so complicated for example: Writing a University system
program, writing a word processor. Complicated issues may be resolved through victimization high
down style, conjointly referred to as Stepwise refinement were,
1. We break the problem into parts,
2. Then break the parts into parts and now each of the parts will be easy to do.
Advantages:
• Breaking problems into parts helps us to identify what needs to be done.
• At each step of refinement, new parts will become less complex and therefore easier to solve.
• Parts of the solution may turn out to be reusable.
• Breaking problems into parts allows more than one person to solve the problem.

3
In this design, individual parts of the system are specified in detail. The parts are linked to form larger
components, which are in turn linked until a complete system is formed. Object-oriented language such
as C++ or Java uses a bottom-up approach where each object is identified first.
Advantage:
• Make decisions about reusable low-level utilities then decide how they will be put together to
create high-level construct. ,
The contrast between Top-down design and bottom-up design.

Top-Down Approach Bottom-Up Approach


In the bottom-up approach, we solve smaller
In this approach, we focus on breaking up the
problems integrate them as a whole, and
problem into smaller parts.
complete the solution.
Mainly used by structured programming Mainly used by object-oriented programming
languages such as COBOL, Fortran, C, etc. languages such as C++, C#, and Python.
Each part is programmed separately and Redundancy is minimized by using data
therefore contains redundancy. encapsulation and data hiding.
In this, the communication is less among
This module must have communication.
modules.
It is used in debugging, module documentation,
It is basically used in testing.
etc.
In the top-down approach, decomposition takes In the bottom-up approach, composition takes
place. place.
This top function of the system might be hard to In this sometimes we cannot build a program
identify. from the piece we have started.
In this implementation details may differ. This is not natural for people to assemble.
Pros-
Pros-
• Easier isolation of interface errors
• Easy to create test conditions
• It benefits in the case an error occurs towards
• Test results are easy to observe
the top of the program.
It is suited if defects occur at the bottom of the
Defects in design get detected early and can be
program.
corrected as an early working module of the
program is available.
Cons- Cons-
• Difficulty in observing the output of the test • There is no representation of the working
case. model once several modules have been
• Stub writing is quite crucial as it leads to the constructed.
setting of output parameters. • There is no existence of the program as an
When stubs are located far from the top-level entity without the addition of the last module.
module, choosing test cases and designing stubs From a partially integrated system, test
becomes more challenging. engineers cannot observe system-level
functions. It can be possible only with the
installation of the top-level test driver.

1.5 Benefits of Object-Oriented Programming


The benefits of Object-Oriented Programming are:
• We can build the programs from standard working modules that communicate with one another,
rather than having to start writing the code from scratch which leads to saving of development
time and higher productivity,

4
• OOP language allows to break of the program into bit-sized problems that can be solved easily
(one object at a time).
• The new technology promises greater programmer productivity, better quality of software, and
lesser maintenance costs.
• OOP systems can be easily upgraded from small to large systems.
• It is possible that multiple instances of objects co-exist without any interference,
• It is very easy to partition the work in a project based on objects.
• It is possible to map the objects in the problem domain to those in the program.
• The principle of data hiding helps the programmer build secure programs that cannot be invaded
by the code in other parts of the program.
• By using inheritance, we can eliminate redundant code and extend the use of existing classes.
• Message passing techniques are used for communication between objects which makes the
interface descriptions with external systems much simpler.
• The data-centered design approach enables us to capture more details of the model in an
implementable form.

1.6 Applications of OOP


Below are some applications of OOPs:
• Real-Time System design: Real-time system inherits complexities and makes it difficult to build
them. OOP techniques make it easier to handle those complexities.
• Hypertext and Hypermedia: Hypertext is similar to regular text as it can be stored, searched, and
edited easily. Hypermedia on the other hand is a superset of hypertext. OOP also helps in laying
the framework for hypertext and hypermedia.
• AI Expert System: These are computer application that is developed to solve complex problems
that are far beyond the human brain. OOP helps to develop such an AI expert System
• Office automation System: These include formal as well as informal electronic systems that are
primarily concerned with information sharing and communication to and from people inside and
outside the organization. OOP also help in making office automation principle.
• Neural networking and parallel programming: It addresses the problem of prediction and
approximation of complex-time varying systems. OOP simplifies the entire process by
simplifying the approximation and prediction ability of the network.
• Stimulation and modeling system: It is difficult to model complex systems due to the varying
specifications of variables. Stimulating complex systems requires modeling and understanding
interaction explicitly. OOP provides an appropriate approach for simplifying these complex
models.
• Object-oriented database: The databases try to maintain a direct correspondence between the real
world and the database object in order to let the object retain its identity and integrity.
• Client-server system: The object-oriented client-server system provides the IT infrastructure for
creating object-oriented server internet (OCSI) applications.
• CIM/CAD/CAM systems: OOP can also be used in manufacturing and designing applications as
it allows people to reduce the efforts involved. For instance, it can be used while designing
blueprints and flowcharts. So it makes it possible to produce these flowcharts and blueprints
accurately.

5
1.7 Features of OOP
1.7.1 Inheritance

In layman’s terms, the attributes that you inherit from your parents are a simple illustration of
inheritance. Classes may inherit characteristics from other classes thanks to inheritance. Parent classes,
in other words, extend properties and behaviors to child classes. Reusability is aided via inheritance.
Prototyping is another name for inheritance in JavaScript. A prototype object serves as a base from
which another object may derive its features and actions. Thus, you may use multiple prototype object
templates to form a prototype chain. Inheritance is passed down from one generation to the next. parent

Consider the application Polygon, which represents several Shapes. We’re expected to make two
distinct sorts of polygons: a Rectangle and a Triangle.

1.7.2. Encapsulation

Encapsulation is the process of enclosing all critical information inside an object and only revealing a
subset of it to the outside world. For example, code inside the class template defines attributes and
behaviors.

The data and methods are then enclosed in the object when it is created from the class. Inside a class,
encapsulation conceals the underlying software code implementation and the internal data of the
objects. Encapsulation necessitates designating certain fields as private while others are made public.
• Methods and attributes only available from other methods in the same class make up the
private/internal interface.
• Methods and attributes that are available from outside the class are known as the public/external
interface.
Encapsulation Demonstration in Real-Time: One of the most practical examples of encapsulation is a
school bag. Our books, pencils, and other items may be kept in our school bag.

The following are some of the advantages of encapsulation:


• Data Hiding: In this case, the user will be unaware of the class’s internal implementation. Even
the user will have no idea how the class stores data in variables. He or she will only be aware
that the values are sent to a setter method and that variables are initialised with that value.
• Increased Flexibility: Depending on our needs, we may make the variables of the class read-
only or write-only. If you want to make the variables read-only, remove the setter methods like
setName(), setAge(), and so on from the above programme. If you want to make the variables
write-only, remove the get methods like getName(), getAge(), and so on from the above
programme.
• It also promotes reusability and makes it simple to alter to meet new needs.

1.7.3. Abstraction

Abstraction refers to the user’s interaction with just a subset of an object’s characteristics and
operations. To access a complicated item, abstraction uses simpler, high-level techniques.
• Simple items are used to show complexity.
• Keep complicated information hidden from the user.

Simple classes are used to indicate complexity in abstraction. Encapsulation is an extension of


abstraction.

6
A Real-Life Example of Abstraction: Abstraction reveals just the most significant facts to the user while
hiding the underlying intricacies. For example, when we ride a bike, we only know how to ride it but
not how it works. We also have no idea how a bike works on the inside.

Advantages of Abstraction
• It simplifies the process of seeing things in their entirety.
• Code duplication is avoided, and reusability is increased.
• Because just the most necessary information is shown to the user, it helps to enhance the
security of an application or software.

1.7.4. Polymorphism

Polymorphism refers to the creation of items that have similar behavior. For example, objects may
override common parent behaviors with particular child behaviors through inheritance. Method
overriding and method overloading are two ways that polymorphism enables the same method to
perform various actions.

Examine how Polymorphism and the actual world are interconnected with examples.

Take, for example, your mobile phone. It has the capability of storing your Contacts. Consider the
following scenario: you wish to store two numbers for one individual. You may do this by storing the
second number under the same name as the first.

Consider the following scenario: you wish to store two numbers for the same individual in an object-
oriented language such as Java. Create a function that will accept as arguments two integers and the
name of the individual to some function void createContact that will be defined later (String name, int
number1, int number2).

1.7.5. Method Overriding

Method overriding is used in runtime polymorphism. When a child class overrides a parent class’s
method, the child class might offer an alternative implementation.

Consider a family of three, consisting of the father, mother, and son. The father makes the decision to
teach his kid to shoot. As a result, he brings him to the range with his favorite rifle and teaches him how
to aim and fire at targets. The father, on the other hand, is right-handed, while the kid is left-handed. So
they each have their own way of handling the pistol! Because of their differing orientations, the father
was concerned that he may not be able to teach his son how to shoot.

The son, on the other hand, was astute and chose to flip his father’s hands, putting his dominant hand
on the trigger rather than the father’s. Specifically, the right hand. By significantly changing the learning
process, the son was able to grasp the skill of shooting!

Method overriding is the term used in programming to describe this idea.

1.7.6. Method Overloading

Method overloading is used in compile-time polymorphism. Although two methods or functions may
have the same name, the number of arguments given to the method call may vary. Therefore, depending
on the number of parameters entered, you may obtain different results.

7
With the help of a simple example, it may be comprehended in simple words. A class addition contains
two add() methods, one with arguments int a and int b and the other with three integer parameters, int
a, int b, and int c. As a result, the add() function is considered overloaded.

The amount of arguments given in the method calling statement determines which method is performed.
For example, add(20,30) calls the two-parameter add() function, whereas add(10,20,30) calls the three-
parameter add method.

8
2. ABSTRACTION

2.1 Introduction
Abstraction is the process of hiding the internal details of an application from the outer world.
Abstraction is used to describe things in simple terms. It’s used to create a boundary between the
application and the client programs.

Abstraction is present in almost all real-life machines:


• Your car is a great example of abstraction. You can start a car by turning the key or pressing the
start button. You don’t need to know how the engine is getting started, or what all components
your car has. The car's internal implementation and complex logic are completely hidden from
the user.
• We can heat our food in Microwave. We press some buttons to set the timer and type of food.
Finally, we get a hot and delicious meal. The microwave's internal details are hidden from us.
We have been given access to the functionality in a very simple manner.

Access specifiers are the main pillar of implementing abstraction. We can use access specifiers to
enforce restrictions on class members. For example:
• Members declared as public in a class can be accessed from anywhere in the program.
• Members declared as private in a class, can be accessed only from within the class. They are not
allowed to be accessed from any part of the code outside the class.

Advantages of Data Abstraction


• Helps the user to avoid writing the low-level code
• Avoids code duplication and increases reusability.
• Can change the internal implementation of the class independently without affecting the user.
• Helps to increase the security of an application or program as only important details are provided
to the user.
• It reduces the complexity as well as the redundancy of the code, therefore increasing the
readability.

2.2 Layers of abstraction


There are mainly 3 levels of data abstraction:
• Physical or Internal Level
• Logical or Conceptual Level
• View or External Level

2.2.1. Physical or Internal Level


This is the lowest level of data abstraction. It tells us how the data is actually stored in memory.
Access methods like sequential or random access and file organization methods like B+ trees and
hashing are used for the same. Usability, size of memory, and the number of times the records are
factors that we need to know while designing the database. Suppose we need to store the details of
an employee. Blocks of storage and the amount of memory used for these purposes are kept hidden
from the user.

9
2.2.2. Logical or Conceptual Level
This level comprises the information that is actually stored in the database in the form of tables. It
also stores the relationship among the data entities in relatively simple structures. At this level, the
information available to the user at the view level is unknown. We can store the various attributes of
an employee and relationships, e.g. with the manager can also be stored.

2.2.3. View or External Level


This is the highest level of abstraction. Only a part of the actual database is viewed by the users. This
level exists to ease the accessibility of the database by an individual user. Users view data in the form
of rows and columns. Tables and relations are used to store data. Multiple views of the same database
may exist. Users can just view the data and interact with the database, storage and implementation
details are hidden from them.

Example: In the case of storing customer data,


• Physical level – it will contain a block of storage (bytes,GB, TB,etc)
• Logical level – it will contain the fields and the attributes of data.
• View level – it works with CLI or GUI access of database

2.3 Forms of abstraction


1. Data abstraction – This type only shows the required information about the data and hides the
unnecessary data.
2. Control Abstraction – This type only shows the required information about the implementation
and hides unnecessary information.

10
2.4 Abstraction mechanisms
1. Abstraction using Classes
We can implement Abstraction using classes. The class helps us to group data members and
member functions using available access specifiers. A Class can decide which data member will be
visible to the outside world and which is not.

2. Abstraction in Header files


One more type of abstraction can be header files. For example, consider the pow() method present
in math.h header file. Whenever we need to calculate the power of a number, we simply call the
function pow() present in the math.h header file and pass the numbers as arguments without
knowing the underlying algorithm according to which the function is actually calculating the power
of numbers.
3. Abstraction using Access Specifiers
Access specifiers are the main pillar of implementing abstraction. We can use access specifiers to
enforce restrictions on class members. For example:

• Members declared as public in a class can be accessed from anywhere in the program.
• Members declared as private in a class, can be accessed only from within the class.
They are not allowed to be accessed from any part of the code outside the class.

11
MODULE – II

3. CLASSES AND OBJECTS


3.1 Classes and objects
Objects are the building blocks of an OO program. A program that uses OO technology is basically a
collection of objects. To illustrate, let’s consider that a corporate system contains objects that
represent employees of that company. Each of these objects is made up of the data and behavior
described in the following sections

3.2 Object data


The data stored within an object represents the state of the object. In OO programming terminology,
this data is called attributes. In our example, as shown, employee attributes could be Social Security
numbers, date of birth, gender, phone number, and so on. The attributes contain the information that
differentiates between the various objects, in this case, the employees. Attributes are covered in more
detail later in this chapter in the discussion on
classes.

3.3 Object behaviors


The behavior of an object represents what the object can do. In procedural languages, the behavior is
defined by procedures, functions, and subroutines. In OO programming terminology, these behaviors
are contained in methods, and you invoke a method by sending a message to it. In our employee
example, consider that one of the behaviors required of an employee object is to set and return the
values of the various attributes. Thus, each attribute would have corresponding methods, such as
setGender() and getGender() . In this case, when another object needs this information, it can send a
message to an employee object and ask it what its gender is. Not surprisingly, the application of getters
and setters, as with much of object-oriented technology, has evolved since the first edition of this book
was published. This is especially true when in comes to data. Remember that one of the most interesting,
not to mention powerful, advantages of using objects is that the data is part of the package—it is not
separated from the code.
The emergence of XML has not only focused attention on presenting data in a portable manner; it also
has facilitated alternative ways for the code to access the data. In .NET techniques, the getters and
setters are considered properties of the data itself. For example, consider an attribute called Name, using
Java, that looks like the following:
public String Name;

12
The corresponding getter and setter would look like this:
public void setName (String n) {name = n;};
public String getName() {return name;};
Now, when creating an XML attribute called Name, the definition in C# .NET may look something like
this:
Private string strName;
public String Name
{
get
{
return this.strName;
}
set
{
if (value == null) return;
this.strName = value;
}
}
In this approach, the getters and setters are actually properties of the attributes—in this case, Name.
Regardless of the approach, the purpose is the same—controlled access to the attribute.
Note that we are showing only the interface of the methods and not the implementation. The following
information is all the user needs to know to effectively use the methods:
a. The name of the method
b. The parameters passed to the method
c. The return type of the method

In the above figure, the Payroll object contains a method called CalculatePay() that calculates the pay
for a specific employee. Among other information, the Payroll object must obtain the Social Security
number of this employee. To get this information, the payroll object must send a message to the
Employee object (in this case, the getSocialSecurityNumber() method). Basically, this means that the
Payroll object calls the getSocialSecurityNumber() method of the Employee object. The employee
object recognizes the message and returns the requested information.

13
3.4 Creating objects
Classes can be thought of as the templates, or cookie cutters, for objects. A class is used to create an
object.

A class can be thought of as a sort of higher-level data type. For example, just as you create an integer
or a float:
int x;
float y;
you can also create an object by using a predefined class:
myClass myObject;
In this example, the names themselves make it obvious that myClass is the class and myObject is the
object.
Remember that each object has its own attributes (data) and behaviors (functions or routines). A class
defines the attributes and behaviors that all objects created with this class will possess. Classes are
pieces of code. Objects instantiated from classes can be distributed individually or as part of a library.
Because objects are created from classes, it follows that classes must define the basic building blocks
of objects (attributes, behavior, and messages). In short, you must design a class before you can create
an object.
For example, here is a definition of a Person class:
public class Person{
//Attributes
private String name;
private String address;
//Methods
public String getName(){
return name;
}
public void setName(String n){
name = n;
}
public String getAddress(){
return address;
}
public void setAddress(String adr){
address = adr;
}}

14
3.5 Attributes
As you already saw, the data of a class is represented by attributes. Each class must define the attributes
that will store the state of each object instantiated from that class. In the Person class example in the
previous section, the Person class defines attributes for name and address.

3.6 Methods
As you learned earlier in the chapter, methods implement the required behavior of a class. Every object
instantiated from this class has the methods as defined by the class. Methods may implement behaviors
that are called from other objects (messages) or provide the fundamental, internal behavior of the class.
Internal behaviors are private methods that are not accessible by other objects. In the Person class, the
behaviors are getName() , setName() , getAddress() , and setAddress() . These methods allow other
objects to inspect and change the values of the object’s attributes. This is a common technique in OO
systems. In all cases, access to attributes within an object should be controlled by the object itself—no
other object should directly change an attribute of another.

3.7 Messages
Messages are the communication mechanism between objects. For example, when Object A invokes a
method of Object B, Object A sends a message to Object B. Object B’s response is defined by its return
value. Only the public methods, not the private methods, of an object can be invoked by another object.
The following code illustrates this concept:
public class Payroll{
String name;
Person p = new Person();
String = p.setName(“Joe”);
... code
String = p.getName();
}
In this example (assuming that a Payroll object is instantiated), the Payroll object is sending
a message to a Person object, with the purpose of retrieving the name via the getName()
method.

3.8 Creating class diagrams


The purpose of a class diagram is to model the static view of an application. Class diagrams are the only
diagrams that can be directly mapped with object-oriented languages and are thus widely used at the
time of construction.
The purpose of the class diagram can be summarized as −
• Analysis and design of the static view of an application.
• Describe the responsibilities of a system.
• Base for component and deployment diagrams.
• Forward and reverse engineering.

A class represents a concept that encapsulates state (attributes) and behavior (operations). Each attribute
has a type. Each operation has a signature. The class name is the only mandatory information.

15
Class Name:
• The name of the class appears in the first partition.
Class Attributes:
• Attributes are shown in the second partition.
• The attribute type is shown after the colon.
• Attributes map onto member variables (data members) in code.
Class Operations (Methods):
• Operations are shown in the third partition. They are services the class provides.
• The return type of a method is shown after the colon at the end of the method signature.
• The return type of method parameters are shown after the colon following the parameter name.
Operations map onto class methods in code

Class Visibility
The +, - and # symbols before an attribute and operation name in a class denote the visibility of the
attribute and operation.

• + denotes public attributes or operations


• - denotes private attributes or operations
• # denotes protected attributes or operations

16
Parameter Directionality
Each parameter in an operation (method) may be denoted as in, out or inout which specifies its
direction with respect to the caller. This directionality is shown before the parameter name.

Perspectives of Class Diagram


The choice of perspective depends on how far along you are in the development process. During the
formulation of a domain model, for example, you would seldom move past the conceptual
perspective. Analysis models will typically feature a mix of conceptual and specification
perspectives. Design model development will typically start with heavy emphasis on the specification
perspective, and evolve into the implementation perspective.
A diagram can be interpreted from various perspectives:
• Conceptual: represents the concepts in the domain
• Specification: focus is on the interfaces of Abstract Data Type (ADTs) in the software
• Implementation: describes how classes will implement their interfaces
The perspective affects the amount of detail to be supplied and the kinds of relationships worth
presenting. As we mentioned above, the class name is the only mandatory information.

Relationships between classes


UML is not just about pretty pictures. If used correctly, UML precisely conveys how code should be
implemented from diagrams. If precisely interpreted, the implemented code will correctly reflect the
intent of the designer. Can you describe what each of the relationships mean relative to your target
programming language shown in the Figure below?
If you can't yet recognize them, no problem this section is meant to help you to understand UML class
relationships. A class may be involved in one or more relationships with other classes. A relationship
can be one of the following types:

17
Inheritance (or Generalization):
A generalization is a taxonomic relationship between a more general classifier and a more specific
classifier. Each instance of the specific classifier is also an indirect instance of the general classifier.
Thus, the specific classifier inherits the features of the more general classifier.
• Represents an "is-a" relationship.
• An abstract class name is shown in italics.
• SubClass1 and SubClass2 are specializations of SuperClass.
The figure below shows an example of inheritance hierarchy. SubClass1 and SubClass2 are derived
from SuperClass. The relationship is displayed as a solid line with a hollow arrowhead that points from
the child element to the parent element.

Inheritance Example - Shapes


The figure below shows an inheritance example with two styles. Although the connectors are drawn
differently, they are semantically equivalent.

18
Association
Associations are relationships between classes in a UML Class Diagram. They are represented by a
solid line between classes. Associations are typically named using a verb or verb phrase which reflects
the real world problem domain.

Simple Association
• A structural link between two peer classes.
• There is an association between Class1 and Class2
The figure below shows an example of simple association. There is an association that connects the
<<control>> class Class1 and <<boundary>> class Class2. The relationship is displayed as a solid line
connecting the two classes.

Cardinality
Cardinality is expressed in terms of:
• one to one
• one to many
• many to many

19
Aggregation
A special type of association.
• It represents a "part of" relationship.
• Class2 is part of Class1.
• Many instances (denoted by the *) of Class2 can be associated with Class1.
• Objects of Class1 and Class2 have separate lifetimes.
The figure below shows an example of aggregation. The relationship is displayed as a solid line with a
unfilled diamond at the association end, which is connected to the class that represents the aggregate.

Composition
• A special type of aggregation where parts are destroyed when the whole is destroyed.
• Objects of Class2 live and die with Class1.
• Class2 cannot stand by itself.
The figure below shows an example of composition. The relationship is displayed as a solid line with a
filled diamond at the association end, which is connected to the class that represents the whole or
composite.

Dependency
An object of one class might use an object of another class in the code of a method. If the object is not
stored in any field, then this is modeled as a dependency relationship.
• A special type of association.
• Exists between two classes if changes to the definition of one may cause changes to the other
(but not the other way around).
• Class1 depends on Class2
The figure below shows an example of dependency. The relationship is displayed as a dashed line with
an open arrow.

20
The figure below shows another example of dependency. The Person class might have a hasRead
method with a Book parameter that returns true if the person has read the book (perhaps by checking
some database).

Realization
Realization is a relationship between the blueprint class and the object containing its respective
implementation level details. This object is said to realize the blueprint class. In other words, you can
understand this as the relationship between the interface and the implementing class.
For example, the Owner interface might specify methods for acquiring property and disposing of
property. The Person and Corporation classes need to implement these methods, possibly in very
different ways.

Class Diagram Example: Order System

21
3.9 Class Diagram Example: GUI
A class diagram may also have notes attached to classes or relationships.

3.10 Access specifiers

Access specifiers/ modifiers help to restrict the scope of a class, constructor, variable, method, or data
member. It provides security, accessibility, etc to the user depending upon the access modifier used
with the element.

3.11 Accessing members and methods

All variables which are defined in a class are known as instance variables as each object of the class
will have its own copy of the variables. Hence the data in various objects are unique and are separate
from one another.
When declaring variables, there are three Access Level Modifiers. These are:

Access specifiers/ modifiers are keywords that can be used to control the visibility of fields, methods,
and constructors in a class. The four access modifiers in Java are public, protected, default, and private.
Four Types of Access Modifiers
• Private: We can access the private modifier only within the same class and not from outside the
class.
• Default: We can access the default modifier only within the same package and not from outside

22
the package. And also, if we do not specify any access modifier it will automatically consider it
as default.
• Protected: We can access the protected modifier within the same package and also from outside
the package with the help of the child class. If we do not make the child class, we cannot access
it from outside the package. So inheritance is a must for accessing it from outside the package.
• Public: We can access the public modifier from anywhere. We can access public modifiers from
within the class as well as from outside the class and also within the package and outside the
package.
Let us see which all members of Java can be assigned with the access modifiers:

Now let us understand the scope of these access modifiers with the help of a table:

3.11.1 Private Access Modifier

• The private access modifier is specified when any member of a class is prefixed with the private
keyword. In comparison with the other access modifiers, this is the most restricted access
modifier.

• When the methods or data members are prefixed with a private access modifier, the visibility of
these methods and data members are restricted so, they can be accessed only within the same
class where they have been declared, they will not be visible to the outside world.

• If we have another class from the same package still, we will not be able to access these methods
or data members. So usually, we keep the class variables and methods as private, which are
intended to be used inside the same class where declared.

23
Let us consider an example where we will consider two classes A1 and A2 within the same package p1.
We will declare a variable and a method as private in class A1 and then try to access these methods and
variables from class A2.

So here we will Compile Time Error.

Let us see for a private constructor:

If we make any class constructor private, we cannot create the instance of that class from outside the
class, and hence, from here we can conclude that the private access modifier can be accessed
only within the same class and not from outside the class.

3.11.2 Default Access Modifier

• It is not a keyword. Any Java members such as class or methods or data members when not
specified with any access modifier they are by default considered as default access
modifiers. These methods or data members are only accessible within the same package and
they cannot be accessed from outside the package. It provides more visibility than a private access
modifier. However this access modifier is more restricted than protected and public access
modifiers.

Let us consider an example of the default access modifier.

Here, we have two different packages p1 and p2. In the p1 package, we have class A1 where we declare
a default variable and a default method. Now we are trying to access this variable and method from
outside the package that is from package p2 which has a class A2.

When we try to access these variables and methods from outside the package we get a Compile time
error. Hence, we conclude that the default access modifier members can be accessed only within the
same package and cannot be accessed from outside the package. And they have more visibility than
private access modifier but is more restricted than protected and public access modifiers.

3.11.3 Protected Access Modifier

• It is a keyword. This access modifier is used to access the methods or data members of a
class within the same package as well as outside the package but only through inheritance.
The protected access modifier has more accessibility than private and default access modifiers.
But it has less visibility than the public access modifier.

Let us consider an example of a protected access modifier.

Here we have two packages p1 and p2. In package p1 we have class A1 where we have declared a
protected test method. In package p2 we are inheriting the members of class A1 inside class A2 with
the help of extending keywords and creating a relationship between the two classes. We can also say
that class A1 is the parent class or the superclass and class A2 is the child class or the subclass
respectively.

When we inherit the members of class A1 inside class A2, with the help of a protected access
modifier we can access the members of class A1 of package p1 from class A2 of the different package
p2.

24
So here we get the output as Hi I’m from a protected method.

Hence, we can conclude that the methods, variables, and data members of a class prefixed with
a protected access modifier can be accessed within the same package as well as can be accessed
from outside the package but only with the help of inheritance.

3.11.4 Public Access Modifier

It is a keyword. If a class member like variable, method, or data members are prefixed with a public
access modifier, then they can be accessed from anywhere inside the program. That is, they can be
accessed within the same class as well as from outside the different classes.

It also includes access within the same package and also from outside the package. The members like
variables, methods, and other data members can be accessed globally.

Using public access modifiers we can provide access to the members most simply. There are no
restrictions on public access modifier members. Hence, it has the widest accessibility or visibility scope
as compared to the rest of the access modifiers.

Let us now consider an example of public access modifier.

Here in this example, we have two different packages p1 and p2. In p1 we have a class a1 where we
have declared a variable and a method prefixed public keyword. And in the p2 package, we have a class
A2 from where we are trying to access the members of class A1 without inheritance.

Here we get the output as 10 and Hi I’m from the public method.

So from the above example, we can conclude that public access modifier members can be accessed
from anywhere, within the same class as well as from outside the class. And also can be accessed within
the same package and also from outside a package.

Example:
Here are examples of access modifiers in Java:
// Public access modifier
public class PublicClass {
public int publicField;
public void publicMethod() {
// code here
}
}
// Protected access modifier
protected class ProtectedClass {
protected int protectedField;
protected void protectedMethod() {
// code here
}
}
// Default (package-private) access modifier
class DefaultClass {

25
int defaultField;
void defaultMethod() {
// code here
}
}
// Private access modifier
class PrivateClass {
private int privateField;
private void privateMethod() {
// code here
}
}

3.12 Static members


Static data members are class members that are declared using static keywords. A static member has
certain special characteristics which are as follows:

• Only one copy of that member is created for the entire class and is shared by all the objects of
that class, no matter how many objects are created.
• It is initialized before any object of this class is created, even before the main starts.
• It is visible only within the class, but its lifetime is the entire program.

Syntax:
static data_type data_member_name;
// C++ Program to demonstrate the working of static data member
#include <iostream>
using namespace std;

class A {
public:
A()
{
cout << "A's Constructor Called " <<
endl;
}
};

class B {
static A a;

public:
B()
{
cout << "B's Constructor Called " <<
endl;
}
};

26
// Driver code
int main()
{
B b;
return 0;
}

Accessing a Static Member


As told earlier, the static members are only declared in the class declaration. If we try to access the
static data member without an explicit definition, the compiler will give an error.
// C++ Program to demonstrate
// the Compilation Error occurred
// due to violation of Static
// Data Memeber Rule
#include <iostream>
using namespace std;

class A {
int x;

public:
A()
{
cout << "A's constructor called " <<
endl;
}
};

class B {
static A a;

public:
B()
{
cout << "B's constructor called " <<
endl;
}
static A getA()
{
return a;
}
};

// Driver code
int main()
{

27
B b;
A a = b.getA();
return 0;
}

Output
Compiler Error: undefined reference to `B::a'

3.13 Access Static Members Without Any Object


We can access any static member without any object by using the scope resolution operator directly
with the class name.
// C++ Program to demonstrate
// static members can be accessed
// without any object
#include <iostream>
using namespace std;

class A {
int x;

public:
A()
{
cout << "A's constructor called " <<
endl;
}
};

class B {
static A a;

public:
B()
{
cout << "B's constructor called " <<
endl;
}
static A getA()
{
return a;
}
};

// Definition of a
A B::a;

// Driver code
int main()

28
{
// static member 'a' is accessed
// without any object of B
A a = B::getA();

return 0;
}

Output
A's constructor called

3.14 Static methods

The static keyword is used to construct methods that will exist regardless of whether or not any instances
of the class are generated. Any method that uses the static keyword is referred to as a static method.

Features of static method:


• A static method in Java is a method that is part of a class rather than an instance of that class.
• Every instance of a class has access to the method.
• Static methods have access to class variables (static variables) without using the class’s object
(instance).
• Only static data may be accessed by a static method. It is unable to access data that is not static
(instance variables).
• In both static and non-static methods, static methods can be accessed directly.

Syntax to declare the static method:

Access_modifier static void methodName()

// Method body.

Syntax to call a static method:

className.methodName();

Restrictions in Static Methods:


1. Non-static data members or non-static methods cannot be used by static methods, and static
methods cannot call non-static methods directly.
2. In a static environment, this and super aren’t allowed to be used.

29
MODULE – III

4. SPECIAL MEMBER FUNCTIONS AND OVERLOADING

4.1 Constructors and destructors


A constructor is a member function of a class that has the same name as the class name. It helps to
initialize the object of a class. It can either accept the arguments or not. It is used to allocate the memory
to an object of the class. It is called whenever an instance of the class is created. It can be defined
manually with arguments or without arguments. There can be many constructors in a class. It can be
overloaded but it can not be inherited or virtual. There is a concept of copy constructor which is used
to initialize an object from another object.
Syntax:

ClassName()
{
//Constructor's Body
}
Destructor:
Like a constructor, Destructor is also a member function of a class that has the same name as the class
name preceded by a tilde(~) operator. It helps to deallocate the memory of an object. It is called while
the object of the class is freed or deleted. In a class, there is always a single destructor without any
parameters so it can’t be overloaded. It is always called in the reverse order of the constructor. if a class
is inherited by another class and both the classes have a destructor then the destructor of the child class
is called first, followed by the destructor of the parent or base class.
Syntax:

~ClassName()
{
//Destructor's Body
}
Note: If we do not specify any access modifiers for the members inside the class then by default the
access modifier for the members will be Private.

Difference between Constructor and Destructor


S.
Constructor Destructor
No.
1. Constructor helps to initialize the object of a Whereas destructor is used to destroy the
class. instances.
2. It is declared as className( arguments if any Whereas it is declared as ~ className( no
){Constructor’s Body }. arguments ){ }.
3. Constructor can either accept arguments or While it can’t have any arguments.
not.
4. A constructor is called when an instance or It is called while object of the class is freed or
object of a class is created. deleted.
5. Constructor is used to allocate the memory to While it is used to deallocate the memory of
an instance or object. an object of a class.

30
6. Constructor can be overloaded. While it can’t be overloaded.
7. 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.
8. In a class, there can be multiple constructors.
While in a class, there is always a single
destructor.
9. There is a concept of copy constructor which Here, there is no copy-destructor concept.
is used to initialize an object from another
object.
10. They are often called in successive order. They are often called in reverse order of
constructor.

4.2 Need for constructors and destructors

The purpose of a constructor is to construct an object and assign values to the object's members. A
constructor takes the same name as the class to which it belongs and does not return any values.
Destructors are usually used to deallocate memory and do other cleanup for a class object and its class
members when the object is destroyed. A destructor is called for a class object when that object passes
out of scope or is explicitly deleted.

4.3 Types of Constructors

There are 3 types of constructors. They are:


• Default Constructor
• Parameterized Constructor
• Copy Constructor

4.3.1 Copy constructors


A copy constructor is a member function that initializes an object using another object of the same
class. In simple terms, a constructor that 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.

Copy constructor takes a reference to an object of the same class as an argument.

Sample(Sample &t)
{
id=t.id;
}
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.
The copy constructor can be defined explicitly by the programmer. If the programmer does not define
the copy constructor, the compiler does it for us.

31
Characteristics of Copy Constructor
1. The copy constructor is used to initialize the members of a newly created object by copying the
members of an already existing object.

2. Copy constructor takes a reference to an object of the same class as an argument.

Sample(Sample &t)
{
id=t.id;
}
3. The process of initializing members of an object through a copy constructor is known as copy
initialization.

4. 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.

5. The copy constructor can be defined explicitly by the programmer. If the programmer does not
define the copy constructor, the compiler does it for us.

Types of Copy Constructors:

1. Default Copy Constructor


An implicitly defined copy constructor will copy the bases and members of an object in the same
order that a constructor would initialize the bases and members of the object.

2. User Defined Copy Constructor


A user-defined copy constructor is generally needed when an object owns pointers or non-shareable
references, such as to a file, in which case a destructor and an assignment operator should also be
written.

4.3.2 Dynamic constructors


The constructor that allocates a block of memory that can be accessed by the objects at run time is
known as Dynamic Constructor.

In simple terms, a Dynamic constructor is used to dynamically initialize the objects, that is memory is
allocated at run time.
We will dynamically allocate memory to the data members inside the default constructor of class A as
well as a parameterized constructor of class A and check the output.
#include <iostream>
using namespace std;
class A
{
int *value;
public:
A()//Default constructor
{
value = new int; //Memory allocation at run time

32
*value = 1729;
}
A(int p_value) //Parameterised constructor
{
value = new int; //Memory allocation at run time
*value= p_value+1;
}
void display()
{
cout<< *value <<endl;
}
~A()
{
delete value ;
}
};
int main()
{
A obj1, obj2(7225);
cout<<"The value of object obj1 is: ";
obj1.display();// Calling default constructor
cout<<"\nThe value of object 0bj2 is: ";
obj2.display();// calling parameterised constructor
return 0;
}

Output:

The value of object obj1 is: 1729


The value of object obj2 is: 7226

4.3.3 Parameterized constructors


Parameterized constructors help to create objects with states defined by the programmer. Objects can
be initialized with the default constructor or by a parameterized constructor. Initializing objects with
parameterized constructors requires the same number and order of arguments to be passed by the user
concerning the parameterized constructor being used. The objects created by using parameterized
constructors can be unique with different data member values or states. One can have any number of
parameterized constructors in a class. The parameterized constructors differ in terms of the parameters
they hold. The compiler would not create a default constructor if the programmer creates their own
constructor.
In the below given parameterized constructor in Java example, three constructors are implemented: one
is the default constructor and the other two are parameterized constructors.

During the initialization of an object, which constructor should get invoked depends upon the
parameters one passes. For example when we create object like namesClass n1=new
namesClass("Krishna"); then the new keyword invokes parameterized constructor with string parameter
(namesClass(String)) after object initialization.

33
public class studentDetails {
// Default constructor created by programmer

studentDetails(){
System.out.println("Default constructor");
}

/* The compiler would not create default constructor


* in this case as user has created his own
* parameterized constructors
*/

/* Parameterized constructor with


* one String argument
*/
private String n1;
studentDetails(String name){
this.n1=name;
System.out.println("Parameterized constructor with one String argument.\n"+"Name:
"+n1);
}

/* Parameterized constructor with


* one string and one integer argument
*/
private int n2;
studentDetails(String name, int age){
this.n1=name;
this.n2=age;
System.out.println("Parameterized constructor with one string and one integer
argument.\n"+"Name:"+n1+" Age:"+n2);
}

public static void main(String[] args) {

//Invoking default constructor


studentDetails s1 = new studentDetails();

//Parameterized constructor with one String parameter.


studentDetails s2 = new studentDetails("Krishna Das");

//Parameterized constructor with one String and one integer parameter.


studentDetails s3 = new studentDetails("Pawan Singhania", 21);
}
}

Output
Default constructor

34
Parameterized constructor one String argument. Name: Krishna Das
Parameterized constructor with one string and one integer argument.
Name:Pawan Singhania Age:21

4.4 Destructors with static members


Static data members are NOT destroyed when an object’s destructor is called. Keep in mind that a
destructor cleans up a specific object (instance) of the class, but that has nothing to do with static data
members of the class.

Think of static members as being shared across all objects (instances) of the class. Only one copy of a
static member exists, no matter how many objects (instances) you have created. Static members exist,
even if no objects of the class have been created. Static members are part of the class but are not bound
to individual class members.

The lifetime (or storage duration) of static members is, well, static. The storage for a static member is
allocated when the program begins and is deallocated when the program ends, just as static global
variables are. That’s what is meant by static storage duration.

Now, if you define the static member as thread_local, then there is one per thread, springing into
existence when the thread starts, and ceasing to exist with the thread terminates. But the static member
is still independent of the number of object instances, and has nothing to do with the object destructor
being called.

4.5 Virtual destructors


Deleting a derived class object using a pointer of base class type that has a non-virtual destructor result
in undefined behavior. To correct this situation, the base class should be defined with a virtual
destructor. As a guideline, any time you have a virtual function in a class, you should immediately add
a virtual destructor (even if it does nothing).
// A program with virtual destructor
#include <iostream>
using namespace std;
class base {
public:
base()
{ cout << "Constructing base\n"; }
virtual ~base()
{ cout << "Destructing base\n"; }
};

class derived : public base {


public:
derived()
{ cout << "Constructing derived\n"; }
~derived()
{ cout << "Destructing derived\n"; }
};

int main()

35
{
derived *d = new derived();
base *b = d;
delete b;
getchar();
return 0;
}
Output
Constructing base

36

You might also like