Data Abstractions 1 1 1
Data Abstractions 1 1 1
Content
1. Overview of C++-------------------------------------------1
2. Structures----------------------------------------------------3
3. Class content -----------------------------------------------5
4. Referance Variable-----------------------------------------7
5. Constructors ------------------------------------------------9
6. Destructors ------------------------------------------------11
7. Member function and classes ---------------------------12
8. Friend function -------------------------------------------14
9. Static class member --------------------------------------16
10. Container classes -------------------------------------17
11. Integrators ---------------------------------------------19
12. Proxy classes ------------------------------------------20
13. Function overloading --------------------------------21
14. Operator overloading --------------------------------22
1. Overview of C++
Definition :
C++ is a middle-level language that combines the features of both high-level and low-level languages.
It supports encapsulation, inheritance, polymorphism, and abstraction, making it suitable for developing
complex software systems.
// Input Statements
// Processing / Logic
// Output Statements
Advantages of C++ :
1. Object-Oriented - Supports OOP concepts like inheritance and polymorphism.
2. Fast and Efficient - Closer to hardware with low-level memory access.
3. Portable - Can be run on various platforms with minimal changes.
4. Standard Template Library (STL) - Provides reusable code for data structures and algorithms.
5. Rich Library Support - Includes extensive built-in functions and libraries.
Application of C++:
1. System Software - Operating systems, drivers.
2. Game Development - Game engines like Unreal Engine.
3. GUI Applications - Applications with graphical user interfaces.
4. Embedded Systems - Used in microcontroller programming.
5. Real-time Systems
Example program :
#include <stdio.h>
int main() {
int a, b, sum;
// Input
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
// Processing
sum = a + b;
// Output
printf("The sum is: %d\n", sum);
return 0;
}
}
2. Structure
Definition of Structure :
A structure in C++ is a user-defined data type that allows grouping variables of different data types
under one name. It is used to represent a record, like storing details of a student or an employee
Syntax of structures :
struct StructureName {
dataType member1;
dataType member2;
...
};
Advantages of Structure :
Sample program :
#include <iostream>
using namespace std;
// Defining a structure
struct Student {
int rollNo;
string name;
float marks;
};
int main() {
// Creating a structure variable
Student s1;
// Taking input
cout << "Enter roll number: ";
cin >> s1.rollNo;
// Displaying output
cout << "\nStudent Details:\n";
cout << "Roll No: " << s1.rollNo << endl;
cout << "Name: " << s1.name << endl;
cout << "Marks: " << s1.marks << endl;
return 0;
}
Output :
Student Details:
Roll No: 101
Name: John
Marks: 87.5
Applications of Structure
1. Data Grouping - Organize related variables.
2. Database Records - Store complex data like employee/student info.
3. Data Transfer - Pass grouped data in functions or between modules.
4. Custom Data Types - Create meaningful types for program logic.
5. Memory Management - Efficiently manage structured data in programs.
Conclusion :
Structures in C++ provide a way to group logically related data. They are essential for handling
complex data in real-world applications like record-keeping, databases, and system design
3. Class Concept
Definition of Class :
A class in C++ is a user-defined data type that acts as a blueprint for creating objects. It groups data
members (variables) and member functions (methods) into a single unit, following the principles of object-
oriented programming like encapsulation and abstraction.
Syntax of class :
class ClassName {
private:
// private data members
// private member functions
public:
// public data members
// public member functions
};
Access Specifiers:
Features of Class:
Encapsulation: Binding data and functions together.
Data hiding: Access control using private, public, and protected.
Reusability: Code can be reused through objects or inheritance.
Modularity: Divides the program into small components (classes).
Sample program :
#include <iostream>
using namespace std;
class Student {
private:
int rollNo;
float marks;
public:
void getDetails() {
cout << "Enter roll number and marks: ";
cin >> rollNo >> marks;
}
void display() {
cout << "Roll Number: " << rollNo << endl;
cout << "Marks: " << marks << endl;
}
};
int main() {
Student s1;
s1.getDetails();
s1.display();
return 0;
}
Output
Enter roll number and marks: 101 87.5
Roll Number: 101
Marks: 87.5
4. Reference Variable
Definition :
A reference variable in C++ is an alias (alternative name) for an existing variable. Once a reference
is initialized with a variable, it becomes just another name for that variable — both share the same memory
location.
Syntax :
datatype &reference_name = original_variable;
Key Features:
A reference must be initialized during declaration.
A reference cannot be changed to refer to another variable once assigned.
Changes made through the reference affect the original variable.
Advantages:
More efficient than pointers (no dereferencing needed).
Safer than pointers (cannot be NULL).
Simplifies syntax for function arguments and object access.
Improves performance by avoiding unnecessary copies.
Sample program :
#include <iostream>
using namespace std;
// Defining a structure
struct Student {
int rollNo;
string name;
float marks;
};
int main() {
// Creating a structure variable
Student s1;
// Taking input
cout << "Enter roll number: ";
cin >> s1.rollNo;
// Displaying output
cout << "\nStudent Details:\n";
cout << "Roll No: " << s1.rollNo << endl;
cout << "Name: " << s1.name << endl;
cout << "Marks: " << s1.marks << endl;
return 0;
}
Output :
Student Details:
Roll No: 101
Name: Arjun
Marks: 89.5
5. Constructors
Definition:
A constructor is a special member function in a class that is automatically invoked when
an object of the class is created. It is used to initialize objects.
Features of Constructors:
Same name as the class
No return type (not even void)
Automatically called when an object is created
Can be overloaded (multiple constructors with different parameters)
Syntax :
class ClassName {
public:
ClassName(); // Default constructor
ClassName(parameters); // Parameterized constructor
};
Types of Constructors:
1. Default Constructor
o Takes no parameters.
o Automatically called when object is created.
2. Parameterized Constructor
o Accepts arguments to initialize object values at creation.
3. Copy Constructor
o Initializes an object using another object of the same class.
4. Dynamic Constructor
o Uses dynamic memory allocation (new operator).
5. Constructor Overloading
o More than one constructor in a class with different parameter lists.
Advantages :
Initializing object values automatically when they are created.
Assigning default values to data members.
Overloading constructors to create objects with different initial values.
Copying objects using the copy constructor
Allocating dynamic memory during object creation
Sample program :
#include <iostream>
using namespace std;
class Rectangle {
int length, width;
public:
// Default constructor to initialize values
Rectangle() {
length = 5;
width = 3;
}
int main() {
Rectangle rect; // Constructor is automatically called
rect.displayArea(); // Output the area
return 0;
}
Output :
Area of rectangle: 15
6. DESTRUCTORS
Definition:
A destructor is a special member function of a class that is automatically invoked when an
object is destroyed. Its main purpose is to release any resources (like memory) that were allocated
to the object during its lifetime.
Syntax:
A destructor has the same name as the class, preceded by a tilde (~), and it doesn't take any
arguments or return any values.
class ClassName {
public:
~ClassName() {
// Code to release resources
}
};
Features of Destructors:
They are automatically called when an object goes out of scope or is explicitly deleted.
There can only be one destructor per class (no overloading).
Destructors are used to free resources, such as memory allocated using new, file handles, etc.
They help prevent memory leaks by releasing resources that the object may have allocated.
Sample program
#include <iostream>
using namespace std;
class Sample {
public:
// Constructor
Sample() {
cout << "Object Created" << endl;
}
// Destructor
~Sample() {
cout << "Object Destroyed" << endl;
}
};
int main() {
Sample obj; // Constructor is called here
// Destructor is called automatically when the object goes out of scope
return 0;
}
Output :
Object Created
Object Destroyed
7. Member Functions and Classes in C++
Definition :
In C++, a class is a user-defined data type that contains data members (variables) and member
functions (methods) to operate on the data. Member functions are functions that are defined inside a
class and can access and modify the data members of that class.
Member Functions :
Member function is a function that is defined inside the class and operates on the class's data
members. It can be used to perform actions or calculations related to the class.
Syntax :
class ClassName {
public:
return_type function_name(parameters) {
// Function body
}
};
object.function_name();
class MyClass {
public:
static int staticValue;
static void staticFunction() {
cout << "Static function called" << endl;
}
Const Member Functions:
These functions guarantee that they will not modify the object’s state.
They are declared with the const keyword after the function signature.
class MyClass {
public:
int value;
void display() const {
cout << "Value: " << value << endl;
}
};
Sample program :
#include <iostream>
using namespace std;
class Circle {
public:
double radius;
int main() {
Circle circle1; // Creating object of class Circle
circle1.setRadius(5); // Setting radius using member function
cout << "Area of circle: " << circle1.calculateArea() << endl; // Calling member
function
return 0;
}
Output :
Area of circle: 78.5
8. Friend function
Definition:
A friend function is a non-member function that is given special access to the private and
protected members of a class. Although it is not a member of the class, it can access its internal
data like a member function.
Syntax :
In the class definition, declare the friend function using the keyword friend:
class ClassName {
friend return_type function_name(parameters); // Friend function declaration
};
The actual function is defined like a normal function (outside the class):
return_type function_name(parameters) {
// Function body
}
. Key Points:
Declared inside the class using the keyword friend.
Defined outside the class like a regular function.
It is not called using an object (unlike member functions).
It does not have access to this pointer because it's not a member function.
It can be useful when two or more classes need to share private data.
class Box {
private:
int length;
public:
Box() {
length = 0;
}
int main() {
Box b1;
setLength(b1, 10); // Accessing private member using friend function
return 0;
}
Output :
Length set to: 10
Advantages:
Allows flexibility to access private data where needed.
Useful for operator overloading and bridging data between classes.
Can simplify interfaces by keeping helper functions outside the class.
Disadvantages:
Breaks encapsulation by exposing private data.
Increases the risk of tight coupling between classes.
Can reduce code maintainability if overused.
Applications :
Can access a class’s private and protected members.
Useful for overloading binary operators that access private data.
Allows one class to access private members of another class.
Makes it easier to write test code that accesses private data.
9. Static Member Class
In C++, a static class member refers to a variable or function that is common to all objects of a class. It
means only one copy of that static member exists for the entire class, and all objects share it. When we
declare something as static inside a class, it becomes shared among all objects — it is not duplicated with
each new object.
Characteristics
• Only one copy of that member is created for the entire class and is shared by all the objects of that
class, no matter how many objects are created.
• It is initialized before any object of this class is created, even before the main starts outside the class
itself.
• Static members are declared using the static keyword inside the class definition.
class ClassName {
static data_type variable_name; // static data member public:
static return_type function_name(); // static member function };
Example Program
# include<iostream> using namespace std;
class Demo {
static int count; // static data member public: Demo() { count++;
}
static void showCount() { // static member function cout << "Count is: "
<< count << endl; }
};
int main() {
Demo d1, d2, d3;
Demo::showCount(); return 0;
}
Output:
Count is: 3
Advantages/Uses:
1. Sequence Containers:
These containers store elements in a specific sequence, where the order of elements matters.
Examples include:
• vector: A dynamic array that allows random access and efficient appending of elements at the end.
• deque: A double-ended queue that allows fast insertion/removal at both ends.
• list: A doubly linked list that allows fast insertion/removal at any position, but doesn't support random
access.
• array: A fixed-size container that holds elements of a specific type.
2. Associative Containers:
These containers store elements as key-value pairs and allow fast searching based on keys.
Examples include:
• set: A collection of unique elements sorted by keys.
• map: A collection of key-value pairs, where each key is unique.
• multiset: Similar to set but allows duplicate elements. multimap: Similar to map but allows
duplicate keys.
4. Container Adapters:
These are wrappers around other containers that provide specific interfaces for certain use
cases.
o Examples include:
• stack: Implements a Last In, First Out (LIFO) structure.
• queue: Implements a First In, First Out (FIFO) structure.
Operations on Container Classes :
1. Insertion: Containers allow adding elements in various ways:
o vector: push_back() to add elements at the end.
o map/set: insert() to add key-value pairs or keys.
• Dynamic Sizing: Containers like vector and deque automatically resize as needed.
• Efficiency: STL containers are highly optimized for performance.
• Flexibility: Containers can store any data type due to their templated nature.
• Ease of Use: Built-in functions for common operations like insertion, deletion, and traversal simplify programming
tasks.
• #include <iostream>
#include <vector> using namespace std;
• int main() { vector<int> v;
•
• v.push_back(5); // Insertion
• v.push_back(10);
• v.push_back(15);
• cout << "Vector elements: "; for (int i : v) {
• cout << i << " "; // Access
• }
• cout << endl;
•
• v.pop_back(); // Deletion of last element
• cout << "After deletion: "; for (int i : v) { cout << i << "
";
• }
• cout << endl;
•
• return 0;
• }
•
11.Integrators
An Integrator Class in C++ is a special type of class that combines multiple components or modules into
a single working system.
It is responsible for managing the interaction, communication, and coordination between various
independent classes (components).
The integrator itself often does not perform the detailed work of individual components, but controls how
and when components work together to achieve a common goal.
actuator.performAction(sensorValue);
}
};
int main() {
Integrator system; system.operate();
return 0;
}
In simple words:
A proxy is a stand-in or middleman between a client and the real object.
Output
return 0;
}
Advantages:
• Arithmetic Operators: +, -, *, /
• Comparison Operators ==, <, >, !=
• Assignment Operators: =, +=, -= Stream Operators: <<, >>
class Complex {
public:
int real, imag;
Complex operator+(const Complex& c) {
return {real + c.real, imag + c.imag};
}
};
11. What is a container class?
A container class is a class that stores collections of objects. Examples: vector, list,
map in STL.