C++ unit 2 notes
C++ unit 2 notes
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.
#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
#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.
#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.
#include <iostream>
using namespace std;
int main() {
char str[] = "Hello"; // String initialization
cout << "String: " << str << endl;
return 0;
}
#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.
A class is defined with the class keyword, and it can have both data members and
member functions.
#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;
}
#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.
#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;
}
#include <iostream>
using namespace std;
class Calculator {
public:
int add(int, int); // Declaration
};
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.
#include <iostream>
using namespace std;
class Box {
private:
double length;
public:
Box(double l) : length(l) {}
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.
The function definition must be placed inside the class definition or using the inline
keyword outside the 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;
}
#include <iostream>
using namespace std;
class Rectangle {
public:
inline int area(int length, int width); // Declaration
};
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.
Example:
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 main() {
cout << add(3, 4); // Calls the 'add' function and prints the result (7)
return 0;
}
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;
}
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;
}
};
int main() {
Dog d;
d.eat(); // Inherited from Animal
d.bark(); // Specific to Dog
return 0;
}
6. Polymorphism
Types:
class Animal {
public:
virtual void sound() { cout << "Some animal sound" << endl; }
};
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)
};
int main() {
Car myCar;
myCar.start(); // Calls Car's start method
return 0;
}
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
Example:
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.