0% found this document useful (0 votes)
6 views29 pages

Data Abstractions 1 1 1

The document provides a comprehensive overview of C++ programming concepts, including data abstractions, structures, classes, constructors, destructors, and function overloading. It outlines the syntax, advantages, applications, and sample programs for each topic, emphasizing the importance of object-oriented programming principles. Additionally, it discusses reference variables, friend functions, and static members, highlighting their roles in enhancing code organization and efficiency.

Uploaded by

keerthivasann405
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)
6 views29 pages

Data Abstractions 1 1 1

The document provides a comprehensive overview of C++ programming concepts, including data abstractions, structures, classes, constructors, destructors, and function overloading. It outlines the syntax, advantages, applications, and sample programs for each topic, emphasizing the importance of object-oriented programming principles. Additionally, it discusses reference variables, friend functions, and static members, highlighting their roles in enhancing code organization and efficiency.

Uploaded by

keerthivasann405
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/ 29

DATA ABSTRACTIONS AND OVERLOADING

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

Important Questions with answers-----------------------24


Data Abstraction & Overloading

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.

Structure of a C++ Program :


// Header Files
#include<iostream>
using namespace std;

// Class Declaration (Optional)


class ClassName {
// Data Members
// Member Functions
};

// Main Function – Entry Point


int main() {
// Variable Declarations

// Input Statements

// Processing / Logic

// Output Statements

return 0; // Indicates successful execution

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;
...
};

- Use `struct` keyword followed by the structure name and members.


- Members can be of different types.
- Structures can be declared globally or inside a function.

Advantages of Structure :

1. Combines different data types under one name.


2. Improves code readability and management.
3. Can be passed to and from functions easily.
4. Supports nested structures and arrays of structures.
5. Helps in modular programming by separating data from logic.

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;

cout << "Enter name: ";


cin >> s1.name;

cout << "Enter marks: ";


cin >> s1.marks;

// 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:

1. private – Accessible only within the class.


2. public – Accessible from outside the class.
3. protected – Accessible in derived classes (used in inheritance).

Creating and Using Objects:


Objects are instances of a class. They are used to access the members of the class

ClassName objectName; // Creating object


objectName.memberFunction(); // Accessing public method

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

Advantages of Using Classes in C++:

 Better organization of code.


 Real-world modeling using OOP principles.
 Secure and maintainable code.
 Easier debugging and reuse
Application of classes :
 Modeling real-world entities (e.g., Student, Employee)
 Data encapsulation and abstraction
 Reusable and modular code
 GUI development using class-based frameworks

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.

Feature Reference Pointer


Declaration Uses & Uses *
Null possible No Yes
Reassignment Not allowed after binding Can point to another value
Dereferencing Not needed Required using *

Applications of Reference Variables:


 Function arguments (call by reference)
Modify original variables passed to functions.
 Function return values
Return references to allow direct access to variables.
 Operator overloading
Used in classes for overloading operators efficiently.
 For performance
Avoid copying large objects or structures.
 Aliasing
Provide multiple names to the same memory.

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;

cout << "Enter name: ";


cin >> s1.name;

cout << "Enter marks: ";


cin >> s1.marks;

// 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 :

Enter roll number: 101


Enter name: Arjun
Enter marks: 89.5

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

// Function to display area


void displayArea() {
cout << "Area of rectangle: " << length * width << endl;
}
};

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.

Member functions can be of three types:


o Instance Functions: Operate on individual object instances.
o Static Functions: Belong to the class itself, not an individual object.
o Const Member Functions: Functions that do not modify the object's state.

Syntax :
class ClassName {
public:
return_type function_name(parameters) {
// Function body
}
};

Instance Member Functions:


 These functions are used to operate on the individual data of an object.
 They are called using the object name.

object.function_name();

Static Member Functions:


 These functions belong to the class and can be called without creating an object.
 They can only access static data members.

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;

// Member function to calculate area


double calculateArea() {
return 3.14 * radius * radius; // Formula for area of circle
}

// Member function to set radius


void setRadius(double r) {
radius = r;
}
};

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.

Use Cases of Friend Function:


 When two classes need to access each other's private data.
 When operator overloading is needed for operators like <<, >>, +, etc.
 For non-member utility functions that require access to private data.
Sample Program :
#include <iostream>
using namespace std;

class Box {
private:
int length;

public:
Box() {
length = 0;
}

// Friend function declaration


friend void setLength(Box &b, int l);
};

// Friend function definition


void setLength(Box &b, int l) {
b.length = l;
cout << "Length set to: " << b.length << endl;
}

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

// Define static member outside the class int Demo::count = 0;

int main() {
Demo d1, d2, d3;
Demo::showCount(); return 0;
}

Output:

Count is: 3

Advantages/Uses:

• Saves memory (only one copy).


• Useful for keeping global information about all objects.
• Helpful in utility functions that don't depend on object data.
10.Container Classes
In C++, container classes are part of the Standard Template Library (STL) that are used to store collections
of data. These classes are templates, meaning they can hold objects of any data type. Containers provide a
way to store and organize data, and they come with built-in functions to help with data management, such
as insertion, deletion, searching, and iteration. There are several types of container classes in C++:

Types of container classes :

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.

3. Unordered Associative Containers:


These containers store elements as key-value pairs, but they do not guarantee any specific
order.
Examples include:
• unordered_set: A collection of unique elements, unordered.
• unordered_map: A collection of key-value pairs, unordered.
• unordered_multiset: A collection of elements, unordered, allowing duplicates.
• unordered_multimap: A collection of key-value pairs, unordered, allowing 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.

2. Deletion: Elements can be removed by value or position:


o vector: pop_back() removes the last element
 map/set: erase() removes by key or iterator.
3. Access:
 vector/array: Access by inde
 iterators: Used for traversing elements in all containers, allowing uniform access. .
 map/set: Access using management

Advantages of Container Classes:

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

Purpose of an Integrator Class:

• To combine and organize different parts of a system.


• To control the execution flow between modules.
• To manage dependencies between different classes.
• To simplify the main program by hiding complex interactions inside the integrator

include <iostream> using namespace std;

// Component 1: Sensor class class Sensor { public:


int readData() {
return 50; // Simulating a sensor value
}
};

// Component 2: Actuator class class Actuator { public:


void performAction(int command) {
cout << "Actuator activated with command value: " << command << endl;
}
};

// Integrator Class: Combines Sensor and Actuator class Integrator { private:


Sensor sensor;
Actuator actuator;
public:
void operate() {
int sensorValue = sensor.readData();
cout << "Sensor Value: " << sensorValue << endl;

actuator.performAction(sensorValue);
}
};
int main() {
Integrator system; system.operate();

return 0;
}

Applications of Integrator Classes:

• Robotics Systems: Integrating sensors, motor controllers, and communication modules.


• Embedded Systems: Combining input devices, processing units, and output units.
• Simulation Software: Integrating physics engines, rendering engines, and AI modules.

• Game Engines: Combining graphics, audio, input controls, and physics.


12.Proxy classes
A Proxy Class in C++ is a class that acts as an interface to another class or object. It
controls access to the real object, which can involve:

• Deferring the creation of the real object.


• Adding extra logic before/after accessing the object.
Protecting the real object from unauthorized
access.

In simple words:
A proxy is a stand-in or middleman between a client and the real object.

Purpose of Proxy Classes

• Control Access to an object (authorization, validation).


• Lazy Instantiation (object created only when needed).
• Add Additional Behavior (like logging, security checks).
• Remote Access (acting as local stand-in for a remote object).

#include <iostream> using namespace std;



• // Real object class RealSubject { public:
• void request() {
• cout << "RealSubject: Handling request." << endl;
• }
• };

• // Proxy class class Proxy { private:
• RealSubject real;
• public:
• void request() {
• cout << "Proxy: Controlling access to RealSubject." << endl;
real.request();
• }
• };

• // Client code int main() { Proxy proxy; proxy.request();
• return 0;
• }

Output

Proxy: Controlling access to RealSubject.


RealSubject: Handling request.
13.Function Overloading
Function Overloading in C++ is a feature that allows multiple functions to have the same
name but different parameter lists (different type or number of arguments).
The compiler determines which function to call based on the number and type of arguments passed.

In simple words, same function name, different behavior based on inputs.

Purpose of Function Overloading:

• To increase readability of the code.


• To perform similar operations with different types of data.
• To avoid creating multiple function names for closely related actions.

#include <iostream> using namespace std;


class Example { public:
void show(int a) {
cout << "Integer: " << a << endl;
}
void show(double b) {
cout << "Double: " << b << endl;
}
void show(string c) {
cout << "String: " << c << endl;
}
}; int main() { Example obj;

obj.show(5); // Calls show(int) obj.show(3.14); // Calls


show(double) obj.show("Hello"); // Calls show(string)

return 0;
}

Applications of Function Overloading:

• Mathematical operations on different types of numbers.


• Printing/displaying various types of data.
• Constructors can also be overloaded to initialize objects differently.

Advantages:

• Same function name for logically similar operations.


• Easier to understand and update code.
• Helps achieve polymorphism at compile time.
It improves code readability, reusability, and flexibility, and is a fundamental part of
ObjectOriented Programming in C++.
14.Operator Overloading
Operator Overloading in C++ is a feature that allows customizing the behavior of operators (+, -, *, etc.)
when they are used with user-defined data types (like classes).
In simple words, we can redefine what an operator means when applied to objects.

Purpose of Operator Overloading:


• To perform operations on user-defined objects in a natural way.
• To make classes work like built-in types.
• To increase code readability and ease of use.

Operators That Can Be Overloaded:


Most C++ operators can be overloaded, like:

• Arithmetic Operators: +, -, *, /
• Comparison Operators ==, <, >, !=
• Assignment Operators: =, +=, -= Stream Operators: <<, >>

• #include <iostream> using namespace std;


• class Complex { private:
• int real, imag;
• public:
• Complex(int r = 0, int i = 0) : real(r), imag(i) {}
• // Overload + operator
• Complex operator + (const Complex& obj) { Complex temp;
• temp.real = real + obj.real; temp.imag = imag + obj.imag;
return temp;
• }
• void display() {
• cout << real << " + " << imag << "i" << endl;
• }
• };
• int main() {
• Complex c1(3, 4), c2(1, 2);
• Complex c3 = c1 + c2; // Calls overloaded + operator c3.display();
// Output: 4 + 6i return 0;
• }

Advantages of Operator Overloading


• Improved Code Readability: Operator overloading can make expressions involving user-defined types more
readable and intuitive.
• Enhanced Code Reusability: By overloading operators, code can be reused and simplified, making it easier to
manage and maintain.
• Customization: Allows users to define their own operations for custom types, enhancing flexibility and usability.

Disadvantages of Operator Overloading


• Overuse: Overloading operators inappropriately can lead to confusion or code that is harder to understand.
• Code Bloat: Overloading too many operators can lead to unnecessary complexity and larger code size.
• Ambiguity: Improper overloading can cause ambiguities in code interpretation and compiler errors.

Applications of Operator Overloading


1. Complex Number Arithmetic
Overloading operators like +, -, *, and / for complex number classes makes it easy to perform arithmetic operations
directly on complex number objects, simplifying the code.
2. String Manipulation
Overloading the + operator enables custom string classes to use string concatenation with a natural syntax, making
string handling more efficient.
3. Matrix Operations
Operator overloading can simplify matrix operations (like addition and multiplication) by overloading the + and *
operators to work on matrix objects, making the code more concise.
4. Smart Pointers
Overloading dereferencing operators (* and ->) in smart pointers allows them to be used as regular pointers,
providing the same syntax as raw pointers for easier memory management.
5. Custom Input and Output
By overloading the << and >> operators, custom objects can be directly written to and read from streams, similar to
how primitive types are handled.
Important 2 mark questions

1. What are the different types of constructors in C++?


2. What is the purpose of the friend function in C++?
3. What are static data members?
4. How do you allocate memory dynamically in C++?
5. What is function overloading?
6. What is operator overloading?
7. What is a proxy class?
8. What is the use of the new and delete operators in C++?
9. What is the role of a constructor in a class?
10. Can we overload all operators in C++? Give an example.
11. What is a container class?
12. What do you mean by class scope?

Important 16 mark questions

1. Explain the features of C++ and its advantages over C.


2. Define Structures in C++. How are they different from Classes?
3. Describe the concept of Class Scope in C++.
4. What are Reference Variables? How are they initialized and used in
C++?
5. What is a Constructor? Explain its types with suitable examples.
6. Define Destructors in C++. How are they different from
Constructors?
7.Explain the role of Member Functions in Classes. How are they
defined and invoked?
8.Write a detailed note on Friend Functions. How are they declared
and used?
9. Explain Dynamic Memory Allocation in C++ using new and delete.
10. What are Static Class Members? How do they differ from regular
members?

2 mark question answers

1. What are the different type of constructors ?


a. Default Constructor: Takes no arguments.
b. Parameterized Constructor: Takes arguments to initialize objects.
c. Copy Constructor: Initializes an object using another object of the same class.
d. Move Constructor (C++11): Transfers resources from a temporary object.
e. Dynamic Constructor: Allocates memory dynamically using new

2. What is the purpose of the friend function in C++?


A friend function can access the private and protected members of a class even though
it is not a member of that class.

3. What are static data members?


Static data members are shared among all objects of the class. They are declared
with the static keyword and have only one copy, regardless of the number of
objects.

4. How do you allocate memory dynamically in C++?


Use the new operator to allocate memory and delete to free it:
int* ptr = new int;
delete ptr;
5. What is function overloading?
Function overloading allows multiple functions with the same name but different
parameters (type or number) in the same scope.

6. What is operator overloading?


Operator overloading allows you to redefine the behavior of operators (like +, -,
==) for user-defined types (classes).

7. What is a proxy class?


A proxy class is a helper class used to represent another class and control access to
it, often used in operator overloading or smart pointers.

8. What is the use of the new and delete operators in C++?


 new: Dynamically allocates memory for an object or variable.
 delete: Frees the memory allocated by new.

9. What is the role of a constructor in a class?


A constructor is a special function that initializes objects of a class automatically
when they are created.

10. Can we overload all operators in C++? Give an example.


No, some operators like ::, .?, sizeof, and typeid cannot be overloaded.
Example of overloading +:

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.

12. What do you mean by class scope?


Class scope refers to the visibility and accessibility of class members (variables and functions)
within the class or through its objects.

You might also like