KEMBAR78
Oops Unit 1 | PDF | Object Oriented Programming | Integer (Computer Science)
0% found this document useful (0 votes)
8 views12 pages

Oops Unit 1

Uploaded by

aviy82405
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)
8 views12 pages

Oops Unit 1

Uploaded by

aviy82405
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/ 12

Introduction to C++

Object-Oriented Technology (OOT)


Object-Oriented Technology (OOT) is a programming paradigm based on the
concept of "objects,". It is widely used in software development due to
its modularity, reusability, and scalability.

Key Concepts of OOT


• Class – A blueprint for creating objects.
• Object – An instance of a class with specific values.
• Encapsulation – Hiding data and restricting direct access to it.
• Abstraction – Showing only essential details while hiding
complexity.
• Inheritance – Allowing new classes to derive properties from
existing classes.
• Polymorphism – Enabling a function or method to have multiple
implementations.

Advantages of Object-Oriented Programming (OOP)


• Modularity – Code is organized into self-contained objects,
making it easier to manage and maintain.
• Reusability – Inheritance allows code reuse, reducing
redundancy and improving efficiency.
• Scalability – OOP enables easy extension of existing code,
making software scalable.
• Maintainability – Encapsulation and modularity make debugging
and modification more manageable.
• Security – Data hiding restricts unauthorized access, ensuring
better security.
• Flexibility – Polymorphism allows using the same interface for
different data types.
• Code Efficiency – Reduces complexity by structuring the code in
a logical and reusable manner.

Input and Output in C++


C++ uses the iostream library to handle input and output operations.
The two primary objects for I/O are:
• cin → Standard input (used to take input from the user)
• cout → Standard output (used to display output)
• getline(cin, stringVariable) → Input a string with spaces.
#include <iostream>
#include <string>
using namespace std;

int main() {
string fullName;
int age;
cout << "Enter your full name: ";
getline(cin, fullName); // Reads full name including spaces

cout << "Enter your age: ";


cin >> age; // Takes integer input

cout << "Hello, " << fullName << "! You are " << age << "
years old." << endl;

return 0;
}

Tokens
A token is the smallest unit in a C++ program. The compiler recognizes
tokens while parsing the code.

Types of Tokens in C++


• Keywords
• Identifiers
• Literals (Constants)
• Operators
• Punctuators (Special Characters)

Keywords (Reserved Words)


Keywords in C++ are reserved words that have special meanings and
cannot be used as identifiers (variable names, function names, etc.).
Example : int, float, if, else, return, class, public, private, etc.

There are 95 keywords in C++.


alignas alignof and and_eq asm auto bitand bitor bool break
char16 char32 concep
case catch char char8_t class compl const
_t _t t
constex const_cas contin co_awa co_yie declty
consteval constinit co_return default
pr t ue it ld pe
dynamic_c
delete do double else enum explicit export extern false
ast
mutabl
float for friend goto if inline int long namespace
e
noexcep nullpt operat privat
new not not_eq or or_eq protected
t r or e
registe reinterpret_c static_ass
public requires return short signed sizeof static
r ast ert
static_ca synchroni templa thread_lo
struct switch this throw true try
st zed te cal
unsign volati
typedef typeid typename union using virtual void wchar_t
ed le
while xor xor_eq
Identifiers:
An identifier is the name used for variables, functions, arrays,
classes, objects, etc. in C++.
Rules for Naming Identifiers in C++
• Must begin with a letter (A-Z or a-z) or an underscore (_).
• Can contain letters (A-Z, a-z), digits (0-9), and underscores (_).
• Cannot be a C++ keyword (e.g., int, return, class, etc.).
• Cannot contain special characters (@, #, $, %, &, etc.).
• Case-sensitive (MyVar and myvar are different).
• No spaces allowed (use _ or camelCase instead).
Valid and Invalid Identifiers in C++

Identifier Valid/Invalid? Reason


age Valid Simple variable name
_count Valid Underscore at the beginning is allowed
totalMarks Valid Camel case is allowed
sum_123 Valid Contains letters, digits, and underscore
9score Invalid Cannot start with a digit
class Invalid class is a C++ keyword
my-variable Invalid - (hyphen) is not allowed
price@cost Invalid Special character @ not allowed
int Invalid int is a C++ keyword
first name Invalid Contains a space

Literals (Constants)
Literals are fixed values in a program.
Types:
• Integer literals → 10, 200, -50
• Floating-point literals → 3.14, 2.71
• Character literals → 'A', 'z'
• String literals → "Hello", "C++"
• Boolean literals → true, false

Operators
Operators are symbols that perform operations on variables and values.
Examples:
Type Examples
Arithmetic +, -, *, /, %
Relational ==, !=, >, <, >=, <=
Logical &&, `
Bitwise &, `
Assignment =, +=, -=, *=, /=, %=
Punctuators (Special Symbols)
Punctuators are special characters used in C++ syntax.
Examples :
Punctuator Usage
{} Block of code (Curly Braces)
; Statement terminator
() Function parameters
[] Array declaration
, Separator
"" String delimiter

#include <iostream>
#include <string>
using namespace std;

int main() {
string fullName;
int age;

cout << "Enter your full name: ";


getline(cin, fullName); // Reads full name including spaces

cout << "Enter your age: ";


cin >> age; // Takes integer input

cout << "Hello, " << fullName << "! You are " << age << "
years old." << endl;

return 0;
}
Breaking the Program into Tokens
Category Tokens Found
Keywords using, namespace, int, return
std, main, fullName, age, cout, cin, getline,
Identifiers
endl
"Enter your full name: ", "Enter your age: ",
Literals
"Hello, ", "! You are ", " years old."
Operators =, >>, <<
Punctuators {}, ;, (), ,, < >
Fundamental Data Types (Built-in)
These are the basic data types available in C++:
Data Size
Description Example
Type (Typical)
int Stores integers int x = 10; 4 bytes
Stores floating-point numbers
float float pi = 3.14; 4 bytes
(single precision)
Stores floating-point numbers double e =
double 8 bytes
(double precision) 2.71828;
Stores single characters
char char grade = 'A'; 1 byte
(enclosed in single quotes)
Stores Boolean values (true or bool isPassed =
bool 1 byte
false) true;
Represents an absence of type
void
void (used for functions that return N/A
functionName();
nothing)

Integer Types (int, short, long, long long)


• Used for storing whole numbers (positive and negative).
Data Size
Range
Type (bytes)
int 4 -2,147,483,648 to 2,147,483,647
short 2 -32,768 to 32,767
Depends on system (at least -2,147,483,648
long 4 or 8
to 2,147,483,647)
long -9,223,372,036,854,775,808 to
8
long 9,223,372,036,854,775,807

Example:
#include <iostream>
using namespace std;

int main() {
int a = 10;
short b = 32767;
long c = 1000000;
long long d = 12345678901234;

cout << "int: " << a << endl;


cout<<" sizeof(int): "<<sizeof(int)<<endl;
cout << "short: " << b << endl;
cout<<" sizeof(short): "<<sizeof(short)<<endl;
cout << "long: " << c << endl;
cout<<" sizeof(long): "<<sizeof(long)<<endl;
cout << "long long: " << d << endl;
cout<<" sizeof(long long): "<<sizeof(long long)<<endl;
return 0;
}

Floating-Point Types (float, double, long double)


• Used for storing decimal numbers.
Data Type Size (bytes) Precision
float 4 6–7 decimal digits
double 8 15–16 decimal digits
long double 10, 12, or 16 More precision than double

Example:
#include<iostream>
using namespace std;

int main() {
float pi = 3.14159f;
double e = 2.718281828459;
long double precisionValue = 1.234567890123456789L;

cout << "Float: " << pi << endl;


cout << "Float size : "<<sizeof(float)<<endl;
cout << "Double: " << e << endl;
cout << "Double size : "<<sizeof(double)<<endl;
cout << "Long Double: " << precisionValue << endl;
cout << "Long Double size : "<<sizeof(long double)<<endl;

return 0;
}

Floating-point numbers in C and C++ follow the IEEE 754 standard,


which defines how the 32-bit (float) and 64-bit (double)
floating-point numbers are stored and processed in memory.
A 32-bit float is divided into three parts:
Bit Size
Component Purpose
Range (bits)
Indicates positive
[31] Sign Bit 1 bit
(0) or negative (1)
Stores exponent
[30:23] Exponent 8 bits (biased
representation)
Stores the
Mantissa
[22:0] 23 bits significant digits
(Fraction)
of the number
Total = 1 + 8 + 23 = 32 bits

A floating-point number is stored using the formula:


𝑉𝑎𝑙𝑢𝑒 = (−1)𝑆𝑖𝑔𝑛 𝐵𝑖𝑡 × 1. 𝑀𝑎𝑛𝑡𝑖𝑠𝑠𝑎 × 2(𝐸𝑥𝑝𝑜𝑛𝑒𝑛𝑡 − 𝐵𝑖𝑎𝑠)
where:
• Sign Bit (S): 0 for positive, 1 for negative.
• Exponent (E): Stored as an 8-bit biased exponent. The bias is
127.
𝐴𝑐𝑡𝑢𝑎𝑙 𝑒𝑥𝑝𝑜𝑛𝑒𝑛𝑡 = 𝐸 − 127
• Mantissa (M): Stored in normalized form (implicit leading 1).
1. 𝑀𝑎𝑛𝑡𝑖𝑠𝑠𝑎(𝑖𝑛 𝑏𝑖𝑛𝑎𝑟𝑦)
Step 1: Convert to Binary
• First, convert 13.625 to binary:
• Integer part 13 in binary → 1101
• Fraction part 0.625 in binary → 0.101
o Combined: 13.62510 = 1101.1012
Step 2: Normalize the Binary Number (scientific notation)
𝟏. 𝟏𝟎𝟏𝟏𝟎𝟏 × 𝟐𝟑
• Mantissa = 101101 (drop leading 1, store only the fraction
part).
• Exponent = 3 (since we moved the decimal 3 places left).
Step 3: Encode Components
• Sign Bit = 0 (positive number).
• Exponent = 3 + 127 = 130 = 10000010 (in binary).
• Mantissa = 10110100000000000000000 (fill up to 23 bits).
Final IEEE 754 Representation
0 10000010 10110100000000000000000

Derived Data Types in C++


• Derived data types are built using fundamental (primitive) data
types.
• The size of derived data types depends on their structure, the
data members they contain, and the system architecture.
Derived
Description Example Size (Typical)
Data Type
A collection of sizeof(type) * number
int arr[5] =
elements of the same of elements
Array {1, 2, 3, 4,
type stored in (e.g., int arr[5]; →
5};
contiguous memory. 4 * 5 = 20 bytes)
Stores the memory
4 bytes (32-bit)
Pointer address of another int *ptr = &x;
8 bytes (64-bit)
variable.
Same as original
An alias for an
Reference int &ref = x; variable (internally
existing variable.
acts like a pointer)
int sum(int a, N/A (Functions don’t
A reusable block of
int b) { have a size, but
Function code that performs a
return a + b; function pointers do:
specific task.
} 4 or 8 bytes)
Groups related struct Student Sum of member sizes
Structure
variables of different { int id; char (with padding)
(struct)
types into one unit. name[50]; }; (e.g., struct Sample
Derived
Description Example Size (Typical)
Data Type
{ int a; char b; }; →
8 bytes)
A blueprint for
class Car {
objects, supporting Sum of member sizes
Class public: string
encapsulation, (plus vtable pointer
(class) brand; int
inheritance, and for polymorphism)
speed; };
polymorphism.
A special type where union Data { Size of the largest
Union
all members share the int i; double member _(e.g., double
(union)
same memory location. d; }; → 8 bytes)

User-Defined Data Types in C++


• User-defined data types are custom data structures created by
the programmer using fundamental or derived types.
User-Defined
Description Example Size
Data Type
Groups variables of struct Student
struct Sum of member sizes
different data types { int id; char
(Structure) (with padding)
into a single unit. name[50]; };
Encapsulates data Sum of member sizes
class Car {
and methods, (plus vtable
public: string
class supporting Object- pointer if
brand; int
Oriented Programming polymorphism is
speed; };
(OOP). used)
Similar to struct,
union Data {
but members share Size of the largest
union int i; double
the same memory member
d; };
location.
Defines a set of enum Color { Typically 4 bytes
enum
named integral Red, Green, (same as int, but
(Enumeration)
constants. Blue }; can be changed)
typedef
typedef (Type Creates an alias for Same as the
unsigned long
Definition) an existing type. original type
int ULI;
using ULI =
using (Type Modern alternative Same as the
unsigned long
Alias) to typedef. original type
int;
Type Modifiers:
• In C++, type modifiers are keywords used to modify the
fundamental data types
• They can affect the size, the range of values a variable can
hold, or how the variable behaves in a program.

Common Type Modifiers in C++

Modifier Description
Allows both negative and positive values (default for most
signed
types).
unsigned Only allows non-negative values (0 and positive).
short Uses less memory (typically 2 bytes).
long Uses more memory (typically 4 or 8 bytes).
long
Even longer range (typically 8 bytes).
long
const Makes a variable read-only after initialization.
Tells the compiler not to optimize the variable (useful in
volatile
multi-threading or hardware access).
Allows a class member to be modified even if it's part of a
mutable
const object.

#include <iostream>
using namespace std;

// Example class demonstrating 'mutable' and 'const'


class Example {
private:
mutable int counter; // Can be modified even in const methods
const int id=5; // Constant member (must be initialized)
public:
// Simple constructor (assigning values inside the constructor body)
Example(int x) {
counter = 0; // Allowed (mutable)
//id = x; // ERROR: Cannot assign to const after declaration
}

// Const member function (cannot modify non-mutable members)


void show() const {
counter++; // Allowed because 'counter' is mutable
cout << "ID: " << id << ", Counter: " << counter << endl;
}
};

int main() {
// ===== TYPE MODIFIERS =====
signed int a = -10; // Can hold negative values (default for 'int')
unsigned int b = 100; // Only non-negative (larger positive range)
short int c = 32767; // Typically 16-bit (smaller range)
long int d = 123456789L;// Larger than int
long long e = 1LL << 40;// Very large integers

cout << "===== Type Modifiers =====" << endl;


cout << "Signed int (a): " << a << endl;
cout << "Unsigned int (b): " << b << endl;
cout << "Short int (c): " << c << endl;
cout << "Long int (d): " << d << endl;
cout << "Long long (e): " << e << endl;

// ===== CONST MODIFIER =====


const float PI = 3.14159f; // Value cannot be changed
// PI = 3.14; // Error: Assignment to const variable

cout << "\n===== Const Modifier =====" << endl;


cout << "PI: " << PI << endl;

// ===== MUTABLE MODIFIER (in class) =====


Example obj(5);
cout << "\n===== Mutable Modifier =====" << endl;
obj.show();
obj.show();

return 0;
}

Output:
===== Type Modifiers =====
Signed int (a): -10
Unsigned int (b): 100
Short int (c): 32767
Long int (d): 123456789
Long long (e): 1099511627776

===== Const Modifier =====


PI: 3.14159

===== Mutable Modifier =====


ID: 5, Counter: 1
ID: 5, Counter: 2

Typecasing :
• Type casting is the process of converting a variable from one
data type to another.
• C++ supports several types of casting:

Implicit (Automatic) Type Conversion :


• Done automatically by the compiler when compatible types are
mixed.
Example:
#include <iostream>
using namespace std;

int main() {
// Variables of different data types
int intNum = 10;
float floatNum = 5.5f;
double doubleNum = 7.8;
char charVal = 'A'; // ASCII value of 'A' is 65

// Implicit type casting examples


float result1 = intNum + floatNum; // int → float
double result2 = floatNum + doubleNum; // float → double
int result3 = charVal + intNum; // char → int (ASCII conversion)
double result4 = intNum + doubleNum; // int → double

// Display results
cout << "int + float → float: " << result1 << endl; // 15.5
cout << "float + double → double: " << result2 << endl; // 13.3
cout << "char + int → int: " << result3 << endl; // 75 (65 + 10)
cout << "int + double → double: " << result4 << endl; // 17.8

return 0;
}
Explicit Type Conversion (C-Style Casting):
• Forces conversion using (type)variable syntax.
Example:
double d = 10.5;
int num = (int)d; // Explicitly converts double to int (truncates decimal)

C++ Style Casting (Better & Safer):


• C++ introduces four specific casting operators for better type
safety:
• static_cast
• dynamic_cast
• const_cast
• reinterpret_cast

Constants :
• Constants are variables whose values cannot be modified after
initialization.
• constants must be initialized when they are declared.
const int MAX_USERS = 100; // Correct: initialized at declaration
const double PI = 3.14159; // Correct: initialized at declaration
// const int x; // Error: must be initialized!

#include <iostream>
using namespace std;

int main() {
const float pi = 3.14; // 'pi' is a constant and can't be changed
int radius = 5;
float area = pi * radius * radius;

cout << "Radius: " << radius << endl;


cout << "Area of circle: " << area << endl;

// pi = 3.14159;
// This will cause a compile-time error (you can't change a const variable)

return 0;
}

Operator precedence table (C):

go through this link to get more details of operators in C:


https://www.gecsheikhpura.org.in/wp-
content/uploads/sites/18/2024/11/file_674347a87bbdd.pdf

You might also like