[go: up one dir, main page]

0% found this document useful (0 votes)
11 views16 pages

Oops_notes -Unit 1

The document provides an overview of Object-Oriented Programming (OOP) concepts in C++, including its features such as classes, objects, inheritance, polymorphism, and encapsulation. It discusses the structure of C++ programs, data types, tokens, constructors, and destructors, highlighting their roles and functionalities. Additionally, it emphasizes the importance of constructors and destructors in resource management and memory allocation.

Uploaded by

vedantkhaire21
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)
11 views16 pages

Oops_notes -Unit 1

The document provides an overview of Object-Oriented Programming (OOP) concepts in C++, including its features such as classes, objects, inheritance, polymorphism, and encapsulation. It discusses the structure of C++ programs, data types, tokens, constructors, and destructors, highlighting their roles and functionalities. Additionally, it emphasizes the importance of constructors and destructors in resource management and memory allocation.

Uploaded by

vedantkhaire21
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/ 16

DR.

BABASAHEB AMBEDKAR TECHNOLOGICAL


UNIVERSITY, LONERE-RAIGAD
Department of Computer Engineering
B.Tech. First Year A.Y.-2023-2024
Semester: - II (Even) Course Code:
Subject: - Object-Oriented Programming in C++
Subject Co-ordinator: -Ms. Shweta N. Tembe

UNIT 1: Introduction to Object Oriented Programming and Objects and


Classes: Need of object-oriented programming, the object-oriented approach, Characteristics of
object-oriented languages, class, Objects as data types, Constructors and Destructor, Objects as
function arguments, Returning objects.

Introduction to C++:
 C++ is an object-Oriented programming language. Initially named ‘C with Classes’, C++
was developed by Bjarne Stroustrup at AT&T Bell Laboratories in New Jersey, USA,
on the early eighties.
 C++ is an extension of C with a major addition of the class construct feature of
SIMULA67.
 C++ is a superset of C. Most of what we already know about C applies to C++ also.
Therefore, almost all C programs are also C++ programs with slight modifications.
 The most important facilities that C++ adds on to C are classes, objects, inheritance,
function overloading, and operator overloading. These features enable us to create
abstract data types, inherit properties from existing data types and support polymorphism,
thus making C++ a truly object-Oriented Language.
 The Object-Oriented features in C++ allow programmers to build large programs with
clarity, extensibility and ease of maintenance, incorporating the spirit and efficiency of C.

Features of Object-Oriented Programming (OOPs):-


The following are the some of the features to know extensively about the Object-Oriented
Programming.
1) Objects 2) Classes 3) Encapsulation 4) Inheritance 5) Multiple inheritance 6) Polymorphism
7) Message Passing 8) Data Abstraction 9) Dynamic Binding

1) Object:
 Objects are the basic run-time entities in an Object-Oriented system. They may represent
a person, a place, a bank account, a table of data or any item that the program must
handle.
 Object is a collection of number of entities. Objects take up space in the memory.
 Objects are instances of classes. When a program is executed , the objects interact by
sending messages to one another. Each object contains data and code to manipulate the
data.
 Objects can interact without having known details of each other’s data or code.
 An object is considered to be a partitioned area of computer memory that stores data and
set of operations that can access that data.
2) Class:
 It is an abstract data type that contains data members and member functions that
operates on data. It starts with the keyword class.
 The entire set of data and code of an object can be made a user-defined data type with
the help of a CLASS.
 Objects are variables to type class. Once a class has been defined, we can create any
number of objects belonging to that class.
3) Encapsulation:
 The wrapping of data and functions into a single unit is known as Encapsulation. The
data is not accessible to the outside world and only those functions which are wrapped in
the class can access it. These functions provides an interface between object’s data and
the program. This insulation of the data from direct access by the program is called data
hiding.
4) Inheritance:
 Inheritance is the process by which objects of one class acquire the properties of objects
of another class.
 That is, deriving a new class from existing class. Here new class is called derived class
where as existing class is called base class.
 In OOP, the concept of inheritance provides the idea of reusability. This means that we
can add additional features to an existing class without modifying it.
 This is possible by deriving a new class from the existing one. The new class will have
the combined features of both the classes.
5) Multiple Inheritance:
 The mechanism by which a class is derived from more than one base class is known as
multiple inheritance.
6) Polymorphism:
 Polymorphism is another important OOP concept.
 Polymorphism means the ability to take more than one form.
 For example, an operation may exhibit different behavior ion different instances. The
behavior depends upon the types of data used in the operation.
 Function overloading and operator overloading are the examples of polymorphism.
7) Message Passing:
 An Object-Oriented program consists of a objects that communicate with each other.
 Objects communicates with one another by sending and receiving information much the
same way as people pass messages to one another.
 A message for an object is a request for execution of a procedure, and therefore will
invoke a function in the receiving object that generates the desired result.
 Message passing involves specifying the name of the object, the name of the function and
the information to be sent.
 Objects have a life cycle. They can be created and destroyed.
8) Data Abstraction:
 Abstraction refers to the act of representing essential features without including the
background details or explanation. Since the classes use the concept of data abstraction,
they are known as Abstract Data Types (ADTs).
9) Dynamic Binding:
 Binding refers to the linking of a procedure call to the code to be executed in response to
the call. Dynamic binding means that the code associated with it given procedure call is
not known until the time of the call at run time. It is associated with Polymorphism and
Inheritance. A function call associated with a polymorphic reference depends on the
dynamic type of that reference.

Structure of C program. Explain the structure or layout of C++ Program.


A typical C++ program would contain four sections as shown below.
They are: 1) Include files section 2) Class declaration section 3) Member function definition
section 4) Main() program section
INCLUDE FILES
CLASS DECLARATION
MEMBER FUNCTIONS DEFINITIONS
MAIN FUNCTION PROGRAM
Include files: In this section we can include all header files which supports C++ Program. For
example #include, #include, #include are the header files.
Class Declaration: In this section we will declare the class which holds data and member
functions.
Member function definition: In this section we will define all the member functions which are
declared in the class. Using Class name followed by :: (scope resolution operator) followed by
function name we will define the member function.
Main() program:
o Each and every C++ Program execution starts from main().
o Each and every member function is called from main ()
o We will create object of the class in main ().

Sample Program:
#include
void main ()
{
cout<<” welcome”<<endl;
cout<<”C++”<<endl;
}

Data Types:-
In C++, data types are used to define the type of data that a variable can store. This helps the
compiler to allocate memory and check type compatibility. C++ is a strongly typed language,
meaning each variable must be declared with a data type before it is used.
1. Built-in (Primitive) Data Types
These are the fundamental data types provided by C++:
Data Type Description Example
int Integer values int age = 25;
float Single precision decimal values float pi = 3.14;
double Double precision decimal values double d = 3.1415;
char Single character char grade = 'A';
bool Boolean values (true/false) bool flag = true;
void Represents absence of type Used for functions that return nothing

2. Derived Data Types


Derived data types are built using fundamental types:
 Arrays → Collection of elements of same type
int arr[5];
 Pointers → Store memory address of another variable
int* ptr = &x;
 Functions → Group of reusable statements
int sum(int a, int b);
 References → Alias for an existing variable
int& ref = original;

3. User-defined Data Types


Used to create custom types that combine variables of different types:
 Structure (struct)
A collection of variables of different types:
struct Student {
int rollNo;
char name[50];
};
 Class (class)
Blueprint for objects in Object-Oriented Programming.
 Union (union)
Shares memory between variables to save space.
 Enumeration (enum)
Defines a set of named integer constants:
enum Color { RED, GREEN, BLUE };

4. Type Modifiers
Modifiers alter the meaning of basic data types in terms of size or sign.
Modifier Description Example
signed Can hold both positive & negative signed int x;
unsigned Holds only positive values unsigned int y;
short Reduces size of int short int a;
long Increases size of int/double long double z;
C++ Tokens:-
In C++, tokens are the smallest units of a program that the compiler understands. A C++
program is made up of different tokens which are the building blocks of the source code.
🔸 Definition:
A token is the smallest element of a C++ program that has a meaningful interpretation by the
compiler.

✅ Types of Tokens in C++


There are 6 main types of tokens in C++:
Token Type Description
1. Keywords Reserved words with special meaning
2. Identifiers Names used for variables, functions, classes
3. Literals / Constants Fixed values (e.g., numbers, characters)
4. Operators Symbols that perform operations
5. Punctuators / Separators Symbols to separate code elements
6. Comments Notes ignored by the compiler

1. Keywords
 Reserved words predefined by the C++ language.
 Cannot be used as variable or function names.
 Examples:
int, float, if, else, while, return, class, public, private
📌 Example:
int main() {
return 0;
}
Here, int and return are keywords.

🔹 2. Identifiers
 Names given to variables, functions, arrays, classes, etc.
 Must follow naming rules:
o Start with a letter or underscore _
o Can contain letters, digits, and underscores
o Case-sensitive
o Cannot use keywords as identifiers
📌 Example:
int totalMarks;
float average;
Here, totalMarks and average are identifiers.

🔹 3. Literals (Constants)
 Fixed values that do not change during execution.
 Types:
o Integer Literals: 10, -5
o Floating-point Literals: 3.14, -0.001
o Character Literals: 'A', 'z'
o String Literals: "Hello", "C++"
o Boolean Literals: true, false
📌 Example:
int a = 10; // 10 is an integer literal
char grade = 'A'; // 'A' is a character literal

🔹 4. Operators
 Perform operations on variables and values.
 Categories:
o Arithmetic Operators: +, -, *, /, %
o Relational Operators: ==, !=, <, >, <=, >=
o Logical Operators: &&, ||, !
o Assignment Operators: =, +=, -=
o Increment/Decrement: ++, --
o Bitwise Operators: &, |, ^, ~, <<, >>
📌 Example:
int sum = a + b;
Here, = and + are operators.

🔹 5. Punctuators (Separators)
 Used to separate statements or group code elements.
 Examples:
o ; → Statement terminator
o , → Separator
o { } → Block of code
o () → Function call or grouping
o [] → Array indexing
📌 Example:
int a = 5, b = 10;
Here, ; and , are punctuators.

🔹 6. Comments
 Used to add notes or explanations in code.
 Ignored by the compiler.
 Types:
o Single-line comment: // comment
o Multi-line comment: /* comment */
📌 Example:
// This is a single-line comment
/*
This is a
multi-line comment
*/

Constructor in C++: -
🔹 Definition:
A constructor is a special member function of a class that is automatically invoked when an
object of the class is created. It is used to initialize the data members of the class.

🔸 Key Characteristics of Constructors:


 Has same name as the class.
 No return type, not even void.
 Automatically called when an object is created.
 Can be overloaded (i.e., multiple constructors in one class).
📌 Syntax Example:
class Student {
public:
Student() { // Constructor
cout << "Constructor called!" << endl;
}
};

✅ Types of Constructors in C++


C++ supports several types of constructors based on how they are defined and used:

🔹 1. Default Constructor
A constructor that takes no parameters.
📌 Used to assign default values to data members.
class Student {
public:
Student() { // Default constructor
cout << "Default Constructor called!" << endl;
}
};
Automatically provided by compiler if no constructor is defined.
Default Constructor (Compiler-Defined vs User-Defined)
 Compiler-defined: Automatically created if no constructor is provided.
 User-defined: Created by the programmer explicitly.

🔹 2. Parameterized Constructor
A constructor that accepts arguments to initialize data members with user-defined values.
class Student {
int roll;
public:
Student(int r) { // Parameterized constructor
roll = r;
cout << "Roll number: " << roll << endl;
}
};
🔹 3. Copy Constructor
A constructor that creates a copy of an existing object.
📌 Used when an object is initialized from another object of the same class.
class Student {
int roll;
public:
Student(int r) {
roll = r;
}
Student(const Student &s) { // Copy constructor
roll = s.roll;
}
};

🔹 4. Dynamic Constructor
Uses dynamic memory allocation (like new operator) in a constructor.
class Demo {
int* ptr;
public:
Demo(int size) {
ptr = new int[size]; // Allocating memory dynamically
}
};
Used for objects that manage memory or resources.

🔹 5. Constructor Overloading
You can define multiple constructors with different parameter lists.
class Student {
public:
Student() {
cout << "Default Constructor" << endl;
}
Student(int id) {
cout << "Parameterized Constructor: " << id << endl;
}
};
🔁 Based on the arguments, the appropriate constructor is called.

Summary Table
Type Description
Default Constructor No parameters; initializes default values
Parameterized Takes arguments to initialize objects
Copy Constructor Copies data from another object
Dynamic Constructor Allocates memory dynamically
Type Description
Constructor Overload Multiple constructors with different args

Destructor in C++:-
🔹 Definition:
A destructor is a special member function in a class that is automatically invoked when an
object goes out of scope or is explicitly deleted. It is used to release resources that the object
may have acquired during its lifetime (like memory, file handles, etc.).

🔸 Syntax of Destructor:
 Has the same name as the class preceded by a tilde (~).
 Takes no parameters and returns nothing.
 Cannot be overloaded (i.e., only one destructor per class).
📌 Example:
class Demo {
public:
Demo() {
cout << "Constructor called" << endl;
}

~Demo() {
cout << "Destructor called" << endl;
}
};

✅ When is a Destructor Called?


 Automatically called when an object is destroyed.
 For:
o Local (stack) objects → at the end of scope.
o Dynamically created objects → when delete is used.

🔸 Use of Destructor:
 To free dynamically allocated memory.
 To close open files.
 To release network or database connections.
 To perform cleanup tasks before object deletion.
🔁 If you allocate memory using new in a constructor, you should release it using delete in the
destructor.

🌟 Why Are Destructors Important?


Destructors play a critical role in resource management. Here's why:
✅ 1. Automatic Cleanup
 Destructors ensure that any resources used by an object (memory, files, sockets, etc.) are
automatically released when the object goes out of scope.
✅ 2. Prevent Memory Leaks
 If memory is allocated dynamically (new), but not properly deallocated (delete), it causes
memory leaks.
 Destructors help prevent such leaks by freeing memory when the object is destroyed.
✅ 3. File Handling
 If a file is opened in a constructor, it should be closed in the destructor to avoid resource
exhaustion.
✅ 4. Object Lifecycle Management
 Destructors make it easy to manage the complete lifecycle of an object, especially in
large applications or when working with dynamic memory.

🔹 Example with Dynamic Memory:


class Student {
int* marks;
public:
Student() {
marks = new int[5]; // dynamic allocation
cout << "Constructor: Memory allocated" << endl;
}

~Student() {
delete[] marks; // freeing memory
cout << "Destructor: Memory deallocated" << endl;
}
};
Benefits & Applications of Object-oriented programming language: -
🧠 Benefits of Object-Oriented Programming (OOP):-
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of
"objects", which contain data and functions. OOP improves software design by promoting
modularity, reusability, and scalability.

✅ 1. Modularity
 Programs are divided into small, manageable units (classes).
 Easier to test, debug, and maintain.
📌 Example: Each class in a library (e.g., Bank, Customer) can be developed and tested
separately.

✅ 2. Reusability
 Once a class is written, it can be reused in other programs using inheritance.
 Reduces code duplication and development time.
📌 Example: A base class Vehicle can be inherited by Car, Bike, Bus, etc.
✅ 3. Data Abstraction
 Hides unnecessary details and shows only essential features.
 Implemented using access specifiers like private, public, and protected.
📌 Example: A Car object provides a start() method, but hides how the engine works.

✅ 4. Encapsulation
 Binds data and methods together in a single unit (class).
 Protects data from unauthorized access.
📌 Example: Set and get methods control access to private variables.

✅ 5. Inheritance
 Enables code reusability by allowing a new class to acquire properties and behavior of an
existing class.
📌 Example: Employee class inherited by Manager, Developer.

✅ 6. Polymorphism
 Allows objects to be treated in many forms: compile-time (function overloading) and
runtime (function overriding).
📌 Example: A draw() function that works for both Circle and Rectangle objects.

✅ 7. Maintainability
 Easier to manage, update, and scale OOP-based programs.
 Modular design simplifies bug fixes and feature enhancements.

✅ 8. Scalability and Flexibility


 OOP makes programs scalable by adding new classes without affecting existing code.
 Promotes flexibility in program design.

Applications of Object-Oriented Programming


OOP is widely used in various fields and industries due to its robustness and scalability.

🔹 1. Software Development
 Used in building desktop, web, and mobile applications.
 Languages: C++, Java, Python, C#, etc.
📌 Example: Inventory management systems, HR management systems.

🔹 2. Game Development
 OOP helps manage game objects like players, enemies, weapons, etc.
 Promotes reuse and complex interaction modeling.
📌 Example: Unity (C#), Unreal Engine (C++).

🔹 3. Graphical User Interfaces (GUI)


 GUI elements like buttons, menus, windows are objects.
 Easy to create reusable components.
📌 Example: Java Swing, .NET Windows Forms.

🔹 4. Web Development
 Backend frameworks use OOP for building scalable applications.
📌 Example: Django (Python), Laravel (PHP), Spring Boot (Java).

🔹 5. Real-Time Systems
 OOP supports complex systems like real-time monitoring, sensor-based applications.
📌 Example: ATM systems, flight control systems.

🔹 6. Simulation and Modeling


 Simulate real-world behaviors using objects.
📌 Example: Hospital management systems, traffic simulations.

🔹 7. Artificial Intelligence & Machine Learning


 Organizing AI agents and algorithms as objects improves modularity and reusability.

Concept of returning objects from functions with C++ Program.


In C++, functions can return objects just like they return basic data types (e.g., int, float, char).
This allows you to:
 Return an object with specific values.
 Use one object to create another.
 Chain object operations.

✅ Why Return an Object?


 To pass object data from one function to another.
 To build new objects dynamically based on logic.
 To support function chaining (used in libraries and frameworks).

💡 Basic Syntax Example:


ClassName functionName() {
ClassName obj;
// some operations
return obj; // returning object
}

C++ Program: Returning an Object from a Function


#include <iostream>
using namespace std;

class Complex {
float real, imag;

public:
// Method to set values
void setData(float r, float i) {
real = r;
imag = i;
}

// Method to display values


void display() {
cout << "Real: " << real << ", Imaginary: " << imag << endl;
}

// Function that returns an object


Complex add(Complex c) {
Complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp; // returning object
}
};
int main() {
Complex c1, c2, result;

c1.setData(2.5, 3.5);
c2.setData(1.5, 2.5);

// Calling function and storing returned object


result = c1.add(c2);

cout << "Sum of complex numbers: ";


result.display();

return 0;
}
🔍 Output:
Sum of complex numbers: Real: 4, Imaginary: 6
✨ Explanation:
 add() is a function that takes a Complex object and returns another Complex object.
 Inside add(), a new object temp is created to hold the sum.
 The function returns the temp object.
 In main(), the result is stored in result and then displayed.

You might also like