Professional Documents
Culture Documents
Data abstraction is one of the most essential and important feature of object oriented
programming in C++. Abstraction means displaying only essential information and
hiding the details. Data abstraction refers to providing only essential information about
the data to the outside world, hiding the background details or implementation.
Consider a real life example of a man driving a car. The man only knows that pressing
the accelerators will increase the speed of car or applying brakes will stop the car but he
does not know about how on pressing accelerator the speed is actually increasing, he
does not know about the inner mechanism of the car or the implementation of
accelerator, brakes etc in the car. This is what abstraction is.
Abstraction using Classes: We can implement Abstraction in C++ using classes.
Class helps us to group data members and member functions using available access
specifiers. A Class can decide which data member will be visible to outside world and
which is not.
Abstraction in Header files: One more type of abstraction in C++ can be header files.
For example, consider the pow() method present in math.h header file. Whenever we
need to calculate power of a number, we simply call the function pow() present in the
math.h header file and pass the numbers as arguments without knowing the underlying
algorithm according to which the function is actually calculating power of numbers.
We can easily implement abstraction using the above two features provided by access
specifiers. Say, the members that defines the internal implementation can be marked as
private in a class. And the important information needed to be given to the outside world
can be marked as public. And these public members can access the private members
as they are inside the class.
Example:
#include <iostream>
using namespace std;
class implementAbstraction
{
private:
int a, b;
public:
void display()
{
cout<<"a = " <<a << endl;
cout<<"b = " << b << endl;
}
};
int main()
{
implementAbstraction obj;
obj.set(10, 20);
obj.display();
return 0;
}
Output:
a = 10
b = 20
You can see in the above program we are not allowed to access the variables a and b
directly, however one can call the function set() to set the values in a and b and the
function display() to display the values of a and b.
Advantages of Data Abstraction:
Helps the user to avoid writing the low level code
Avoids code duplication and increases reusability.
Can change internal implementation of class independently without affecting the
user.
Helps to increase security of an application or program as only important details
are provided to the user.
https://www.tutorialspoint.com/cplusplus/cpp_data_abstraction.htm
Let's take one real life example of a TV, which you can turn on and off,
change the channel, adjust the volume, and add external components such
as speakers, VCRs, and DVD players, BUT you do not know its internal
details, that is, you do not know how it receives signals over the air or
through a cable, how it translates them, and finally displays them on the
screen.
For example, your program can make a call to the sort() function without
knowing what algorithm the function actually uses to sort the given values.
In fact, the underlying implementation of the sorting functionality could
change between releases of the library, and as long as the interface stays
the same, your function call will still work.
In C++, we use classes to define our own abstract data types (ADT). You
can use the cout object of class ostream to stream data to standard
output like this −
#include <iostream>
int main() {
cout << "Hello C++" <<endl;
return 0;
Here, you don't need to understand how cout displays the text on the
user's screen. You need to only know the public interface and the
underlying implementation of ‘cout’ is free to change.
Members defined with a public label are accessible to all parts of the program.
The data-abstraction view of a type is defined by its public members.
Members defined with a private label are not accessible to code that uses the
class. The private sections hide the implementation from code that uses the
type.
There are no restrictions on how often an access label may appear. Each
access label specifies the access level of the succeeding member definitions.
The specified access level remains in effect until the next access label is
encountered or the closing right brace of the class body is seen.
Class internals are protected from inadvertent user-level errors, which might
corrupt the state of the object.
By defining data members only in the private section of the class, the
class author is free to make changes in the data. If the
implementation changes, only the class code needs to be examined to
see what affect the change may have. If data is public, then any
function that directly access the data members of the old
representation might be broken.
Data Abstraction Example
Any C++ program where you implement a class with public and
private members is an example of data abstraction. Consider the
following example −
#include <iostream>
class Adder {
public:
// constructor
Adder(int i = 0) {
total = i;
total += number;
int getTotal() {
return total;
};
private:
int total;
};
int main() {
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
return 0;
When the above code is compiled and executed, it produces the following
result −
Total 60
Above class adds numbers together, and returns the sum. The public
members - addNum and getTotal are the interfaces to the outside world
and a user needs to know them to use the class. The private
member total is something that the user doesn't need to know about, but
is needed for the class to operate properly.
Designing Strategy
Abstraction separates code into interface and implementation. So while
designing your component, you must keep interface independent of the
implementation so that if you change underlying implementation then
interface would remain intact.
In this case whatever programs are using these interfaces, they would not
be impacted and would just need a recompilation with the latest
implementation.
https://www.tutorialspoint.com/cplusplus/cpp_data_encapsulation.htm
All C++ programs are composed of the following two fundamental elements
−
Program data − The data is the information of the program which gets affected
by the program functions.
C++ supports the properties of encapsulation and data hiding through the
creation of user-defined types, called classes. We already have studied
that a class can contain private, protected and public members. By
default, all items defined in a class are private. For example −
class Box {
public:
double getVolume(void) {
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The variables length, breadth, and height are private. This means that they
can be accessed only by other members of the Box class, and not by any
other part of your program. This is one way encapsulation is achieved.
#include <iostream>
class Adder {
public:
// constructor
Adder(int i = 0) {
total = i;
total += number;
int getTotal() {
return total;
};
private:
int total;
};
int main() {
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
return 0;
When the above code is compiled and executed, it produces the following
result −
Total 60
Above class adds numbers together, and returns the sum. The public
members addNum and getTotal are the interfaces to the outside world
and a user needs to know them to use the class. The private
member total is something that is hidden from the outside world, but is
needed for the class to operate properly.
Designing Strategy
Most of us have learnt to make class members private by default unless we
really need to expose them. That's just good encapsulation.
This is applied most frequently to data members, but it applies equally to all
members, including virtual functions.
Manipulating Pointers in C Programming
In this lesson, you will learn how to manipulate pointers in C programming. You will understand
pointer declaration and how to increment a pointer either by value or by address. We will also
discuss the use of relational operations to compare pointer addresses.
Pointers in C
A pointer in C is like a display sign that indicates the direction of another city or a place. This display
sign actually holds the name and address of the city. In C, the pointer variable actually points to the
address of another variable, such as the variable's address in memory. It is more efficient to use
pointers than standard variables and this is one of the requirement if you are working with memory.
In order to get the address of a variable, use the ampersand (&) symbol. For a quick test, copy the
following code into your C compiler and run it.
1. #include <stdio.h>
2. int main(void) {
3. int menu1;
4. int menu2;
5. printf("Address of Menu 1: %x\n", &menu1);
6. printf("Address of Menu 2: %x\n", &menu2);
7. }
Your results for the variables may vary, but will look something like this:
Address of Menu 1: 62fe24
Address of Menu 2: 62fe30
It is always recommended to initialize a pointer and give it a NULL value at first. Why? If the pointer
does not have any address assigned to it, it will take any random address and this can create issues
when you try to run the program; in other words, your program could crash.
1. int i = 0;
2. i++;
Because a pointer points to an address (which is also a numeric value), you can also increment a
pointer. However, you are incrementing by address value instead of integer value. In most C
compilers, an integer is stored as 4 bytes. Therefore, if your integer pointer has a value of 62fe30,
incrementing the pointer will result in a new address of 62fe34.
Note that memory addresses are stored as hexadecimal values. The decimal value of 62fe34 is
6487604.
1. #include <stdio.h>
2. int main(void) {
3. int scores[] = {1500, 1700, 2250};
4. int i = 0;
5. int *ptr = NULL;
6. ptr = scores;
7. for(i=0;i<3;i++) {
8. printf("Address of scores[%d] array = %x\n", i, ptr);
9. printf("Value stored at scores[%d] = %d\n", i, *ptr); /* increment */
10. ptr++;
11. }
12. }
Output:
Address of scores[0] array = c8264abc
Value stored at scores[0] = 1500
Address of scores[1] array = c8264ac0
Value stored at scores[1] = 1700
Address of scores[2] array = c8264ac4
Value stored at scores[2] = 2250
Incrementing the Value of Pointer in an Array
Because a pointer points to another value (e.g., an address in memory), it is also useful for array
processing. We can indicate the bucket of an array by using its index; but we can also use pointers.
For example, look at the following array and how the incrementing works.
1. #include <stdio.h>
2. int main(void) {
3. int scores[5] = {100, 235, 275, 50, 100};
4. intt *ptr = NULL;
5. ptr = &scores;
6. Printf(“Value stored in pointer after increment is %d”,*++ptr);
7. }
http://btechsmartclass.com/c_programming/C-Parameter-Passing.html
Parameter Passing in C
When a function gets executed in the program, the execution control is transferred from calling
function to called function and executes function definition, and finally comes back to the calling
function. When the execution control is transferred from calling function to called function it may
carry one or more number of data values. These data values are called as parameters.
Parameters are the data values that are passed from calling function to called function.
Actual Parameters
Formal Parameters
The actual parameters are the parameters that are speficified in calling function. The formal
parameters are the parameters that are declared at called function. When a function gets executed,
the copy of actual parameter values are copied into formal parameters.
In C Programming Language, there are two methods to pass parameters from calling function to
Call by Value
Call by Reference
Call by Value
In call by value parameter passing method, the copy of actual parameter values are copied to
formal parameters and these formal parameters are used in called function. The changes made on
the formal parameters does not effect the values of actual parameters. That means, after the
execution control comes back to the calling function, the actual parameter values remains same. For
example consider the following program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int,int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
Output:
In the above example program, the variables num1 and num2 are called actual parameters and the
variables a and b are called formal parameters. The value of num1 is copied into a and the value of
num2 is copied into b. The changes made on variables a and b does not effect the values
of num1 and num2.
Call by Reference
In Call by Reference parameter passing method, the memory location address of the actual
parameters is copied to formal parameters. This address is used to access the memory locations of
the actual parameters in called function. In this method of parameter passing, the formal parameters
must be pointer variables.
That means in call by reference parameter passing method, the address of the actual parameters is
passed to the called function and is recieved by the formal parameters (pointers). Whenever we use
these formal parameters in called function, they directly access the memory locations of actual
parameters. So the changes made on the formal parameters effects the values of actual
parameters. For example consider the following program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int *,int *) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
Output:
In the above example program, the addresses of variables num1 and num2 are copied to pointer
variables a and b. The changes made on the pointer variables a and b in called function effects the
values of actual parameters num1 and num2 in calling function.
Recursive Functions in C
In C programming language, function calling can be made from main() function, other functions or
The recursive functions should be used very carefully because, when a function called by itself it
enters into infinite loop. And when a function enters into the infinite loop, the function execution
never gets completed. We should define the condition to exit from the function call so that the
When a function is called by itself, the first call remains under execution till the last call gets invoked.
Every time when a function call is invoked, the function returns the execution control to the previous
function call.
Example Program
#include<stdio.h>
#include<conio.h>
Output:
In the above example program, the factorial() function call is initiated from main() function with the
value 3. Inside the factorial() function, the function calls factorial(2), factorial(1) and factorial(0) are
called recursively. In this program execution process, the function call factorial(3) remains under
execution till the execution of function calls factorial(2), factorial(1) and factorial(0) gets completed.
Similarly the function call factorial(2) remains under execution till the execution of function calls
factorial(1) and factorial(0) gets completed. In the same way the function call factorial(1) remains
under execution till the execution of function call factorial(0) gets completed. The complete execution
process of the above program is shown in the following figure...
http://btechsmartclass.com/c_programming/C-Structures.html
The memory allocated in stack is fixed at the time of compilation and remains till end the program
execution. When we create an array, we must specify the size at the time of declaration itself and it
can not be changed during the program execution. This is a major problem when we does not know
the number of values to be stored in an array. To solve this we use the concept of Dynamic
Memory Allocation. The dynamic memory allocation allocates memory from heap storage.
Allocation of memory during the program execution is called dynamic memory allocation.
or
Dynamic memory allocation is the process of allocating the memory manually at the time of
program execution.
We use pre-defined or standard library functions to allocate memory dynamically. There
are FOUR standard library functions that are defined in the header file known as "stdlib.h". They
are as follows...
1. malloc()
2. calloc()
3. realloc()
4. free()
malloc()
malloc() is the standard library function used to allocate a memory block of specified number of
bytes and returns void pointer. The void pointer can be casted to any datatype. If malloc() function
unable to allocate memory due to any reason it returns NULL pointer.
Syntax
void* malloc(size_in_bytes)
Example
Example Program for malloc().
#include<stdio.h>
#include<conio.h>
int main () {
char *title;
return(0);
calloc()
calloc() is the standard library function used to allocate multiple memory blocks of specified number
of bytes and initializes them to ZERO. calloc() function returns void pointer. If calloc() function unable
to allocate memory due to any reason it returns NULL pointer. Generelly calloc() is used to allocate
memory for array and structure. calloc() function takes two arguments and they are 1. Number of
blockas to be allocate, 2. Size of each block in bytes
Syntax
void* calloc(number_of_blocks,
size_of_each_block_in_bytes)
Example
Example Program for calloc().
#include<stdio.h>
#include<conio.h>
int main () {
int i, n;
int *ptr;
printf("Number of blocks to be created:");
scanf("%d",&n);
return(0);
}
realloc()
realloc() is the standard library function used to modify the size of memory blocks that were
previously allocated using malloc() or calloc(). realloc() function returns void pointer. If calloc()
function unable to allocate memory due to any reason it returns NULL pointer.
Syntax
void* realloc(*pointer,
new_size_of_each_block_in_bytes)
Example
Example Program for realloc().
#include<stdio.h>
#include<conio.h>
int main () {
char *title;
return(0);
free()
free() is the standard library function used to deallocate memory block that was previously allocated
using malloc() or calloc(). free() function returns void pointer. When free() function is used with
memory allocated that was created using calloc(), all the blocks are get deallocated.
Syntax
void free(*pointer)
Example
Example Program for free().
#include<stdio.h>
#include<conio.h>
int main () {
char *title;
free(title);
return(0);
https://www.geeksforgeeks.org/structures-c/
Structures in C
What is a structure?
A structure is a user defined data type in C/C++. A structure creates a data type that
can be used to group items of possibly different types into a single type.
int main()
{
struct Point p1; // The variable p1 is declared like a normal variable
}
Note: In C++, the struct keyword is optional before in declaration of a variable. In C, it is
mandatory.
int main()
{
// A valid initialization. member x gets value 0 and y
// gets value 1. The order of declaration is followed.
struct Point p1 = {0, 1};
}
How to access structure elements?
Structure members are accessed using dot (.) operator.
filter_none
edit
play_arrow
brightness_4
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {0, 1};
Output:
x = 20, y = 1
struct Point
int x, y, z;
};
int main()
{
// Examples of initializtion using designated initialization
struct Point p1 = {.y = 0, .z = 1, .x = 2};
struct Point p2 = {.x = 20};
filter_none
edit
play_arrow
brightness_4
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
// Create an array of structures
struct Point arr[10];
// Access array members
arr[0].x = 10;
arr[0].y = 20;
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {1, 2};
// p2 is a pointer to structure p1
struct Point *p2 = &p1;