C++
C++
using namespace std; tells the compiler to use the Standard Namespace (std). All standard library classes,
objects, and functions (e.g., cin, cout, endl) are part of the std namespace. Instead of writing std::cout or std::
endl every time, using namespace std; allows you to directly write cout or endl.
• std::cout << "Hello, World!" << std::endl;
cin and cout can be used for multiple variables in a single statement.
cout (Character Output): Used to display output on the screen. Uses the insertion operator (<<) to send data to
the standard output.
cin (Character Input): Used to take input from the user. Uses the extraction operator (>>) to receive data from the
keyboard.
The insertion operator (<<) is used for sending data to the stream (output), while the extraction operator (>>) is
used for extracting data from the stream (input).
endl: Adds a newline
Double 8 bytes
Bool 1 byte
Void -
char 1 byte
#include <string>
#include <iostream>
int main() {
cout << "Hello, " << name << "!" << endl;
Input
return 0; 1. string fullName;
} cout << "Enter your full name: ";
getline(cin, fullName);
cout << "Welcome, " << fullName << "!" << endl;
2. string name;
cout << "Enter your name: ";
cin >> name; // Input stops at a space
cout << "Hello, " << name << "!" << endl;
String operations
1. Length 5. Comparison
str.length() or str.size() Returns the number of characters str1 == str2, str1 < str2 //Compares strings
string str = "Hello"; string str1 = "apple";
cout << "Length: " << str.length() << endl; string str2 = "banana";
// Output: 5 if (str1 < str2)
cout << str1 << " comes before " << str2 << endl;
2. Concatenation output: apple comes before banana
str1 + str2 or str1.append(str2) Joins two strings 6. Clear
string firstName = "John"; str.clear() //Erases the string
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << "Full Name: " << fullName << endl;
7. Empty
str.empty() //Checks if the string is empty
3. Access Characters
8. Find
str[i] or str.at(i) Access a character by index
str.find("word") //Finds the position of a substring
string str = "Hello";
cout << "First character: " << str[0] << endl; // Output: H 9. Replace
str[0] = 'h';
str.replace(pos, len, "new") //Replaces a part of the string
cout << "Modified string: " << str << endl; // Output: hello
string str = "I love cats.";
4. Substring str.substr(pos, len)
str.replace(7, 4, "dogs");
Extracts a portion of the string
cout << str << endl; // Output: I love dogs.
string str = "Hello, World!";
cout << "Substring: " << str.substr(7, 5) << endl; // Output: World
String declaration and Creation
1. Creates an empty string. 6. Directly initialize a character array with a string literal.
char str[] = "Hello, World!";
string str;
std::cout << str << std::endl;
cout << "Empty string: " << str << std::endl; // Output: (nothing)
2. string str = "Hello, World!"; 7. Initialize the characters of the array, including the null terminator.
char str[] = {'H', 'e', 'l', 'l', 'o', '\0'};
3. create a new string by copying another string. std::cout << str << std::endl; // Output: Hello
std::string str1 = "Hello";
8. Combining Strings:
std::string str2(str1); // Copy of str1
a. Using “+” operator
std::cout << str2 << std::endl; // Output: Hello std::string part1 = "Hello";
4. create a string from a substring of another string. std::string part2 = "World";
std::string result = part1 + ", " + part2 + "!";
std::string str = "Hello, World!"; std::cout << result << std::endl; // Output: Hello, World!
std::string substr(str, 7, 5); // Start at index 7, length 5
b. Using append
std::cout << substr << std::endl; // Output: World std::string str = "Hello";
5. Creates a string by repeating a character multiple times. str.append(", World!");
std::cout << str << std::endl; // Output: Hello, World!
std::string str(5, '*'); // 5 asterisks
std::cout << str << std::endl; // Output: *****
Class
• A class in C++ is a user-defined data type that groups data (variables) and
functions together into a single unit.
• Data members are the data variables/atributes and member functions are
the functions/operations used to manipulate these variables .
#include <iostream>
using namespace std;
class Car {
public: // Access specifier (public/private/protected)
string brand; // Data members (variables)
int speed;
void showDetails() { // Member function
cout << "Brand: " << brand << ", Speed: " << speed << " km/h" << endl;
} • Class need to be terminated with semicolon.
}; • Private and Public are the access specif ie r/visibility
int main() {
labels.
Car car1; // Creating an object of the class • If no access specif ie r is given by default all the members
car1.brand = "Toyota";
are
car1.speed = 120;
private .Such a class is completely hidden from the outside
car1.showDetails(); // Calling the method world and does not serve any purpose.
return 0; • The binding of data and functions together into a single
} class-type variable is referred to as encapsulation.
Object
A n O b j e c t i s a n i d e n t i f ia b l e e n t i t y w i t h s o m e
characteristics and behavior.
An Object is an instance of a Class.
When a class is def ined, no memory is allocated but when
it is instantiated (i.e. an object is created) memory is
allocated.
Classname objectname;
Example:
Person p1,p2; // these are the class variables which are called as
instances/objects
Optional:
Objects can be created when a class is def ined by placing
their names immediately after the closing brace, similar to
structure
class Person {
Accessing the class members
• The private members of the class can not be accessed from
outside the class, ie main() cannot access private members.
• Only public members can be accessed from outside of the
class
Syntax:
• ObjectName.Variablename=Value/Variable;
// for data members of a class
• Variable=ObjectName.function(actual_arguments);
• Characteristics:
• Has the same name as the class.
• Does not have a return type.
• Can be overloaded with multiple versions.
• Can include default arguments.
Types:
1. Default Constructor: This constructor is automatically called when no arguments are passed.
A::A() {
name = “ISHA";
Branch = CSE;
brand = "Unknown";
Car car2("Toyota"); // Parameterized constructor is
} called
// Parameterized Constructor car2.showBrand();
Car(string b) {
Car car3 = car2; // Copy constructor is called
cout << "Parameterized Constructor Called!" << endl; car3.showBrand();
brand = b;
return 0;
} Default Constructor Called!
}
// Copy Constructor Car Brand: Unknown
Car(const Car &c) { Parameterized Constructor Called!
Car Brand: Toyota
cout << "Copy Constructor Called!" << endl;
Copy Constructor Called!
brand = c.brand; } Car Brand: Toyota
• Passing an object by reference means that instead of creating a new
copy of the object, we pass a reference (or alias) to the original object.
A reference in C++ is an alias for an existing variable. Instead of
copying the value, it refers to the original memory location.
#include <iostream> #include <iostream>
using namespace std; using namespace std;
return 0;
}
Copy Constructor Called!
Copy Constructor Called!
Copy Constructor Called!...
(Stack Overflow - Program Crash)
The ampersand (&) in Car(const Car &c) is used to pass the object by reference
instead of by value
Car(Car &c) {
cout << "Copy Constructor Called!" << endl;
brand = c.brand; }
void showBrand() {
Default Constructor Called!
cout << "Car Brand: " << brand << endl;
Default Constructor Called!
} Car Brand: Unknown
}; Parameterized Constructor Called!
Car Brand: Toyota
int main() {
Copy Constructor Called!
Car car1,car4; // Default constructor is called Car Brand: Toyota
car1.showBrand(); Car Brand: Toyota
Car car2("Toyota"); // Parameterized constructor is called Copy Constructor Called!
Car Brand: Toyota
car2.showBrand();
Car car3 = car2; // Copy constructor is called
car3.showBrand();
car4 = car2; // Copy constructor not called
car4.showBrand();
Car car5(car2); // Copy constructor is called
car5.showBrand(); }
Car car2 = car1;
→ Calls Car(Car c)
→ Needs to copy `car1` into `c` (calls copy constructor again)
→ Calls Car(Car c)
→ Needs to copy `car1` into `c` (calls copy constructor again)
→ Infinite recursion! Stack overflow!
private:
string name;
string mealPref;
public:
name = n;
mealPref = m;
void showDetails() {
cout << "Passenger: " << name << ", Meal Preference: " << mealPref << endl;
};
int main() {
p1.showDetails();
p2.showDetails();
return 0;
}
Destructor #include <iostream>
using namespace std;
• A destructor is a special member function that is
automatically called when an object goes out of class Car {
scope or is deleted. It is used for cleanup (e.g., public:
releasing memory). // Constructor
Car() {
Characteristics of Destructors: cout << "Car object created!" << endl;
1. Has the same name as the class but prefixed with ~ }
(tilde).
.
2. Does not take parameters (no overloading). // Destructor
3. Does not return anything. ~Car() {
cout << "Car object destroyed!" << endl;
4. Automatically called when the object is destroyed
}
};
int main() {
Car myCar; // Constructor is called
cout << "Inside main function" << endl;
return 0; // Destructor is called automatically
}
return 0;
}
• Protected Access Specifier
#include <iostream>
1. Works like private, but allows inheritance.
using namespace std;
2. Accessible in derived classes, but not outside class Parent {
the class. protected: // Protected member (not accessible outside but
3. Used when you want derived classes to accessible in derived class)
access members, but not the outside world. int secretCode;
public:
void setCode(int code) { secretCode = code; }
};
class Child : public Parent {
public:
void showCode() {
✅
cout << "Secret Code: " << secretCode << endl; //
Accessible in derived class
}
};
int main() {
Child obj;
obj.setCode(1234);
obj.showCode();
❌
// cout << obj.secretCode; //
the class
ERROR: Not accessible outside
return 0;
}
Member Function Definition in C++
Inside the class
• A member function in C++ is a function that
#include <iostream>
belongs to a class and operates on its data
members. using namespace std;
class Car {
• Member functions in a class can be defined in
two ways: public:
string brand;
1. Inside the class (Inline definition)
int speed;
2. Outside the class (Using the scope resolution
operator ::) - The function is declared inside the // Member function defined inside the class
class but defined outside
void showDetails() {
cout << "Brand: " << brand << ", Speed: " << speed << "
km/h" << endl;
}
};
int main() {
Car car1;
car1.brand = "Toyota";
car1.speed = 120;
void setName(string n) {
name = n;
}
void showName() const { // 'const' function ensures no modification
cout << "Name: " << name << endl;
}
};
int main() {
Person p;
p.setName("Alice");
p.showName(); // Safe function, no modification allowed
return 0; }
Assignment
1. Banking System (Classes & Objects, Access Specifiers)
Scenario:
A bank wants to develop a system to manage customers' savings accounts. The system should have the following:
•Private attributes: accountNumber, balance.
•Public methods: deposit(), withdraw(), displayBalance().
Question:
•Design a BankAccount class with the above features.
•Implement a constructor to initialize the account.
•Ensure that accountNumber and balance are private and cannot be accessed directly.
•Implement withdrawal restrictions (e.g., no withdrawal if balance is insufficient).
Question:
Create a MovieTicket class with a copy constructor.
When a customer books a ticket, a copy of the ticket should be created using the
copy constructor.
Ensure that changing the copy does not affect the original ticket.
➡ Hint: Copy constructors prevent shared memory issues when duplicating objects.
Friend Function
• A friend function is a function that is not a member of a class
but is allowed to access the private and protected members of
that class.
• It is declared inside the class with the friend keyword but
defined outside the class.