You are on page 1of 28

Abstraction in C++

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.

Abstraction using access specifiers


Access specifiers are the main pillar of implementing abstraction in C++. We can use
access specifiers to enforce restrictions on class members. For example:
 Members declared as public in a class, can be accessed from anywhere in the
program.
 Members declared as private in a class, can be accessed only from within the
class. They are not allowed to be accessed from any part of code outside the
class.

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:

// method to set values of


// private members
void set(int x, int y)
{
a = x;
b = y;
}

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

Data Abstraction in C++


Data abstraction refers to providing only essential information to the
outside world and hiding their background details, i.e., to represent the
needed information in program without presenting the details.

Data abstraction is a programming (and design) technique that relies on the


separation of interface and implementation.

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.

Thus, we can say a television clearly separates its internal implementation


from its external interface and you can play with its interfaces like the
power button, channel changer, and volume control without having any
knowledge of its internals.

In C++, classes provides great level of data abstraction. They provide


sufficient public methods to the outside world to play with the functionality
of the object and to manipulate object data, i.e., state without actually
knowing how class has been implemented internally.

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>

using namespace std;

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.

Access Labels Enforce Abstraction


In C++, we use access labels to define the abstract interface to the class. A
class may contain zero or more access labels −

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

Benefits of Data Abstraction


Data abstraction provides two important advantages −

 Class internals are protected from inadvertent user-level errors, which might
corrupt the state of the object.

 The class implementation may evolve over time in response to changing


requirements or bug reports without requiring change in user-level code.

 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>

using namespace std;

class Adder {

public:

// constructor

Adder(int i = 0) {

total = i;

// interface to outside world

void addNum(int number) {

total += number;

// interface to outside world

int getTotal() {

return total;

};

private:

// hidden data from outside world

int total;
};

int main() {

Adder a;

a.addNum(10);

a.addNum(20);

a.addNum(30);

cout << "Total " << a.getTotal() <<endl;

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 statements (code) − This is the part of a program that performs


actions and they are called functions.

 Program data − The data is the information of the program which gets affected
by the program functions.

Encapsulation is an Object Oriented Programming concept that binds


together the data and functions that manipulate the data, and that keeps
both safe from outside interference and misuse. Data encapsulation led to
the important OOP concept of data hiding.

Data encapsulation is a mechanism of bundling the data, and the


functions that use them and data abstraction is a mechanism of exposing
only the interfaces and hiding the implementation details from the user.

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.

To make parts of a class public (i.e., accessible to other parts of your


program), you must declare them after the public keyword. All variables or
functions defined after the public specifier are accessible by all other
functions in your program.
Making one class a friend of another exposes the implementation details
and reduces encapsulation. The ideal is to keep as many of the details of
each class hidden from all other classes as possible.

Data Encapsulation Example


Any C++ program where you implement a class with public and private
members is an example of data encapsulation and data abstraction.
Consider the following example −
Live Demo

#include <iostream>

using namespace std;

class Adder {

public:

// constructor

Adder(int i = 0) {

total = i;

// interface to outside world

void addNum(int number) {

total += number;

// interface to outside world

int getTotal() {

return total;

};
private:

// hidden data from outside world

int total;

};

int main() {

Adder a;

a.addNum(10);

a.addNum(20);

a.addNum(30);

cout << "Total " << a.getTotal() <<endl;

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.

A pointer points to an address location

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

Declare and Initialize Pointers


In order to declare a variable as a pointer, you use the asterisk (*):
1. int *menu; //pointer to an integer
2. char *code; //pointer to a character
3. double *pay; //pointer to double

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.

Increment and Decrement Pointers


When you increment a variable, you usually add 1 to it. For example, the value of i in the following
code will be 1:

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.

Incrementing the Address of Pointer


The following code loops through an array, incrementing the pointer along the way. In the for loop, it
displays the address (ptr) and the value (*ptr):

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.

In C, there are two types of parameters and they are as follows...

 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

called function and they are as follows...


In C Programming Language, there are two methods to pass parameters from calling function to
called function and they are as follows...

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

printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;

swap(num1, num2) ; // calling function

printf("\nAfter swap: num1 = %d\nnum2 = %d", num1, num2);


getch() ;
}
void swap(int a, int b) // called function
{
int temp ;
temp = a ;
a=b;
b = temp ;
}

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 ;

printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;


swap(&num1, &num2) ; // calling function

printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);


getch() ;
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}

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

from same function itself. The recursive function is definedd as follows...

A function called by itself is called recursive function.

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

recursive function gets terminated.

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>

int factorial( int ) ;


int main()
{
int fact, n ;
printf("Enter any positive integer: ") ;
scanf("%d", &n) ;
fact = factorial( n ) ;
printf("\nFactorial of %d is %d\n", n, fact) ;
return 0;
}
int factorial( int n )
{
int temp ;
if( n == 0)
return 1 ;
else
temp = n * factorial( n-1 ) ; // recursive function call
return temp ;
}

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

Dynamic Memory Allocation in C


In C programming language, when we declare variables memory is allocated in space called stack.

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.

Dynamic memory allocation is defined as follow...

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;

title = (char *) malloc(15);

strcpy(title, "c programming");


printf("String = %s, Address = %u\n", title, 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);

ptr = (int*)calloc(n, sizeof(int));


printf("Enter %d numbers:\n",n);
for( i=0 ; i < n ; i++ ) {
scanf("%d",&ptr[i]);
}

printf("The numbers entered are: ");


for( i=0 ; i < n ; i++ ) {
printf("%d ",ptr[i]);
}

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;

title = (char *) malloc(15);

strcpy(title, "c programming");


printf("Before modification : String = %s, Address = %u\n", title, title);

title = (char*) realloc(title, 30);

strcpy(title,"C Programming Language");


printf("After modification : String = %s, Address = %u\n", title, 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;

title = (char *) malloc(15);


strcpy(title, "c programming");
printf("Before modification : String = %s, Address = %u\n", title, title);

title = (char*) realloc(title, 30);

strcpy(title,"C Programming Language");


printf("After modification : String = %s, Address = %u\n", title, 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.

How to create a structure?


‘struct’ keyword is used to create a structure. Following is an example.
filter_none
brightness_4
struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
How to declare structure variables?
A structure variable can either be declared with structure declaration or as a separate
declaration like basic types.
filter_none
brightness_4
// A variable declaration with structure declaration.
struct Point
{
int x, y;
} p1; // The variable p1 is declared with 'Point'

// A variable declaration like basic data types


struct Point
{
int x, y;
};

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.

How to initialize structure members?


Structure members cannot be initialized with declaration. For example the following C
program fails in compilation.
filter_none
brightness_4
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
The reason for above error is simple, when a datatype is declared, no memory is
allocated for it. Memory is allocated only when variables are created.
Structure members can be initialized using curly braces ‘{}’. For example, following is a
valid initialization.
filter_none
brightness_4
struct Point
{
int x, y;
};

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

// Accesing members of point p1


p1.x = 20;
printf ("x = %d, y = %d", p1.x, p1.y);
return 0;

Output:

x = 20, y = 1

What is designated Initialization?


Designated Initialization allows structure members to be initialized in any order. This
feature has been added in C99 standard.
filter_none
edit
play_arrow
brightness_4
#include<stdio.h>

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

printf ("x = %d, y = %d, z = %d\n", p1.x, p1.y, p1.z);


printf ("x = %d", p2.x);
return 0;
}
Output:
x = 2, y = 0, z = 1
x = 20
This feature is not available in C++ and works only in C.

What is an array of structures?


Like other primitive data types, we can create an array of structures.

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;

printf("%d %d", arr[0].x, arr[0].y);


return 0;
}
Output:
10 20

What is a structure pointer?


Like primitive types, we can have pointer to a structure. If we have a pointer to structure,
members are accessed using arrow ( -> ) operator.
filter_none
edit
play_arrow
brightness_4
#include<stdio.h>

struct Point
{
int x, y;
};

int main()
{
struct Point p1 = {1, 2};

// p2 is a pointer to structure p1
struct Point *p2 = &p1;

// Accessing structure members using structure pointer


printf("%d %d", p2->x, p2->y);
return 0;
}
Output:
1 2

You might also like