0% found this document useful (0 votes)
6 views13 pages

C++ unit 2 notes

The document covers fundamental concepts in C++ programming, including dynamic memory allocation, arrays, strings, classes, encapsulation, inheritance, polymorphism, and abstraction. It explains how to define and use variables, functions, and classes, as well as memory management and the Standard Template Library (STL). Key OOP principles such as encapsulation and polymorphism are highlighted with examples to illustrate their usage.

Uploaded by

Jayesh
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)
6 views13 pages

C++ unit 2 notes

The document covers fundamental concepts in C++ programming, including dynamic memory allocation, arrays, strings, classes, encapsulation, inheritance, polymorphism, and abstraction. It explains how to define and use variables, functions, and classes, as well as memory management and the Standard Template Library (STL). Key OOP principles such as encapsulation and polymorphism are highlighted with examples to illustrate their usage.

Uploaded by

Jayesh
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

1.

Variables: Dynamic Creation and Derived Data

In C++, variables can be dynamically created using pointers and dynamic memory allocation.
Dynamic memory allocation is done using new and delete operators. Derived data types are user-
defined types created using struct or class.

Dynamic Creation of Variables

 Dynamic memory allocation enables creating variables at runtime.

Example: Dynamic allocation of a single integer:

#include <iostream>
using namespace std;

int main() {
int* ptr = new int; // Dynamic memory allocation
*ptr = 10; // Assigning value
cout << "Value: " << *ptr << endl;
delete ptr; // Freeing memory
return 0;
}

Dynamic Arrays

 Arrays can also be dynamically created using new[].

Example: Dynamic allocation of an array:

#include <iostream>
using namespace std;

int main() {
int* arr = new int[5]; // Dynamically allocated array
for (int i = 0; i < 5; ++i) {
arr[i] = i + 1; // Assigning values
}
for (int i = 0; i < 5; ++i) {
cout << arr[i] << " "; // Displaying values
}
delete[] arr; // Deleting dynamically allocated array
return 0;
}
2. Arrays and Strings in C++

Arrays in C++

 Arrays are a collection of elements of the same type, stored in contiguous memory
locations.

Example: Defining and accessing elements of an array:

#include <iostream>
using namespace std;

int main() {
int arr[5] = {1, 2, 3, 4, 5}; // Array initialization
cout << "Third element: " << arr[2] << endl; // Accessing array element
return 0;
}

Strings in C++

 Strings are arrays of characters. In C++, we can use char[] or the string class.

Example: Using a character array for a string:

#include <iostream>
using namespace std;

int main() {
char str[] = "Hello"; // String initialization
cout << "String: " << str << endl;
return 0;
}

Example: Using std::string:

#include <iostream>
#include <string> // Required for using std::string
using namespace std;

int main() {
string str = "Hello, World!";
cout << "String: " << str << endl;
return 0;
}
3. Classes in C++

Classes in C++ are blueprints for creating objects. A class encapsulates data for the object and
methods to manipulate that data.

Defining Classes in C++

 A class is defined with the class keyword, and it can have both data members and
member functions.

Example: Basic class definition:

#include <iostream>
using namespace std;

class Car {
public:
string model;
int year;

void displayInfo() {
cout << "Model: " << model << ", Year: " << year << endl;
}
};

int main() {
Car myCar;
myCar.model = "Toyota";
myCar.year = 2020;
myCar.displayInfo();
return 0;
}

4. Classes and Encapsulation

Encapsulation is one of the fundamental concepts in object-oriented programming. It restricts


direct access to some of the object’s components and can prevent the accidental modification of
data.

Member Access Specifiers

 Private: Members are accessible only within the class.


 Public: Members are accessible from outside the class.
 Protected: Members are accessible within the class and by derived classes.
Example: Encapsulation using private and public access specifiers:

#include <iostream>
using namespace std;

class Account {
private:
double balance;

public:
void setBalance(double b) {
balance = b; // Setting the balance
}

double getBalance() {
return balance; // Getting the balance
}
};

int main() {
Account acc;
acc.setBalance(5000.0); // Setting balance via setter
cout << "Balance: " << acc.getBalance() << endl; // Getting balance via getter
return 0;
}

5. Member Functions

Member functions are functions that belong to a class and can access the class's data members.

Defining Member Functions

 They can be defined inside or outside the class definition.

Example: Defining member functions inside the class:

#include <iostream>
using namespace std;

class Calculator {
public:
int add(int a, int b) {
return a + b;
}
};
int main() {
Calculator calc;
int result = calc.add(5, 7);
cout << "Result: " << result << endl;
return 0;
}

Defining Member Functions outside the Class

#include <iostream>
using namespace std;

class Calculator {
public:
int add(int, int); // Declaration
};

// Definition of member function outside class


int Calculator::add(int a, int b) {
return a + b;
}

int main() {
Calculator calc;
int result = calc.add(5, 7);
cout << "Result: " << result << endl;
return 0;
}

6. Friend Function

A friend function is a function that is not a member of the class but can access its private and
protected members.

Declaring and Defining a Friend Function

 It can be declared inside the class with the friend keyword.

Example: Using a friend function:

#include <iostream>
using namespace std;

class Box {
private:
double length;

public:
Box(double l) : length(l) {}

friend void printLength(Box); // Friend function declaration


};

// Friend function definition


void printLength(Box b) {
cout << "Length of the box: " << b.length << endl;
}

int main() {
Box box(10.5);
printLength(box); // Accessing private member via friend function
return 0;
}

7. Inline Function

Inline functions are functions defined with the inline keyword to suggest to the compiler that the
code of the function should be inserted directly into the calling code, reducing function-call
overhead.

Defining Inline Functions

 The function definition must be placed inside the class definition or using the inline
keyword outside the class.

Example: Inline function inside a class:

#include <iostream>
using namespace std;

class Square {
public:
inline int getSquare(int x) { return x * x; } // Inline function
};

int main() {
Square s;
cout << "Square of 5: " << s.getSquare(5) << endl; // Function call
return 0;
}

Example: Inline function outside the class:

#include <iostream>
using namespace std;

class Rectangle {
public:
inline int area(int length, int width); // Declaration
};

// Inline function definition outside class


inline int Rectangle::area(int length, int width) {
return length * width;
}

int main() {
Rectangle rect;
cout << "Area: " << rect.area(4, 6) << endl;
return 0;
}

Summary

1. Dynamic Creation of Variables: You can dynamically allocate memory using new and
deallocate it using delete. This is useful for creating variables at runtime.
2. Arrays and Strings: Arrays can be created statically or dynamically, and strings can be
managed using char[] or std::string.
3. Classes: Classes are blueprints for creating objects and can have data members and
member functions.
4. Encapsulation: Encapsulation ensures that data is protected and can only be accessed or
modified through methods.
5. Member Functions: Functions that belong to a class and operate on its data.
6. Friend Function: A function that is not a member of a class but has access to its private
and protected members.
7. Inline Function: Functions that are expanded at the point of call to reduce overhead from
function calls.

1. Variables and Data Types


 Variable: A variable is like a container that holds data. You give it a name, and it can
store values like numbers or text. For example, int x = 5; creates a variable x that
holds the number 5.
 Data Types: The type of data a variable can hold. For example:
o int is for integers (whole numbers),
o float is for decimal numbers,
o char is for single characters (like 'A'),
o string is for text (a collection of characters).

Example:

int age = 25; // 'age' is an integer variable


float salary = 5500.5; // 'salary' is a floating-point number

2. Functions

 Function: A function is a set of instructions that can be used repeatedly. It can take
inputs (parameters) and return an output (result).

Example:

#include <iostream>
using namespace std;

int add(int a, int b) {


return a + b; // Adds two numbers and returns the result
}

int main() {
cout << add(3, 4); // Calls the 'add' function and prints the result (7)
return 0;
}

3. Object-Oriented Programming (OOP)

 OOP: It is a way of organizing your code around "objects", which represent real-world
things like a "Car" or "Dog". Each object has:
o Attributes (also called data members), like color, speed, or weight.
o Methods (also called member functions), which are actions the object can
perform, like driving or barking.
 Classes: A class is like a blueprint for creating objects. It's where you define the
attributes and methods.

Example:

class Car {
public:
string color;
int speed;

void drive() {
cout << "The car is driving at " << speed << " mph." << endl;
}
};

int main() {
Car myCar; // Create an object of type Car
myCar.color = "Red"; // Assign values to attributes
myCar.speed = 60;
myCar.drive(); // Call the 'drive' method
return 0;
}

4. Encapsulation

 Encapsulation: It's the concept of hiding the internal details of how an object works and
only showing what’s necessary. This keeps things organized and safe from outside
interference. It is done by making data members private and providing public functions
to access them.

Example:

class Account {
private:
double balance; // Private data, cannot be accessed directly

public:
void setBalance(double amount) { // Public method to set balance
balance = amount;
}

double getBalance() { // Public method to get balance


return balance;
}
};

int main() {
Account acc;
acc.setBalance(1000); // Set balance using a public method
cout << "Balance: " << acc.getBalance() << endl; // Get balance using a
public method
return 0;
}

5. Inheritance

 Inheritance: It's like getting characteristics from a parent. For example, a Dog class can
inherit features from an Animal class. This helps in reusing code.
Example:

class Animal {
public:
void eat() {
cout << "Animal is eating." << endl;
}
};

class Dog : public Animal { // Dog inherits from Animal


public:
void bark() {
cout << "Dog is barking." << endl;
}
};

int main() {
Dog d;
d.eat(); // Inherited from Animal
d.bark(); // Specific to Dog
return 0;
}

6. Polymorphism

 Polymorphism: It means "many shapes." In C++, this allows objects to behave


differently based on their types. For example, a function draw() can behave differently
for a Circle or a Rectangle, even though the function name is the same.

Types:

 Compile-time Polymorphism (like function overloading),


 Runtime Polymorphism (using inheritance and virtual functions).

Example (Runtime Polymorphism):

class Animal {
public:
virtual void sound() { cout << "Some animal sound" << endl; }
};

class Dog : public Animal {


public:
void sound() override { cout << "Bark" << endl; } // Overriding the base
function
};

int main() {
Animal* animal = new Dog();
animal->sound(); // Calls Dog's sound() method at runtime
return 0;
}
7. Abstraction

 Abstraction: Hiding unnecessary details and showing only the essential features. For
example, when you drive a car, you don’t need to know how the engine works, you just
need to know how to start the car and drive.

Example:

class Vehicle {
public:
virtual void start() = 0; // Pure virtual function (abstract method)
};

class Car : public Vehicle {


public:
void start() { cout << "Car is starting." << endl; }
};

int main() {
Car myCar;
myCar.start(); // Calls Car's start method
return 0;
}

8. Constructor and Destructor

 Constructor: A special function that is called when an object is created. It's used to
initialize the object’s attributes.
 Destructor: A special function that is called when an object is destroyed. It is used for
cleaning up, like deallocating memory.

Example:

class Book {
public:
string title;

// Constructor
Book(string t) {
title = t;
cout << "Book " << title << " created." << endl;
}

// Destructor
~Book() {
cout << "Book " << title << " destroyed." << endl;
}
};
int main() {
Book b("C++ Programming"); // Constructor is called here
// Destructor is automatically called when 'b' goes out of scope
return 0;
}

9. Memory Management

 Memory Allocation: Memory is allocated to variables using the new keyword. It is


dynamically allocated, which means it is created during the program's execution.
 Memory Deallocation: After you're done using the memory, you should free it using the
delete keyword.

Example:

int* ptr = new int; // Dynamically allocating memory for an integer


*ptr = 20; // Assign value
cout << *ptr << endl; // Accessing the value
delete ptr; // Freeing the memory

10. Standard Template Library (STL)

 STL: A collection of template classes that provide generic classes and functions for
common data structures (like vectors, lists, and maps) and algorithms (like sorting,
searching, etc.).
o vector: A dynamic array.
o list: A doubly-linked list.
o map: A collection of key-value pairs.

Example:

#include <iostream>
#include <vector> // Include vector from STL
using namespace std;

int main() {
vector<int> v = {1, 2, 3, 4, 5}; // Create a vector
v.push_back(6); // Add an element to the end of the vector
for (int i : v) {
cout << i << " "; // Display all elements
}
return 0;
}

Conclusion
 C++ is a powerful, multi-paradigm language that allows you to write high-performance
code and provides strong support for Object-Oriented Programming (OOP).
 Key concepts in OOP include Encapsulation, Inheritance, Polymorphism, and
Abstraction.
 STL provides efficient, ready-made solutions for common programming problems, such
as managing collections of data.

You might also like