Unit 1
Unit 1
UNIT 1
OVERVIEW OF C++ PROGRAMMING
• The first version of C++ was called "C with Classes," and its primary goal was to provide a
more effective way to manage large-scale software projects.
Cont.
• C++98: The first standardized version of C++ by ISO (International Organization for Standardization).
• C++11: Introduced significant features like auto keyword, nullptr, lambda expressions, and range-based for
loops.
• C++20: Added features like concepts, coroutines, and ranges, along with continued optimizations and tools
for modern software development.
• C++23: Refined features from C++20 and introduced further improvements in performance and ease of use.
Key Features of C++
• Efficiency: C++ allows direct control over system resources, such as memory and hardware, making it one of the most efficient
languages for high-performance applications.
• Performance: C++ generates optimized machine code, which makes it one of the fastest programming languages, suitable for
performance-critical applications like real-time systems and games.
• Multi-Paradigm Support: C++ supports procedural, object-oriented, and generic programming, allowing developers to choose the
best paradigm for the task at hand.
• Object-Oriented Programming (OOP): C++ supports key OOP concepts such as classes, inheritance, polymorphism, and
encapsulation, which help in organizing complex software systems and improving code reuse.
• Templates and Generic Programming: C++ provides templates, which enable writing generic and reusable code. This allows the
creation of functions and classes that work with any data type.
• Standard Template Library (STL): The STL is a powerful library that provides pre-built templates for common data structures (e.g.,
vectors, lists, maps) and algorithms (e.g., sorting, searching), boosting productivity and efficiency.
• Low-Level Memory Management: C++ gives programmers direct control over memory allocation and deallocation using pointers
and manual memory management, allowing precise control over system resources.
Key Features of C++
• Function Overloading and Operator Overloading: C++ supports function overloading, where multiple functions with the same
name can exist but with different parameters, and operator overloading, allowing operators (e.g., +, *) to be customized for user-
defined types.
• Exception Handling: C++ provides robust exception handling mechanisms (using try, catch, and throw), allowing developers to
manage runtime errors and maintain program stability.
• RAII (Resource Acquisition Is Initialization): C++ uses RAII to manage resources like memory, file handles, and locks
automatically. Objects acquire resources when they are created and release them when they go out of scope.
• Const Keyword: The const keyword ensures that variables or data members cannot be modified, which improves program safety and
optimizes performance by enabling compiler optimizations.
• Namespaces: Namespaces allow the grouping of functions, classes, and variables into logical scopes, avoiding name conflicts in large
projects.
• Smart Pointers: C++ supports smart pointers (e.g., std::unique_ptr, std::shared_ptr) to manage memory automatically and help
prevent common issues like memory leaks and dangling pointers.
• Lambda Expressions: C++11 introduced lambdas, which allow the definition of anonymous functions (or function objects) in place,
making it easier to write short, inline functions.
• Move Semantics and Rvalue References: Introduced in C++11, move semantics allow efficient transfer of resources (like memory
or ownership) from one object to another, reducing unnecessary copying and improving performance.
Role of C++ in modern software development
• Systems Programming: C++ is used for developing operating systems, device drivers, and embedded systems due to its low-level
hardware control and performance.
• Game Development: It's the primary language for game engines (e.g., Unreal Engine), offering real-time rendering and physics
simulation with high performance.
• High-Performance Computing: C++ is crucial for scientific simulations, financial modeling, and supercomputing, where speed and
resource management are critical.
• Real-Time Systems: Used in industries like automotive, aerospace, and robotics, C++ helps build systems with strict timing and
resource constraints.
• Machine Learning & AI: While Python is popular for AI, C++ powers high-performance libraries (e.g., TensorFlow) for fast
computation and low-latency applications.
• Database Systems: C++ is used to build high-performance database engines (e.g., MySQL, PostgreSQL) for efficient data handling.
• Multimedia & Graphics: C++ is foundational in graphics, video processing, and other multimedia applications requiring intensive
processing.
• Cross-Platform Development: Frameworks like Qt allow C++ applications to run across different platforms with high performance.
C++ DATA TYPES
int main() {
int age = 30; // Integer initialization
float height = 5.9; // Float initialization
double pi = 3.14159; // Double initialization
char grade = 'A'; // Char initialization
bool isStudent = true; // Boolean initialization
return 0;
}
USER-DEFINED DATA TYPES
There are following user defined data types:
• Struct
• Union
• Enum
• class
Struct
• A structure is a collection of simple variable
• The variable in a structure can be of different type such as int,char,float,char,etc.
• This is unlike the array which has all variables of same data type
• The data items in a structure is called the member of structure.
Syntax:
struct structure_name{
declaration of data member;
};
• You can access data member of stucture by using only structure variable with dot operator.
PROGRAMME OF STRUCTURE
#include<iostream>
using namespace std; cout<<"Enter Marks For Sql :";
cin>>s.sql;
struct student{
int Roll_No; cout<<"Enter Marks For DFS:";
char name[15]; cin>>s.dfs;
int cPlus,maths,sql,dfs,total;
float per; s.total=s.cPlus+s.maths+s.sql+s.dfs;
}; s.per=s.total/4;
• It consume memory of highest variable and it will share the data among all other variable.
• For example: If a union contains variable like int, char,float then the memory will be consume of float
variable because float is highest among all variable of data type.
Syntax:
union union_name //union declaration
{
data_type member1;
data_type member2;
};
Example ,
char grade ;
}; roll_no
Byte 0 Byte 1
grade
enum char{a,b,c};
• The user also can assign value to one or more enumeration constant,and
subsequent values that are not assigned will be incremented.
For example :
enum char{a=3,b=7,c,d};
here, value of c is 8 and d is 9.
Example of Enum
#include<iostream> switch(i)
using namespace std; {
case apple:
cout<<"Your first fruit is Apple."; break;
int main()
case orange:
{ cout<<"Your second fruit is Orange."; break;
enum Fruits{ case guava:
apple,orange,guava,pinapple cout<<"Your third fruit is Guava.";
}; break;
case pineapples:
cout<<"Your forth fruit is Pineapples."; break;
Fruits myfruit;
int i; }
cout<<"Enter your choice:"; return 0;
cin>>i; }
CLASS
Syntax:
class class_name{
data member variables;
data member methods/functions;
};
Class Example
#include<iostream> void piramid::buildpyramid()
using namespace std; {
for(i=1;i<=n;i++)
class pyramid {
{ for(j=1;j<=i;j++)
int i,n,j; {
cout<<"*";
public: }
void getdata(); cout<<"\n";
void buildpyramid(); }
}; }
int main()
void pyramid::getdata() {
{ pyramid p;
cout<<"enter N:"; p.getdata();
cin>>n; p.buildpyramid();
} return 0;
}
Derived Data Types
Syntax:
data_type name[size];
Example:
char name[10];
int student[10];
Function
• A function is a group of statement that together perform a task.
• Every c++ program has at least one function that is main() and programmer can define
additional function.
• A function prototype tells compiler the name of the function ,return type, and parameters.
Syntax
return_type function_name(parameter_list);
Example
int max(int n1,int n2);
Function Example
#include<iostream> int max(int n1,int n2)
using namespace std; {
int result;
int max(int n1,int n2); \\declaration
if(n1>n2)
int main() result=n1;
{ else
int n1; int n2; int a; result=n2;
cout<<"Enter Number1: "<<"\n";
cin>>n1; return result;
cout<<"Enter Number2: "<<"\n"; }
cin>>n2;
• Pointer is basically the same as any other variable, difference about them is that
instead of containing actual data they contain a pointer to the memory location
where information can be found.
• Basically, pointer is variable whose value is address of another variable.
Syntax:
type *var_name;
Example:
int *p;
Pointer
• There are few operation which will do frequently with
pointer is:
• We define a pointer variable.
• Assign address of variable to a pointer and
• Finally access the value at the address available in the pointer
variable.
Like,
I. int var=20;
II. int *p;
III. p =&var;
Pointer Example
#include<iostream>
using namespace std;
int main()
{
int var=34;
int *p;
p=&var;
return 0;
}
symbolic constant type
You must initialize a constant when you craete it,you can not assign new
value later after constant is initialized.
• It can be used to get the size of classes, structure, union and any other user
defined data type.
Syntax:
sizeof(data_type)
Example:
sizeof(x) or sizeof(int)
int main()
{
int a,x;
char b;
float c=10.02;
double d;
cout<<"size of a:"<<sizeof(a)*sizeof(x)<<"\n";
cout<<"size of b:"<<sizeof(b)<<"\n";
cout<<"size of c:"<<sizeof(10.02)<<"\n";
cout<<"size of d:"<<sizeof(d)<<"\n";
return 0;
}
Challenges related to data type portability
• In C++, data type portability challenges often arise due to the differences in how compilers,
platforms, and architectures handle basic data types.
• Since C++ does not explicitly guarantee fixed-size types (other than for those specified by the
C++11 <cstdint> standard), the size of basic types like int, long, short, etc., can vary across
different systems.
• This can lead to issues when code is intended to run on multiple platforms with varying
architectures (e.g., 32-bit vs 64-bit systems, or big-endian vs little-endian machines).
Challenges related to data type portability
Pointer Size
• Problem: On 32-bit systems, pointers are 4 bytes, while on 64-bit systems, they are 8 bytes. This can
lead to issues in programs that assume a specific pointer size for calculations or memory management.
• Solution: Use uintptr_t or intptr_t from <cstdint> for performing pointer arithmetic or storing pointer
values as integers. These types are guaranteed to be able to hold a pointer value across platforms.
Procedural Programming Language
Step 1
Step 2
Step 3
Main Program
Function- 4 Function- 5
It is a method of Programming
where code is designed and based
on the functions and attributes of
the objects.
Contd..
Object-Oriented (OO)
▪ The term Object-Oriented means that we organize software as a collection of discrete
object that incorporate both data structure and behavior are only loosely connected.
Dog
Bicycle
Monitor Mango
Object Oriented Programming Language:
■ Object: Entity
■ Examples:
Dog
Table
Man
Apple
Object Oriented Programming Language:
Object
State Behaviour
Bottom- Up Approach
50
Example:
Bank Account Holder withdraws
money from ATM.
Object Abstraction
Inheritance
Class Encapsulation
Polymorphism
Concepts of OOP:
• Class: Collection of Objects.
• Blueprint of any functional entity which defines its properties
and functions
Example
:
Class Fruits
Object 1 Object 2
Object 3
What is a Class?
• Definition:
• A class is a blueprint or prototype that defines the variables and
methods common to all objects of a certain kind
Class Example
Television
Properties Functionalities
■ Physical entity
Truck
■ Conceptual entity
Chemical
Process
■ Software entity
Linked
List
68
Class/Object
Each copy of an
object from a
particular class is
called an instance of
the class.
69
Class/Object
70
In short…
CLASS OBJECT
Class is a data type Object is an instance of Class.
Shape
Draw ()
• The variables of a class will be hidden from other classes, and can be accessed only through the methods of their
current class.
• Also known as data hiding.
• For example: capsule, it is wrapped with different medicines.
Abstraction
■ 2 types:
1. Operator Overloading
2. Function Overloading
82
Applications of OOP
• Real-Time System
• Simulation & Modeling
• Object Oriented Database
• Hypertext and hypermedia
• AI and expert system
• Neural Network & Parallel Programming
• Decision Support and Office Automation System
• CIM/CAM/CAD System
Benefits of Object Model
The benefits of using the object model are −
• It helps in faster development of software.
• Code organization: By organizing code into objects, OOP improves structure and clarity.
• Modularity: It helps break down complex problems into smaller, manageable parts,
improving collaboration and team development.
• Security and Data Integrity: OOP encapsulates data and exposes only necessary methods,
ensuring that the system's state is protected and easily controlled.
• Real-world modeling: OOP makes it easier to model real-world systems, enhancing both
development and understanding.
Introduction to the C++ Standard Library
The C++ Standard Library is a collection of pre-defined classes, functions, and objects that
facilitate common programming tasks like:
integrating libraries.
• Logical Code Organization: Groups related functionalities together, making the code more structured and manageable.
• Improved Readability: Makes it clear which scope an identifier belongs to, aiding understanding.
• Extensibility: Allows adding new features to existing namespaces without interfering with the current code.
• Resolving Ambiguity: Clarifies which version of an identifier to use when multiple libraries define the same name.
• Reusability: Facilitates using code across different projects without naming conflicts.
• Compatibility with the Standard Library: Standard Library features (like std::cout) rely on namespaces.
• Scalability in Large Projects: Makes large systems manageable by dividing them into logical scopes.
• Best Practices Enforcement: Helps avoid global namespace pollution, ensuring cleaner and conflict-free code.
Structure of a C++ Program
class Example {
public:
void greet() {
cout << "Welcome to C++!" << endl;
}
};
int main() {
Example obj; // Create an object
obj.greet(); // Call a member function
return 0; // Return success status
}
Data Members and Member Functions
Data Members
• Variables defined within a class.
• Store data for objects of the class.
Member Functions
• Functions defined within a class to operate on data members.
• Can be defined inside or outside the class.
Example
#include <iostream>
int main() {
using namespace std;
Person p;
p.setDetails("Alice", 25);
class Person {
p.displayDetails();
private:
return 0;
string name; // Data member
}
int age; // Data member
public:
void setDetails(string n, int a) { // Member function
name = n;
age = a;
}
A constructor is a special member function used to initialize objects. It has the same name as the class
and no return type.
Types of Constructors:
• Default Constructor: No parameters.
• Parameterized Constructor: Accepts parameters.
• Copy Constructor: Creates a copy of an object.
Example
#include <iostream> int main() {
using namespace std; // Object initialized using the constructor
Rectangle rect(10, 20);
class Rectangle { cout << "Area: " << rect.area() << endl;
private: return 0;
int width, height; }
public:
// Parameterized constructor
Rectangle(int w, int h) {
width = w;
height = h;
}
int area() {
return width * height;
}
};
#include <iostream>
Lines beginning with a hash sign (#) are directives read and interpreted by what is
known as the preprocessor. They are special lines interpreted before the compilation of
In this case, the directive #include <iostream>, instructs the preprocessor to include a
section of standard C++ code, known as header iostream, that allows to perform
standard input and output operations, such as writing the output of this program
Statements are executed in the same order that they appear within a
function's body.
Using namespace std
• If you have seen C++ code before, you may have seen cout being used instead of
std::cout.
• Both name the same object: the first one uses its unqualified name (cout), while the
• cout is part of the standard library, and all the elements in the standard C++ library
• In order to refer to the elements in the std namespace a program shall either
qualify each and every use of elements of the library (as we have done by prefixing
cout with std::), or introduce visibility of its components. The most typical way to
Example:
int a, b, c;
double x;
int sum;
char my-character;
Input statements
cin >> variable-name;
Meaning: read the value of the variable called <variable-name> from the user
It extracts the value from the keyboard and assigns it to the variable on the
right.
Example:
cin >> a;
cin >> b >> c;
cin >> x;
cin >> my-character;
Input Operator
Output statements
cout << variable-name;
Meaning: print the value of variable <variable-name> to the user
cout << “any message”;
Meaning: print the message within quotes to the user
cout << endl;
Meaning: print a new line
Example:
cout << a;
cout << b << c;
cout << “This is my character: “ << my-character << “ he he he” << endl;
Output Operator
First sends the string “sum=“ to cout and then sends the value
of sum.
Finally, it sends the newline character so that the next output
will be in the new line.
Example:-
cin>>number1>>number2;
Access Modifiers
Accessing a data member depends solely on the access
control of that data member.
This access control is given by Access modifiers in C++.
2. private
3. protected
Contd..