Oops_notes -Unit 1
Oops_notes -Unit 1
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.
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.
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
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.
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.
🔹 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;
}
};
🔸 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.
~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.
🔹 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++).
🔹 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.
class Complex {
float real, imag;
public:
// Method to set values
void setData(float r, float i) {
real = r;
imag = i;
}
c1.setData(2.5, 3.5);
c2.setData(1.5, 2.5);
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.