INTRODUCTION OF C++ LANGUAGE
By-RAHUL CHAUBE
## C++ Language Notes
### 1. **Introduction to C++**
**Definition**: C++ is a versatile, high-performance programming language that extends C with object-oriented features. It is widely used in systems software, game development, and applications requiring high performance.
**Key Features**:
- **Object-Oriented Programming (OOP)**: Supports classes and objects, encapsulation, inheritance, and polymorphism.
- **Rich Standard Library**: Includes the Standard Template Library (STL) for collections and algorithms.
- **Low-Level Manipulation**: Allows for direct memory access and hardware interaction.
— -
### 2. **Basic Syntax and Structure**
**Basic Program Structure**:
```cpp
#include <iostream> // Include input-output stream library
using namespace std; // Use standard namespace to avoid std:: prefix
int main() { // Main function — entry point of the program
cout << “Hello, World!” << endl; // Output text to the console
return 0; // Return statement indicating successful completion
}
```
**Components**:
- **`#include <iostream>`**: Preprocessor directive to include the standard input-output stream library.
- **`using namespace std;`**: Makes the standard library accessible without `std::` prefix.
- **`main()` Function**: Where program execution starts.
- **`cout`**: Output stream object.
- **`endl`**: End-of-line manipulator.
— -
### 3. **Data Types**
**Basic Data Types**:
- **`int`**: Integer type.
- **`float`**: Single-precision floating-point type.
- **`double`**: Double-precision floating-point type.
- **`char`**: Character type.
**Example**:
```cpp
int age = 25;
float salary = 50000.50;
double pi = 3.1415926535;
char grade = ‘A’;
```
**Modifiers**:
- **`short`**, **`long`**: Modify the size of `int`.
- **`unsigned`**: Represents non-negative values.
**Example**:
```cpp
unsigned int positiveNumber = 10;
long long bigNumber = 1234567890;
```
— -
### 4. **Operators**
**Arithmetic Operators**:
- **`+`**: Addition
- **`-`**: Subtraction
- **`*`**: Multiplication
- **`/`**: Division
- **`%`**: Modulus (remainder)
**Example**:
```cpp
int a = 10, b = 20;
int sum = a + b; // sum = 30
```
**Relational Operators**:
- **`==`**: Equal to
- **`!=`**: Not equal to
- **`<`**: Less than
- **`>`**: Greater than
- **`<=`**: Less than or equal to
- **`>=`**: Greater than or equal to
**Example**:
```cpp
bool result = (a == b); // false
```
**Logical Operators**:
- **`&&`**: Logical AND
- **`||`**: Logical OR
- **`!`**: Logical NOT
**Example**:
```cpp
bool isTrue = (a < b) && (b > 15); // true
```
**Assignment Operators**:
- **`=`**: Assignment
- **`+=`**: Addition assignment
- **`-=`**: Subtraction assignment
- **`*=`**: Multiplication assignment
- **`/=`**: Division assignment
- **`%=`**: Modulus assignment
**Example**:
```cpp
int x = 10;
x += 5; // x = 15
```
— -
### 5. **Control Flow**
**Conditional Statements**:
- **`if`, `else if`, `else`**: For decision-making.
**Example**:
```cpp
if (age >= 18) {
cout << “Adult”;
} else {
cout << “Minor”;
}
```
**Loops**:
- **`for` Loop**: For fixed iterations.
**Example**:
```cpp
for (int i = 0; i < 5; i++) {
cout << i << “ “;
}
```
- **`while` Loop**: Continues as long as the condition is true.
**Example**:
```cpp
int i = 0;
while (i < 5) {
cout << i << “ “;
i++;
}
```
- **`do-while` Loop**: Executes at least once before checking the condition.
**Example**:
```cpp
int i = 0;
do {
cout << i << “ “;
i++;
} while (i < 5);
```
— -
### 6. **Functions**
**Definition**: Blocks of code designed to perform specific tasks. They promote code reuse and modularity.
**Syntax**:
```cpp
returnType functionName(parameters) {
// function body
return value; // return type
}
```
**Example**:
```cpp
int add(int a, int b) {
return a + b;
}
```
**Calling Functions**:
```cpp
int result = add(5, 10); // result = 15
```
**Function Overloading**: Multiple functions with the same name but different parameters.
**Example**:
```cpp
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
```
— -
### 7. **Arrays**
**Definition**: A collection of elements of the same type stored in contiguous memory locations.
**Syntax**:
```cpp
type arrayName[arraySize];
```
**Example**:
```cpp
int numbers[5] = {1, 2, 3, 4, 5};
```
**Accessing Elements**:
```cpp
int firstNumber = numbers[0]; // 1
```
**Multidimensional Arrays**:
```cpp
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
```
**Accessing Elements**:
```cpp
int value = matrix[1][2]; // 6
```
— -
### 8. **Pointers**
**Definition**: Variables that store memory addresses of other variables.
**Syntax**:
```cpp
type* pointerName;
```
**Example**:
```cpp
int value = 10;
int* ptr = &value; // ptr holds the address of value
```
**Dereferencing**:
```cpp
int dereferencedValue = *ptr; // dereferencedValue = 10
```
**Pointer Arithmetic**:
```cpp
ptr++; // Moves the pointer to the next memory location
```
**Dynamic Memory Allocation**:
```cpp
int* arr = new int[5]; // Allocate an array of 5 integers
delete[] arr; // Free the allocated memory
```
— -
### 9. **Classes and Objects**
**Definition**: Classes are user-defined types that encapsulate data and functions. Objects are instances of classes.
**Syntax**:
```cpp
class ClassName {
public:
// Attributes
// Methods
};
```
**Example**:
```cpp
class Car {
public:
string brand;
void honk() {
cout << “Honk! Honk!” << endl;
}
};
Car myCar;
myCar.brand = “Toyota”;
myCar.honk(); // Output: Honk! Honk!
```
**Constructors and Destructors**:
- **Constructor**: Initializes objects.
- **Destructor**: Cleans up resources.
**Example**:
```cpp
class Example {
public:
Example() {
cout << “Constructor called” << endl;
}
~Example() {
cout << “Destructor called” << endl;
}
};
```
— -
### 10. **Inheritance**
**Definition**: Mechanism for creating new classes from existing ones, inheriting their attributes and methods.
**Syntax**:
```cpp
class Base {
// Base class members
};
class Derived : public Base {
// Derived class members
};
```
**Example**:
```cpp
class Animal {
public:
void eat() {
cout << “Eating” << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << “Barking” << endl;
}
};
Dog myDog;
myDog.eat(); // Inherited method
myDog.bark(); // Derived method
```
— -
### 11. **Polymorphism**
**Definition**: Allows objects of different classes to be treated as objects of a common base class, mainly using virtual functions.
**Types**:
- **Compile-Time (Static)**: Function overloading and operator overloading.
- **Run-Time (Dynamic)**: Virtual functions.
**Example**:
```cpp
class Base {
public:
virtual void show() {
cout << “Base class show” << endl;
}
};
class Derived : public Base {
public:
void show() override {
cout << “Derived class show” << endl;
}
};
Base* bptr;
Derived d;
bptr = &d;
bptr->show(); // Outputs: Derived class show
```
— -
### 12. **Templates**
**Definition**: Enables functions and classes to operate
with generic types.
**Function Template**:
```cpp
template <typename T>
T add(T a, T b) {
return a + b;
}
```
**Class Template**:
```cpp
template <class T>
class Stack {
// Stack implementation
};
```
— -
### 13. **Exception Handling**
**Definition**: Mechanism to handle runtime errors and exceptions gracefully.
**Syntax**:
```cpp
try {
// Code that might throw an exception
} catch (exceptionType e) {
// Code to handle the exception
}
```
**Example**:
```cpp
try {
int result = 10 / 0;
} catch (const std::exception& e) {
cout << “Exception: “ << e.what() << endl;
}
```
— -
### 14. **File I/O**
**Definition**: Handling input and output through files.
**Syntax**:
```cpp
#include <fstream> // For file handling
int main() {
ofstream outFile(“example.txt”); // Create an output file stream
outFile << “Hello, File!” << endl; // Write to the file
outFile.close(); // Close the file
ifstream inFile(“example.txt”); // Create an input file stream
string line;
getline(inFile, line); // Read a line from the file
cout << line << endl; // Output to console
inFile.close(); // Close the file
return 0;
}
```
**Classes**:
- **`ofstream`**: For writing to files.
- **`ifstream`**: For reading from files.
- **`fstream`**: For both reading and writing.
— -
### 15. **Standard Template Library (STL)**
**Definition**: A collection of template classes and functions to facilitate common programming tasks.
**Components**:
- **Containers**: `vector`, `list`, `deque`, `set`, `map`, etc.
- **Algorithms**: Sorting, searching, etc.
- **Iterators**: For traversing containers.
**Example**:
```cpp
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
vector<int> nums = {4, 1, 8, 3};
sort(nums.begin(), nums.end()); // Sort the vector
for (int num : nums) {
cout << num << “ “; // Output sorted elements
}
cout << endl;
return 0;
}
```
— -
### 16. **Namespaces**
**Definition**: Used to organize code into logical groups and prevent name conflicts.
**Syntax**:
```cpp
namespace MyNamespace {
int myVariable;
void myFunction() {
// Code
}
}
```
**Example**:
```cpp
namespace Math {
int add(int a, int b) {
return a + b;
}
}
int main() {
int result = Math::add(5, 3); // Accessing function from namespace
cout << result << endl; // Outputs: 8
return 0;
}
```
— -
### 17. **Preprocessor Directives**
**Definition**: Commands processed by the preprocessor before compilation.
**Common Directives**:
- **`#define`**: Define constants or macros.
- **`#include`**: Include files.
- **`#ifdef` / `#ifndef`**: Conditional compilation.
- **`#pragma`**: Implementation-specific directives.
**Example**:
```cpp
#define PI 3.14
#include <iostream>
using namespace std;
int main() {
cout << “Value of PI: “ << PI << endl;
return 0;
}
```
— -
-RAHUL CHAUBE