0% found this document useful (0 votes)
8 views

UNIT 1 OOPS NOTES (1)

Uploaded by

fervor0205
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

UNIT 1 OOPS NOTES (1)

Uploaded by

fervor0205
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

UNIT-1 OOPS

TYPES OPERATORS AND EXPRESSIONS


In C++, operators are special symbols that perform operations on operands. These operators
are categorized into several types:

1. Arithmetic Operators

 Addition (+): Adds two operands. Example: a + b


 Subtraction (-): Subtracts the second operand from the first. Example: a - b
 Multiplication (*): Multiplies two operands. Example: a * b
 Division (/): Divides the first operand by the second. Example: a / b
 Modulus (%): Returns the remainder of a division. Example: a % b
 Increment (++): Increases the value of an operand by 1. Example: ++a or a++
 Decrement (--): Decreases the value of an operand by 1. Example: --a or a--

2. Relational Operators

 Equal to (==): Checks if two operands are equal. Example: a == b


 Not equal to (!=): Checks if two operands are not equal. Example: a != b
 Greater than (>): Checks if the first operand is greater than the second. Example: a
> b
 Less than (<): Checks if the first operand is less than the second. Example: a < b
 Greater than or equal to (>=): Checks if the first operand is greater than or equal to
the second. Example: a >= b
 Less than or equal to (<=): Checks if the first operand is less than or equal to the
second. Example: a <= b

3. Logical Operators

 Logical AND (&&): Returns true if both operands are true. Example: a && b
 Logical OR (||): Returns true if at least one of the operands is true. Example: a || b
 Logical NOT (!): Reverses the logical state of its operand. Example: !a

4. Bitwise Operators

 Bitwise AND (&): Performs a binary AND operation. Example: a & b


 Bitwise OR (|): Performs a binary OR operation. Example: a | b
 Bitwise XOR (^): Performs a binary XOR operation. Example: a ^ b
 Bitwise NOT (~): Inverts all the bits of the operand. Example: ~a
 Left Shift (<<): Shifts the bits of the first operand left by the number of positions
specified by the second operand. Example: a << 2
 Right Shift (>>): Shifts the bits of the first operand right by the number of positions
specified by the second operand. Example: a >> 2

5. Assignment Operators
 Assignment (=): Assigns the value of the right operand to the left operand. Example:
a = b
 Add and assign (+=): Adds the right operand to the left operand and assigns the result
to the left operand. Example: a += b
 Subtract and assign (-=): Subtracts the right operand from the left operand and
assigns the result to the left operand. Example: a -= b
 Multiply and assign (*=): Multiplies the right operand with the left operand and
assigns the result to the left operand. Example: a *= b
 Divide and assign (/=): Divides the left operand by the right operand and assigns the
result to the left operand. Example: a /= b
 Modulus and assign (%=): Takes the modulus of the left operand by the right operand
and assigns the result to the left operand. Example: a %= b

6. Conditional (Ternary) Operator

 Ternary (?:): Evaluates a condition and returns one of two values based on whether
the condition is true or false. Example: condition ? expr1 : expr2

7. Comma Operator

 Comma (,): Allows two expressions to be evaluated in a single statement. Example:


a = (b = 3, b + 2)

8. Sizeof Operator

 Sizeof (sizeof): Returns the size, in bytes, of its operand. Example: sizeof(int)

9. Pointer Operators

 Address-of (&): Returns the address of the operand. Example: &a


 Dereference (*): Returns the value at the address of the operand. Example: *ptr

10. Member Access Operators

 Dot (.): Accesses a member of a structure or class. Example: object.member


 Arrow (->): Accesses a member of a structure or class through a pointer. Example:
ptr->member

11. Type Casting Operators

 C-style Cast: (type) expression


 Static Cast (static_cast<type>)
 Dynamic Cast (dynamic_cast<type>)
 Const Cast (const_cast<type>)
 Reinterpret Cast (reinterpret_cast<type>)

These operators allow C++ programmers to perform a wide variety of operations, from basic
arithmetic to complex bitwise manipulation.
4o

You said:

UNARY,BINARY,TERNARY AND SPECIAL CASE OPERATORS IN C++


ChatGPT said:

ChatGPT

In C++, operators can be classified based on the number of operands they operate on:

1. Unary Operators

Unary operators operate on a single operand. They perform operations like


incrementing/decrementing a value, inverting a boolean value, etc.

 Unary plus (+): Indicates a positive value. Example: +a


 Unary minus (-): Negates the value. Example: -a
 Increment (++): Increases the value of the operand by 1.
o Pre-increment: ++a (increments a before using its value)
o Post-increment: a++ (uses the value of a and then increments it)
 Decrement (--): Decreases the value of the operand by 1.
o Pre-decrement: --a (decrements a before using its value)
o Post-decrement: a-- (uses the value of a and then decrements it)
 Logical NOT (!): Inverts the boolean value of the operand. Example: !a
 Bitwise NOT (~): Inverts all the bits of the operand. Example: ~a
 Address-of (&): Returns the memory address of the operand. Example: &a
 Dereference (*): Returns the value at the address of the operand (pointer). Example:
*ptr
 Sizeof (sizeof): Returns the size, in bytes, of the operand. Example: sizeof(int)
 Type cast: Converts a value from one type to another. Example: (int)a

2. Binary Operators

Binary operators operate on two operands and include most of the arithmetic, logical,
relational, and bitwise operators.

 Arithmetic Operators: +, -, *, /, %
 Relational Operators: ==, !=, >, <, >=, <=
 Logical Operators: &&, ||
 Bitwise Operators: &, |, ^, <<, >>
 Assignment Operators: =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
 Member Access Operators:
o Dot (.): Accesses a member of an object. Example: object.member
o Arrow (->): Accesses a member of an object through a pointer. Example:
ptr->member
 Comma Operator (,): Evaluates two expressions from left to right and returns the
value of the second expression. Example: a = (b = 3, b + 2)
3. Ternary Operator

The ternary operator operates on three operands. It is a shorthand for an if-else statement
and is also known as the conditional operator.

 Ternary Operator (?:):


o Syntax: condition ? expr1 : expr2
o If the condition is true, expr1 is evaluated and returned; otherwise, expr2 is
evaluated and returned.
o Example: int result = (a > b) ? a : b; (returns a if a > b, otherwise
returns b)

4. Special Case Operators

These operators don't strictly fall into the unary, binary, or ternary categories but are special
in their behavior.

 Sizeof Operator (sizeof): Returns the size of a data type or object in bytes.
Example: sizeof(int) returns the size of an int.
 Pointer Operators:
o Address-of (&): Returns the memory address of the operand. Example: int
*ptr = &a;
o Dereference (*): Accesses the value stored at the memory address of the
operand. Example: int value = *ptr;
 Type Casting Operators:
o Static Cast (static_cast<type>): Converts between compatible types.
Example: static_cast<int>(3.14)
o Dynamic Cast (dynamic_cast<type>): Safely converts pointers/references to
classes, used primarily with polymorphism. Example:
dynamic_cast<Derived*>(basePtr)
o Const Cast (const_cast<type>): Adds or removes the const qualifier.
Example: const_cast<int&>(constInt)
o Reinterpret Cast (reinterpret_cast<type>): Converts between any pointer
types. Example: reinterpret_cast<int*>(ptr)
 Scope Resolution Operator (::): Used to define the context in which a member
(variable, function) is defined. Example: std::cout, ClassName::memberFunction
 Member Pointer Operator (.* and ->*): Used to access a member of an object
through a pointer to a member.
o Example: ptr_to_member->*pointer_to_member_function

These operators are fundamental in C++ and are used in a wide range of programming tasks,
from simple calculations to complex logic and data manipulation.

SCOPE AND LIFETIME


n C++, the concepts of scope and lifetime are fundamental to understanding how variables
and objects behave during the execution of a program. Let's explore each concept in detail.
1. Scope

Scope refers to the region of the code where a variable, function, or object is accessible and
can be used. In C++, there are different types of scopes:

a) Local Scope (Block Scope)

 Definition: Variables declared inside a block {} have a local scope. They are accessible only
within that block.
 Example:

cpp
Copy code
void func() {
int x = 10; // x has local scope within this function
if (x > 5) {
int y = 20; // y has local scope within this if-block
}
// y is not accessible here
}
// x is not accessible here

 Behavior: Once the block is exited, variables within that block are destroyed and are no
longer accessible.

b) Function Scope

 Definition: The scope of labels (used in goto statements) is the entire function where they
are declared.
 Example:

cpp
Copy code
void func() {
int x = 10;
label:
x++;
if (x < 15) goto label; // label is accessible throughout the
function
}
c) Global Scope

 Definition: Variables declared outside of all functions and classes have global scope. They
are accessible from any part of the program after their declaration.
 Example:

cpp
Copy code
int globalVar = 5; // globalVar has global scope

void func() {
globalVar = 10; // accessible inside the function
}

int main() {
globalVar = 20; // accessible inside main
func();
}

 Behavior: Global variables remain accessible throughout the program after they are
declared.

d) Namespace Scope

 Definition: Variables, functions, and classes declared inside a namespace are only accessible
within that namespace or when explicitly referenced with the namespace name.
 Example:

cpp
Copy code
namespace MyNamespace {
int var = 10;
}

int main() {
MyNamespace::var = 20; // accessing var within MyNamespace
}
e) Class Scope

 Definition: Members of a class (variables, methods) have class scope. They are accessible
within the class and through objects of the class.
 Example:

cpp
Copy code
class MyClass {
public:
int myVar; // myVar has class scope
void myFunc() {
myVar = 10; // accessible within the class
}
};

CONSTANTS

const Keyword

The const keyword is used to define constants that cannot be modified after initialization. It
can be applied to variables, pointers, and function parameters.

a) Constant Variables

 Definition: A variable declared with the const keyword cannot be modified after its initial
assignment.
 Example:

cpp
Copy code
const int MAX_VALUE = 100;
MAX_VALUE = 200; // Error: MAX_VALUE cannot be modified

POINTERS

Pointers are a fundamental concept in C++ that provide powerful capabilities for managing
memory and data. A pointer is a variable that stores the memory address of another variable.
Understanding pointers is crucial for tasks like dynamic memory allocation, efficient array
handling, and implementing data structures.

1. What is a Pointer?

A pointer is a variable that holds the memory address of another variable. Instead of storing a
data value directly, a pointer stores the location in memory where the value is stored.

 Pointer Declaration: To declare a pointer, you use the * operator before the pointer
name.

cpp
Copy code
int* ptr; // ptr is a pointer to an int

 Pointer Initialization: You can initialize a pointer to the address of an existing


variable using the address-of operator &.

cpp
Copy code
int value = 10;
int* ptr = &value; // ptr now holds the address of value

2. Accessing Value through Pointers

Once a pointer is pointing to a variable, you can access or modify the value of the variable it
points to using the dereference operator *.

 Dereferencing: The * operator is used to access the value stored at the memory
address the pointer is holding.

cpp
Copy code
int value = 10;
int* ptr = &value;

// Accessing the value through the pointer


int x = *ptr; // x will be 10

// Modifying the value through the pointer


*ptr = 20; // value is now 20
NAMESPACE

In C++, a namespace is a declarative region that provides a scope to identifiers such as


variables, functions, classes, and other entities. Namespaces help organize code and prevent
name collisions, especially when your code includes multiple libraries that might use the
same names for identifiers.

Key Points about Namespaces:

1. Defining a Namespace:
o You can define a namespace using the namespace keyword.

cpp
Copy code
namespace MyNamespace {
int myVar = 10;
void myFunction() {
// function implementation
}
}

2. Accessing Namespace Members:


o To access members of a namespace, use the scope resolution operator ::.

cpp
Copy code
MyNamespace::myVar = 20;
MyNamespace::myFunction();

3. Using using Directive:


o The using directive allows you to use all members of a namespace without
qualifying them with the namespace name.

cpp
Copy code
using namespace MyNamespace;
myVar = 30; // no need to use MyNamespace::
myFunction();

ERROR HANDLING
Error handling in C++ refers to the techniques used to manage and respond to errors that occur
during the execution of a program. Proper error handling ensures that a program can handle
unexpected situations gracefully, without crashing or producing incorrect results.

Exceptions:

 Exceptions provide a way to react to exceptional circumstances (like runtime errors)


in a structured and controlled manner. C++ supports exceptions via try, throw, and
catch.
 Example:
cpp
Copy code
try {
int result = divide(10, 0);
if (result == -1) throw std::runtime_error("Division by zero!");
} catch (const std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
}

 try block: Encapsulates code that might throw an exception.


 throw statement: Throws an exception, which can be any type (usually an object or
an error code).
 catch block: Handles the exception, preventing the program from terminating
abruptly.

INPUT AND OUTPUT STATEMENTS IN C++

In C++, input and output (I/O) operations are handled using streams. The standard library
provides facilities for both console and file I/O through streams. The most common streams
used for console I/O are cin, cout, and cerr.

1. Output Statement: cout

 cout: The standard output stream used to print data to the console.
 Syntax: The << operator (known as the insertion operator) is used to send data to the
output stream.

Example:

cpp
Copy code
#include <iostream>

int main() {
std::cout << "Hello, World!" << std::endl;
int num = 10;
std::cout << "The number is: " << num << std::endl;
return 0;
}

o Explanation:
 std::cout prints the message to the console.
 << is the insertion operator.
 std::endl is used to insert a newline and flush the output buffer.

2. Input Statement: cin

 cin: The standard input stream used to take input from the console.
 Syntax: The >> operator (known as the extraction operator) is used to get data from
the input stream.

Example:
cpp
Copy code
#include <iostream>

int main() {
int num;
std::cout << "Enter a number: ";
std::cin >> num; // Taking input from the user
std::cout << "You entered: " << num << std::endl;
return 0;
}

o Explanation:
 std::cin reads input from the user.
 >> is the extraction operator.
 The input is stored in the variable num.

COMMAND LINE ARGUMENTS

In C++, command line arguments allow you to pass information to a program when it is
executed. This feature is useful for configuring the program's behavior without hardcoding
values.

Basic Syntax

When writing a C++ program, you can define the main function to accept command line
arguments:

cpp
Copy code
int main(int argc, char* argv[])

 argc: An integer that represents the number of command line arguments passed to the
program. It includes the name of the program itself as the first argument.
 argv: An array of C-strings (char*), where each element is a command line
argument. argv[0] is the name of the program, and argv[1] through argv[argc-1]
are the arguments passed to the program.

Example

Here's a simple program that demonstrates how to use command line arguments:

cpp
Copy code
#include <iostream>

int main(int argc, char* argv[]) {


std::cout << "Number of arguments: " << argc << std::endl;
std::cout << "Program name: " << argv[0] << std::endl;
for (int i = 1; i < argc; ++i) {
std::cout << "Argument " << i << ": " << argv[i] << std::endl;
}

return 0;
}

Preprocessor Directives
Preprocessor directives in C++ are commands that are processed by the preprocessor before
the actual compilation of the code begins. They allow you to include files, define macros, and
conditionally compile code. Preprocessor directives are not part of the C++ language itself
but are handled by the preprocessor, which runs before the compiler.

Common Preprocessor Directives

1. #include
o Purpose: Includes the contents of a file into the source file.
o Syntax:

cpp
Copy code
#include <filename> // For standard library headers
#include "filename" // For user-defined headers

o Example:

cpp
Copy code
#include <iostream>
#include "myheader.h"

2. #define
o Purpose: Defines a macro, which is a fragment of code that can be used
repeatedly.
o Syntax:

cpp
Copy code
#define MACRO_NAME replacement_text

o Example:

cpp
Copy code
#define PI 3.14159
#define SQUARE(x) ((x) * (x))

double area = PI * SQUARE(5);


3. #undef
o Purpose: Undefines a macro, so it is no longer available.
o Syntax:

cpp
Copy code
#undef MACRO_NAME

SINGLE LINE COMMENTS


In C++, single-line comments are used to add brief explanations or notes in the code. These
comments are ignored by the compiler and do not affect the execution of the program.

Syntax for Single-Line Comments

There are two ways to write single-line comments in C++:

1. Using //
o Syntax:

cpp
Copy code
// This is a single-line comment

o Example:

cpp
Copy code
#include <iostream>

int main() {
int a = 5; // Initialize variable a with value 5
int b = 10; // Initialize variable b with value 10
std::cout << "Sum: " << (a + b) << std::endl; // Output the
sum
return 0;
}

TYPECASTING
Typecasting in C++ is the process of converting a variable from one data type to another.
This is often necessary when performing operations that involve different types or when
explicit control over type conversions is required.

Types of Typecasting in C++

1. Implicit Typecasting (Automatic Conversion)


o The compiler automatically converts one data type to another when needed,
based on the context of the operation.
o Example:
cpp
Copy code
int intValue = 10;
double doubleValue = intValue; // Implicitly converts int to
double

2. Explicit Typecasting (Manual Conversion)


o You manually specify the type to which you want to convert a value. This can
be done using C-style casts or C++ style casts.
o C-style Cast:
 Syntax:

cpp
Copy code
(type)expression

 Example:

cpp
Copy code
double doubleValue = 9.7;
int intValue = (int)doubleValue;

You might also like