0% found this document useful (0 votes)
4 views11 pages

II Unit Notes

The document discusses static variables in C++, explaining their behavior in functions and classes, including initialization and access through static member functions. It also covers constant member functions, data abstraction, abstract data types (ADT), encapsulation, and dynamic memory management in C++. Key concepts include the importance of hiding implementation details and the use of access specifiers to control visibility of class members.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views11 pages

II Unit Notes

The document discusses static variables in C++, explaining their behavior in functions and classes, including initialization and access through static member functions. It also covers constant member functions, data abstraction, abstract data types (ADT), encapsulation, and dynamic memory management in C++. Key concepts include the importance of hiding implementation details and the use of access specifiers to control visibility of class members.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Static Variables

Static variables in a Function: When a variable is declared as static,


space for it gets allocated for the lifetime of the program.
Even if the function is called multiple times, space for the static
variable is allocated only once and the value of variable in the previous
call gets carried through the next function call.
// C++ program to demonstrate
// the use of Static variables in a Function
#include <iostream>
using namespace std;
void fun1()
{
// static variable
static int count = 0;
cout << count << " ";
// value is updated and will be carried to next function calls
count++;
}
int main()
{
for (int i=0; i<5; i++)
fun1();
return 0;
}
Output:
01234
Static variables in a class: As the variables declared as static are
initialized only once as they are allocated space in separate static
storage so, the static variables in a class are shared by the objects.
There can not be multiple copies of same static variables for different
objects.
A static variable inside a class should be initialized explicitly by the
user using the class name and scope resolution operator outside the
class as shown below:
// C++ program to demonstrate static variables //inside a class

#include <iostream>
using namespace std;
class abc
{
public:
static int i;

};
//static data members initializations
int abc::i = 1;

int main()
{
abc obj;
// prints value of i
cout <<"Value of i is "<< obj.i;
}
Output:
Value of i is 1
Static member function
A static member function is a special member function, which is used
to access only static data members, any other normal data member
cannot be accessed through static member function.
Static member function can be accessed with class name, by using
following syntax:
class_name:: function_name(parameter);
Example:
#include <iostream>
using namespace std;
class abc
{
private:
//static data members
static int X;
static int Y;
public:
//static member function
static void Print()
{
cout <<"Value of X: " << X << endl;
cout <<"Value of Y: " << Y << endl;
}
};
//static data members initializations
int abc :: X =10;
int abc :: Y =20;
int main()
{
abc OB;
//accessing member function with object name
cout<<"Printing through object name:"<<endl;
OB.Print();
//accessing member function with class name
cout<<"Printing through class name:"<<endl;
abc::Print();
}
Output:
Printing through object name:
Value of X: 10
Value of Y: 20
Printing through class name:
Value of X: 10
Value of Y: 20

Constant Member Functions


A constant (const) member function can be declared by
using const keyword, it is used when we want a function that should
not be used to change the value of the data members i.e. any type of
modification is not allowed with the constant member function.
Syntax:
return_type> <function_name>() const
Example:
//demonstrates const member functions
class aClass
{
private:
int alpha;
public:
void nonFunc() //non-const member function
{
alpha = 99;
} //OK
void conFunc() const //const member function
{
alpha = 99;
} //ERROR: can’t modify a member
};

The non-const function nonFunc() can modify member data alpha, but
the constant function conFunc() can’t. If it tries to, a compiler gives
error.
Member functions that do nothing but acquire data from an object are
obvious candidates for being made const, because they don’t need to
modify any data.
Making a function const helps the compiler flag errors, and tells
anyone looking at the listing that you intended the function not to
modify anything in its object.

Data Abstraction in C++


• Data Abstraction is a process of providing only the essential
details to the outside world and hiding the internal details, i.e.,
representing only the essential details in the program.
• Data Abstraction is a programming technique that depends on the
separation of the interface and implementation details of the
program.
• C++ provides a great level of abstraction. For example, pow()
function is used to calculate the power of a number without knowing
the algorithm the function follows.
• In C++ program if we implement class with private and public
members then it is an example of data abstraction.
• Let's take a real-life example of AC, which can be turned ON or OFF,
change the temperature, change the mode, and other external
components such as fan, swing. But we don't know the internal details
of the AC, i.e., how it works internally. Thus, we can say that AC
separates the implementation details from the external interface.
Data Abstraction can be achieved in two ways:
 Abstraction using classes
 Abstraction in header files

Abstraction using classes: An abstraction can be achieved


using classes. A class is used to group all the data members
and member functions into a single unit by using the access
specifiers. A class has the responsibility to determine which data
member is to be visible outside and which is not.

Abstraction in header files: Another type of abstraction is


header file.
For example, pow() function available is used to calculate the
power of a number without actually knowing which algorithm
function uses to calculate the power. Thus, we can say that
header files hides all the implementation details from the user.

Access Specifiers Implement Abstraction:

Public specifier: When the members are declared as public,


members can be accessed anywhere from the program.
Private specifier: When the members are declared as private,
members can only be accessed only by the member functions of
the class.

Example of Abstraction in header files


#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int n = 2;
int power = 3;
int result = pow(n,power); // pow(n,power) is the power function
cout << "Cube of "<<n<<" is : " <<result<< endl;
}
Output:
Cube of 2 is : 8
Example of data abstraction using classes.
#include <iostream>
using namespace std;
class Sum
{
private: int x, y, z; // private variables
public:
void add()
{
cout<<"Enter two numbers: ";
cin>>x>>y;
z= x+y;
cout<<"Sum of two numbers is: "<<z<<endl;
}
};
int main()
{
Sum s1;
s1.add();
}
Output:
Enter two numbers: 5 10
Sum of two numbers is: 15

Advantages of Abstraction:
• Implementation details of the class are protected from the
inadvertent user level errors.
• A programmer does not need to write the low-level code.
• Data Abstraction avoids the code duplication, i.e., programmer does
not have to undergo the same tasks every time to perform the similar
operation.
• The main aim of the data abstraction is to reuse the code and the
proper partitioning of the code across the classes.
• Internal implementation can be changed without affecting the user
level code.

ADT(Abstract Data type)


The definition of ADT only mentions what operations are to be performed but
not how these operations will be implemented.
It does not specify how data will be organized in memory and what
algorithms will be used for implementing the operations.
It is called “abstract” because it gives an implementation-independent view.
The process of providing only the essentials and hiding the details is known
as abstraction.
The user of data type does not need to know how that data type is
implemented, for example, we have been using Primitive values like int, float,
char data types only with the knowledge that these data type can operate
and be performed on without any idea of how they are implemented.
ADT is like a black box which hides the inner structure and design of the
data type.
An abstract data type is defined as a mathematical model of the data objects
that make up a data type as well as the functions that operate on these
objects.
An abstract data type (ADT) is a set of objects and an associated set of
operations on those objects
ADTs support abstraction, encapsulation and information hiding. Basically,
enhance representational independence.
They provide equal attention to data and operations
Common examples of ADTs:
Built-in types: Boolean, integer, real, arrays
User-defined types: stacks, queues, trees, lists
Built-in ADTs:
boolean
Values: TRUE and FALSE
Operations: and, or, not, nand, etc.
integer
Values: Whole numbers between MIN and MAX values
Operations: add, subtract, multiply, divide, etc.
arrays
Values: Homogeneous elements, i.e., array of X
Operations: initialize, store, retrieve,copy, etc.
User-definned ADTs:
stack
Values: Stack elements, i.e., stack of X
Operations: create, dispose, push, pop, is empty, is full, etc.
queue
Values: Queue elements, i.e., queue of X
Operations: create, dispose, enqueue, dequeue, is empty, is full, etc.
tree search structure
Values: Tree elements, i.e., tree of X
Operations: insert, delete, find, size,traverse (in-order, post-order, pre-
order), etc.

Encapsulation in C++
In normal terms Encapsulation is defined as wrapping up of data and
information under a single unit.
In Object Oriented Programming, Encapsulation is defined as binding
together the data and the functions that manipulates them.
Encapsulation leads to data abstraction or hiding.
Information hiding
Information or data hiding is a programming concept which protects the
data from direct modification by other parts of the program.
The feature of information hiding is applied using Class in most of the
programming languages.
Example
class student
{
char name[30];
int marks;
public:
void display(); };
int main()
{
student S;
S.marks=50; // Error as marks is private
}
Dynamic creation and destruction of objects
C++ supports dynamic memory allocation/deallocation. C++ allocates
memory and initializes the member variables.
An object can be created at run time; such an object is called a dynamic
object.
The construction and destruction of dynamic object is explicitly done by the
programmer.
The new and delete operators are used to allocate and deallocate memory to
such objects.

A dynamic object can be created using the new operator as:


ptr=new classname;
The variable ptr is the pointer object of the same class.
The member variable of the object can be accessed using the pointer and ->
operator.

A Dynamic object can be destroyed using the delete operator as:


delete ptr;
It also invokes the destructor of 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