0% found this document useful (0 votes)
7 views26 pages

Unit 2

Turning Point is a comprehensive guide for GATE CSE preparation, semester exams, and placement assistance, offering resources such as study materials, mock tests, and expert mentorship. The guide emphasizes the importance of community engagement through platforms like Telegram and social media for discussions and updates. It covers key concepts in Object-Oriented Programming, including I/O processing, object characteristics, class diagrams, and access modifiers.

Uploaded by

2810aryansh0
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)
7 views26 pages

Unit 2

Turning Point is a comprehensive guide for GATE CSE preparation, semester exams, and placement assistance, offering resources such as study materials, mock tests, and expert mentorship. The guide emphasizes the importance of community engagement through platforms like Telegram and social media for discussions and updates. It covers key concepts in Object-Oriented Programming, including I/O processing, object characteristics, class diagrams, and access modifiers.

Uploaded by

2810aryansh0
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/ 26

Turning Point – Your Ultimate Guide for GATE CSE, Semester Exams &

Placements

Welcome to Turning Point by Ankush Saklecha, your one-stop destination for GATE CSE
preparation, semester exams, and placement guidance. Stay connected with us across various
platforms for expert mentorship, study materials, and career guidance.

� GATE CSE | Semester Exams | Placement Preparation


 GATE CSE – High-quality content, previous year questions, mock tests & expert strategies.
 Semester Exams – Conceptual clarity, important topics, and subject-wise revision.
 Placement Preparation – Coding practice, aptitude, technical & HR interview guidance.

�Get everything you need to excel in academics and secure top placements!

� Download the Turning Point App


Access GATE CSE, semester, and placement preparation resources in one place.
�Download Now: Turning Point App

� Join Our Telegram Community


�Telegram Group: Join Now (Discuss doubts, strategies & placement tips)
�Telegram Channel: Follow Updates (Get study materials, exam notifications & job updates)

�Join our Telegram Group for interactive discussions and quick solutions to your doubts.

� Connect with Us on Social Media


Stay updated with study materials, placement preparation tips, and special announcements
by following us:

�Facebook: Turning Point with Ankush Saklecha


�Instagram: Follow Us (Daily motivation, study hacks & live sessions)
�LinkedIn: Connect with Ankush Saklecha (Professional updates & industry insights)

�Follow us on Instagram, LinkedIn, and YouTube for exclusive content and live updates.

� Stay Updated & Get Placed!


✔ Join our Telegram Group for GATE CSE & Placement discussions.
✔ Follow us on Instagram & LinkedIn for career tips & updates.
✔ Subscribe to our YouTube Channel for coding & interview guidance.
✔ Download the Turning Point App for structured learning & career growth.

�Prepare for GATE, semester exams, and placements with the best resources. Stay connected,
stay ahead!

Unit II

Q1. What is I/O Processing in OOP?


I/O (Input/Output) Processing in OOP refers to handling input from users, files,
or devices and outputting data to screens, files, or networks using objects and
streams.

OOP languages like C++, Java, and Python use I/O streams to handle input and
output efficiently.
Q2. What are I/O Streams?
Definition:

An I/O stream is a sequence of bytes or characters used to read input or write


output.

Types of I/O Streams in OOP:

Type Description Example


Input Reads data from a source (keyboard, file, cin in C++, Scanner in
Stream network) Java
Output Writes data to a destination (screen, file, cout in C++, System.out
Stream printer) in Java
File Stream Reads/writes data from/to files ifstream, ofstream in C++

IO Streams in C++

C++ offers a well-defined stream-based IO system in the <iostream> library. Here


are the main components:

a) Standard IO Stream Classes:

 istream and ostream:

 istream is used for input operations.


 ostream is used for output operations.

 iostream:
 Inherits from both istream and ostream for simultaneous input and
output.
b) Commonly Used Objects:

 cin: Standard input stream (an object of istream).


 cout: Standard output stream (an object of ostream).

IO Streams in Java

Java's IO system is based on streams as well, but it uses a different class hierarchy
found in the java.io package.

a) Byte Streams vs. Character Streams:

 Byte Streams:

 Used for raw binary data.


 Classes include InputStream and OutputStream.

 Character Streams:

 Designed for handling character data.


 Classes include Reader and Writer.

Advantages of I/O Streams in OOP

 Efficient Data Handling: Reads and writes large data efficiently.


 Flexibility: Can work with console, files, and network data.
 Encapsulation of Data: Streams hide low-level complexities of I/O
processing.
Q3. What are Objects and its Characteristics
with the help of examples?

In Object-Oriented Programming (OOP), an object is a fundamental unit that


represents a real-world entity. Each object has three characteristics:

1. State (Attributes/Data)
2. Behavior (Methods/Functions)
3. Identity (Unique Existence)

State of an Object

The state of an object refers to the data or attributes that define its current
condition. The state changes when the values of its attributes are modified.

Example: Consider an object Car.

class Car {
public:
string brand;
string color;
int speed;
};

Here, the state of the Car object is defined by:

 brand (Toyota, Honda, Ford)


 color (Red, Blue, Black)
 speed (60 km/h, 80 km/h, etc.)

Changing State:
Car c1;
c1.brand = "Toyota";
c1.color = "Red";
c1.speed = 60;
Now, c1 has the state: Brand = Toyota, Color = Red, Speed = 60.

Behavior of an Object
The behavior of an object refers to the methods (functions) that define what
actions the object can perform.

Example:

Continuing with the Car class, we can define behaviors like accelerate() and
brake().

class Car {
public:
string brand;
int speed;

void accelerate(int increase) {


speed += increase;
cout << brand << " accelerated. New Speed: " << speed << " km/h" << endl;
}

void brake(int decrease) {


speed -= decrease;
cout << brand << " slowed down. New Speed: " << speed << " km/h" <<
endl;
}
};
int main() {
Car c1;
c1.brand = "Toyota";
c1.speed = 50;

c1.accelerate(20); // Behavior: Increases speed


c1.brake(10); // Behavior: Decreases speed
return 0;
}

Identity of an Object
Definition:

The identity of an object is a unique identifier that distinguishes it from other


objects, even if they have the same state and behavior.

Each object in OOP has a unique memory location or ID.

Car car1;
Car car2;

Even if car1 and car2 have the same state (brand, color, speed), they are different
objects stored at different memory locations.

Identity in C++ (Using Pointers)

#include <iostream>
using namespace std;

class Car {
public:
string brand;
Car(string b) { brand = b; }
};

int main() {
Car car1("Toyota");
Car car2("Toyota");

cout << "Car1 Memory Address: " << &car1 << endl;
cout << "Car2 Memory Address: " << &car2 << endl;

return 0;
}

Summary of Object Characteristics

Characteristic Definition Example


Data that defines an object's
State Car: Brand = Toyota, Speed = 60
properties
Functions that define object
Behavior Car: accelerate(), brake()
actions
Unique existence of an object Different memory addresses for
Identity
in memory car1 and car2

Q.4) Discuss the elements of class diagram with


the help of an example.
Elements of a Class Diagram

A Class Diagram is a structural diagram in UML (Unified Modeling Language)


that visually represents the structure of a system by showing its classes, attributes,
methods, relationships, and access specifiers. It is mainly used for object-
oriented design and analysis.

Elements of a Class Diagram

1. Class:
 Represents a blueprint for objects.
 Depicted as a rectangle with three compartments:
1. Class Name (at the top)
2. Attributes (in the middle)
3. Methods/Operations (at the bottom)
2. Attributes (Properties/Fields):
 Define the characteristics of a class.
 Example: name, age, salary in a Person class.
3. Methods (Operations/Functions):
 Define the behavior of a class.
 Example: getSalary(), setAge() in a Person class.
4. Access Specifiers (Visibility Modifiers):
o Control access to attributes and methods:
 + (Public) → Accessible everywhere
 - (Private) → Accessible only within the class
 # (Protected) → Accessible within the class and its
subclasses
5. Relationships:
 Association (↔) → A relationship between two classes (e.g., a
"Teacher teaches a Student").
 Multiplicity (1..*, 0..1) → Defines the number of instances (e.g., one
teacher can teach multiple students).
 Aggregation (○--) → Weak relationship (e.g., A "Department"
consists of multiple "Professors").
 Composition (◆--) → Strong relationship (e.g., A "Car" has an
"Engine" that cannot exist separately).
 Inheritance (Generalization) (▸|—) → Represents parent-child
relationships.
Q5. What is Association? Explain the various
forms of Association.
Association in UML Class Diagrams

Association in UML (Unified Modeling Language) represents a relationship


between two or more classes that interact with each other. It shows how objects of
one class are related to objects of another class.

Forms of Association

1. One-to-One (1:1) Association


 Each instance of Class A is associated with only one instance of Class
B and vice versa.
 Example: A Person has one Passport.
 Representation:
Person 1 --------- 1 Passport

2. One-to-Many (1:M) Association


 One instance of Class A is associated with multiple instances of Class B.
 Example: A Teacher can teach multiple Students, but each student has
only one teacher.
 Representation:
Teacher 1 --------- * Student
3. Many-to-Many (M:N) Association
 Multiple instances of Class A are associated with multiple instances of Class
B.
 Example: A Student can enroll in multiple Courses, and each Course can
have multiple Students.
 Representation:
Student * --------- * Course

Special Types of Association


1. Aggregation (Weak Association)
 A "whole-part" relationship where the part can exist independently of
the whole.
 Example: A Department consists of multiple Professors, but a
Professor can exist independently.
 Notation: Hollow diamond (○--)
 Representation:
Department ○-- * Professor

car object is an aggregation of engine, seat, wheels and other objects.


2. Composition (Strong Association)
 A "whole-part" relationship where the part cannot exist
independently of the whole.
 Example: A Car has an Engine, and the Engine cannot exist without
the Car. ―heart is part of body‖
 Notation: Filled diamond (◆--)
 Representation:
Car ◆-- 1 Engine
#include <iostream>
using namespace std;
// Engine class (Part)
class Engine {
public:
void start() {
cout<< "Engine started" <<endl;
}
};
// Car class (Whole) - Aggregation
class Car {
private:
Engine* engine; // Aggregation (Car has an Engine but doesn't own it)
public:
// Constructor takes an existing Engine object
Car(Engine* eng) {
engine = eng;
}
void startCar() {
cout<< "Car is starting..." <<endl;
engine->start(); // Using Engine's method
}
};

int main() {
Engine eng; // Engine exists independently
Car myCar(&eng); // Aggregation: Car uses Engine but doesn’t own it
myCar.startCar(); // Car starts using the Engine
return 0;
}

Q6. What are Access Modifiers?


Access Modifiers are keywords used in OOP to control the accessibility of class
members (attributes and methods). They define which parts of the program
can access or modify data inside a class.

Types of Access Modifiers in C++ and Java

Access Access Accessible in Accessible in Accessible


Modifier Level Same Class? Derived Class? Outside Class?
private Restricted Yes No No
protected Limited Yes Yes No
public Open Yes Yes Yes

#include <iostream>
using namespace std;
class Person {
private:
string name; // Private: Not accessible outside the class
protected:
int age; // Protected: Accessible in derived classes
public:
void setName(string n) { name = n; } // Public function
void display() { cout << "Name: " << name << ", Age: " << age << endl; }
};
// Derived Class
class Student : public Person {
public:
void setAge(int a) { age = a; } // Accessing protected member
};

int main() {
Student s;
s.setName("John"); // Allowed (public method)
s.setAge(20); // Allowed (protected variable accessible in derived class)
s.display();
return 0;
}

 Private: Only accessible within the class.


 Protected: Accessible in the class and subclasses.
 Public: Accessible everywhere.

Using access modifiers ensures data security, encapsulation, and controlled


access in OOP.
Q7. What are Static Members in a Class?
Static members are shared across all objects of a class. Unlike instance members,
static members belong to the class itself, not to individual objects.

Types of Static Members:

1. Static Data Members (variables shared among all objects)


2. Static Member Functions (functions that operate on static data)

Static Data Members


A static data member is a class variable that is shared by all objects of the class.
It is initialized only once and has a single memory location.

Key Features:

 Declared using the static keyword.


 Memory is allocated only once, at class level.
 It is shared among all objects of the class.
 Must be defined outside the class.

#include <iostream>
using namespace std;
class Student {
private:
static int count; // Static data member (shared by all objects)
public:
Student() { count++; } // Increment count when a new object is created
static void showCount() { // Static function to access static member
cout << "Total Students: " << count << endl;
}
};
// Definition of static member outside the class
int Student::count = 0;
int main() {
Student s1, s2, s3;
Student::showCount(); // Accessing static function
return 0;
}

Static Member Functions


Definition:

A static member function is a function that can access only static data members.
It does not operate on object-specific data.

Key Features:

 Declared using the static keyword.


 Can only access static data members (not instance variables).
 Can be called using the class name (ClassName::FunctionName()).

#include <iostream>
using namespace std;
class Counter {
private:
static int value; // Static data member
public:
static void increment() { // Static function
value++;
cout << "Counter Value: " << value << endl;
}
};
// Define static member outside class
int Counter::value = 0;
int main() {
Counter::increment(); // Calling static function without object
Counter::increment();
return 0;
}

Differences Between Static and Non-Static Members


Non-Static
Feature Static Members
Members
Memory Allocation Allocated once at class level Allocated per object
Accessed using Accessed using
Access Method
ClassName::FunctionName() object instance
Can Modify Instance
No Yes
Variables?
Unique for each
Scope Shared among all objects
object

When to Use Static Members?


 To store global counters (e.g., tracking object count).
 To implement utility functions (e.g., mathematical calculations, logging).
 To share configuration settings across objects.
Q8. What is Message Passing?
Message passing is the mechanism by which objects communicate with each
other in an Object-Oriented system. Instead of directly modifying another object’s
data, one object sends a message (a function call) to another object requesting
an action.

Message Passing Mechanism

1. Object Creation – Objects are instantiated from a class.


2. Sending a Message – One object calls a method on another object.
3. Receiving a Message – The receiving object executes the requested method.
4. Returning a Response – If needed, the receiver returns data to the sender.
#include <iostream>
using namespace std;
// Class definition
class Car {
public:
void startEngine() { // Message receiver
cout << "Engine started." << endl;
}
};
int main() {
Car myCar; // Object creation
myCar.startEngine(); // Sending a message (method call)
return 0;
}

Q9. Compare aggregation and inheritance. Write


down the properties of aggregation.

Comparison of Aggregation and Inheritance

1. Definition:
 Aggregation: It is a type of association where one object "has a"
relationship with another object. It represents a "whole-part" relationship
where the part can exist independently of the whole. It is a more flexible,
loosely coupled relationship compared to inheritance.
 Inheritance: It represents an "is-a" relationship where a subclass inherits the
properties and behaviors of a superclass. Inheritance is tightly coupled
because the subclass depends on the superclass for its functionality.
2. Type of Relationship:
 Aggregation: A "has-a" relationship. For example, a Car has an Engine.
The Engine can exist without the Car.
 Inheritance: An "is-a" relationship. For example, a Dog is a Mammal. The
Dog inherits all attributes and behaviors of the Mammal.
3. Dependency:

 Aggregation: The lifetime of the part does not depend on the lifetime of the
whole. For example, if a Team object contains multiple Player objects, the
Player objects can exist independently of the Team.
 Inheritance: The lifetime of the subclass is dependent on the superclass. If a
Dog is a subclass of Animal, the Dog cannot exist without the concept of
Animal.
4. Reusability:

 Aggregation: It promotes reuse of components because objects can be


shared between other objects. For instance, an Engine object can be used in
multiple Car objects.
 Inheritance: It promotes reuse of code but creates a dependency between
the parent and child class.
5. Flexibility:
 Aggregation: More flexible because the contained objects (parts) can be
changed or replaced without affecting the container object (whole).
 Inheritance: Less flexible because changing the superclass can affect all
subclasses that inherit from it.

Properties of Aggregation:

1. "Has-a" Relationship:
 Aggregation expresses a "whole-part" relationship where the whole
can exist independently of the parts. For example, a Library has
many Books, but the Books can exist even without the Library.
2. Independent Existence:
 The objects involved in aggregation can exist independently of each
other. For instance, a Department can contain many Employee
objects, but the Employees exist independently and are not
necessarily bound to a specific Department.
3. No Ownership:
 The whole does not own the part. In aggregation, a part can be shared
by multiple objects. For example, multiple Cars can use the same
Engine.
4. Loose Coupling:
 Aggregation represents a loose coupling between the whole and part
objects, meaning they can interact but are not strongly dependent on
one another.
5. Life Cycle Independence:
 The lifespan of the part object is not dependent on the lifespan of the
whole. When the whole object is destroyed, the part object can still
exist.
6. Refers to Collection:
 Aggregation typically represents a collection of objects, where one
object contains a set of other objects, often with a common theme. For
example, a Team can aggregate many Players, but the Players are
not tightly bound to the Team.

You might also like