0% found this document useful (0 votes)
18 views28 pages

C++

The document outlines a syllabus for a C++ programming course covering object-oriented design principles, classes, memory allocation, exception handling, and the Standard Template Library. It includes basic concepts of C++ such as data types, input/output operations, arrays, strings, and class definitions, along with constructors and object manipulation. Additionally, it provides examples of basic programs and string operations, emphasizing the importance of encapsulation and the use of constructors in class design.

Uploaded by

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

C++

The document outlines a syllabus for a C++ programming course covering object-oriented design principles, classes, memory allocation, exception handling, and the Standard Template Library. It includes basic concepts of C++ such as data types, input/output operations, arrays, strings, and class definitions, along with constructors and object manipulation. Additionally, it provides examples of basic programs and string operations, emphasizing the importance of encapsulation and the use of constructors in class design.

Uploaded by

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

Syllabus

• Object-Oriented Design Goals, Object-Oriented Design Principles.


• Classes: Class Structure, Constructors and Destructor
• Classes and Memory Allocation, Demonstration of OOPs concepts,
Exception Handling, Friends and Class Members
• Standard Template Library, Inheritance in C++, Examples, Multiple
Inheritance, Interfaces and Abstract Classes, Templates: Class Templates,
Function Templates
Basic Concepts
 #include <iostream>: This is a preprocessor directive that includes the Input/Output Stream (iostream) header
file in your program. It enables the use of standard input (cin), output (cout), and other I/O functions.

 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

 For strings without spaces, cin works fine.


 For strings with spaces, use getline().

 C++ has 95 keywords.


 Latest version is C++23. C++11, C++14 can be used.
Data types in C++
• There are four main categories:
int 4 bytes (typical)
Basic Data Derived Data Types: array, pointer, function
Types
Float 4 bytes

Double 8 bytes

Bool 1 byte

Void -

char 1 byte

Enumeration Data Types User-defined Data Types

#include <iostream> struct Point {


using namespace std; int x, y;
enum Color { RED, GREEN, BLUE }; };
int main() { Point p = {10, 20};
Color c = RED; cout << p.x << ", " << p.y << endl;
cout << "Value of RED: " << c << endl; // Output: 0 cout << "Size of int: " << sizeof(int) << " bytes" << endl;
return 0;
}
Basic Programs
1. #include <iostream> 3. Check even or odd
using namespace std; #include <iostream>
int main() using namespace std;
{ int main() {
cout << "Hello, World!" << endl; int num;
return 0; cout << "Enter a number: ";
} cin >> num;
if (num % 2 == 0)
2. Addition of 2 numbers
cout << num << " is even." << endl;
#include <iostream>
using namespace std; else
int main() { cout << num << " is odd." << endl;
int num1, num2, sum; return 0;
cout << "Enter two numbers: "; }
cin >> num1 >> num2;
sum = num1 + num2;
cout << "The sum is: " << sum << endl;
return 0; }
Arrays and Strings
• In C++, there are multiple ways to declare arrays.

a. int arr[5] = {10, 20, 30, 40, 50};


b. #include <array>

• using namespace std;

• array<int, 5> arr = {10, 20, 30, 40, 50};

• int numbers[5]; // Declaration of an array of 5 integers


• int numbers[5] = {1, 2, 3, 4, 5}; // Declaration and initialization
• char vowels[] = {'a', 'e', 'i', 'o', 'u’};
• char str[] = "Hello, World!";
String Data Type
The string data type in C++ is part of the Standard Template Library (STL),
specifically under the <string> header file.

#include <string>

#include <iostream>

using namespace std;

int main() {

string name = "John"; //string declaration and initialization

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);

// for member functions


Constructors
• A constructor is a special member function that is invoked when an object is created. It is primarily used to
initialize class members.

• 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";

Specialization = “IMAGE PROCESSING";

Branch = CSE;

2. Parameterized Constructor: Takes parameters to initialize member variables.

A::A(const string& nm, const string& sp, const string& br )

3. Copy Constructor: Creates a new object as a copy of an existing object.

A::A(const A& B) A p1; // Default constructor


{ A p2("John Smith", “AI”, “CSE"); // Parameterized
name = B.name; constructor
Specialization = B. Specialization; A p3(p2); // Copy constructor
Branch = B. Branch ; }
#include <iostream>
using namespace std;
void showBrand() {
class Car { cout << "Car Brand: " << brand << endl;
public: }
};
string brand;
// Default Constructor int main() {
Car() { Car car1; // Default constructor is called
cout << "Default Constructor Called!" << endl;
car1.showBrand();

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;

class Car { class Car {


public: public:
string brand;
string brand;
// ❌ Wrong: Copy constructor passing by value //✅ Correct Copy Constructor (Pass by Reference)
Car(const Car &c) {
Car(Car c) { cout << "Copy Constructor Called!" << endl;
cout << "Copy Constructor Called!" << endl; brand = c.brand;
}
brand = c.brand; };
}
int main() {
}; Car car1; // Normal object creation
int main() { Car car2 = car1; // Copy constructor is called ONCE

Car car1; // Normal constructor (not shown) return 0;


Car car2 = car1; // Copy constructor is called }

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!

Car car2 = car1;


→ Calls Car(const Car &c)
→ Uses reference to `car1` (no new copy created)
→ Assigns `car1.brand` to `car2.brand`
Using Default Arguments in Parameterized Constructor
class Passenger {

private:

string name;

string mealPref;

public:

// Parameterized constructor with a default argument

Passenger(string n, string m = "No Preference") {

name = n;

mealPref = m;

void showDetails() {

cout << "Passenger: " << name << ", Meal Preference: " << mealPref << endl;

};

int main() {

Passenger p1("John", "Vegetarian");

Passenger p2("Alice"); // Uses default meal preference

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
}

Car object created!


Inside main function
Car object destroyed!
Access Specifiers
• Access specifiers control the visibility and accessibility of class
members (variables and functions)
• Public Access Specifier:
1. Members are accessible anywhere (inside and outside the class).
2. Used for interface methods (functions that interact with the
outside world).
• Private Access Specifier
1. Members are only accessible inside the class.
2. NOT accessible in derived classes or outside the class.
3. Used for data hiding and encapsulation.
#include <iostream>
using namespace std;
class BankAccount {
private: // Private access
double balance;
public:
void setBalance(double b) { balance = b; } // Public setter function
void showBalance() { cout << "Balance: $" << balance << endl; }
};
int main() {
BankAccount account;

// account.balance = 1000; // ERROR: Cannot access private member
directly

account.setBalance(1000); //
account.showBalance();
Allowed via public function

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;

car1.showDetails(); // Calling the member function


return 0;
}
Outside the Class
#include <iostream>
using namespace std;
class Car {
public:
string brand;
int speed;
void showDetails(); // Function declaration (prototype)
};
// Function definition outside the class using `::`
void Car::showDetails() {
cout << "Brand: " << brand << ", Speed: " << speed << " km/h" << endl;
}
int main() {
Car car1;
car1.brand = "Ford";
car1.speed = 150;
car1.showDetails();
return 0;
}
Member Function with Parameters Member Function Returning Values
1. #include <iostream>
#include <iostream>
using namespace std; using namespace std;
class Rectangle { class Square {
public: public:
int side;
int length, width;
void setSide(int s) {
void setValues(int l, int w) { // Function with parameters side = s;
length = l; }
int getArea() { // Function returning a value
width = w;
return side * side;
} }
int area() { };
return length * width; int main() {
Square sq;
}
sq.setSide(4);
}; cout << "Area of square: " << sq.getArea() << endl;
int main() { return 0;
}
Rectangle rect;
rect.setValues(10, 5);
cout << "Area: " << rect.area() << endl;
return 0; }
const Member Functions :
 Ensures the function does not modify class data members.
#include <iostream>
using namespace std;
class Person {
public:
string name;

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).

2. Student Report Card (Parameterized Constructor, Access Specifiers)


Scenario:
A school wants to generate report cards for students. Each student has:
Attributes: name, rollNumber, marks (out of 100).
A function displayGrade() to print the student’s grade (A/B/C/F based on marks).
Question:
Create a Student class with a parameterized constructor to initialize name, rollNumber, and marks.
Implement displayGrade() to calculate and print the grade.
➡ Hint:
Use private access specifier for marks to prevent direct modification.
Grade Logic: marks >= 90 → A, 80-89 → B, 70-79 → C, Below 70 → F.
Movie Ticket Booking (Copy Constructor)
Scenario:
A multiplex cinema wants to automate online ticket booking. A MovieTicket has:
movieName
ticketPrice
seatNumber

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy