Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

C++ Notes void *ptr ;

Before using this pointer to point to a set of


Major topics covered: integers, we will at first cast it. It means that it
will be converted into a type of a pointer to an
 Memory Allocation integer. The syntax of doing this casting is
 Classes and Objects simple and is given below.

 Operation Overloading ( int * ) ptr ;


Here both int and * are written in parentheses.
The int is the data type into which we are
Tips for defining and undefining converting a void pointer ptr. Now ptr is a
pointer to an integer.
directives and use of macros
• All the preprocessor directives start with the #
sign calloc Function
• A symbol cannot be redefined without The syntax of the calloc function is as follows.
undefining it first
void *calloc (size_t n, size_t el_size)
• The conditional compilation directives help in
debugging the program This function takes two arguments. The first
argument is the required space in terms of
• Do not declare variable names starting with numbers while the second one is the size of
underscore the space. So we can say that we require n
• Always use parenthesis while defining elements of type int.
macros that takes arguments

malloc Function
The Pointer function for dynamic The malloc function takes one argument i.e.
memory Allocation: the number of bytes to be allocated. The
syntax of the function is void * malloc (size_t
The functions used for dynamic memory size) ;
allocation, provide a chunk of memory from
heap. The function does not know for what It returns a void pointer to the starting of the
data type this chunk of memory will be used? It chunk of the memory allocated from the heap
returns a pointer of type void. A pointer ptr of in case of the availability of that memory. If the
type void is declared as under. memory is not available or is fragmented (not
in a sequence), malloc will return a NULL
void *ptr ; pointer. While using malloc, we normally make
The ‘void’ is a special type of pointers. We use sizeof operator and a call to malloc
have to cast it before its use. The cast means function is written in the following way.
the conversion of ‘void’ into a type of pointer malloc (1000 * sizeof(int)) ;
that can be used for native data type like int,
char, float etc. The operator used for casting, in Here * is multiplication operator and not a
C, is standard cast operator. We write the dereference operator of a pointer.
name of the type in parentheses. Suppose we
have a pointer ptr defined as a void pointer like
Free( )
We use a function free. This function returns C language was developed by scientists of Bell
the allocated memory, got through calloc or Labs in 1970s. It is very lean and mean
malloc, back to the heap. The argument that is language, very concise but with lot of power. C
passed to this function is the pointer through conquered the programming world and took it
which we have allocated the memory earlier. In by storm. Major operating systems e.g., Unix
our program, we write was written in C language.
free (iptr) ; Going briefly into the history of languages, after
the Machine Language (language of 0s and
Realloc Function 1s), the Assembly Language was developed.
We can reallocate the same memory with a Using Assembly language, programmers could
new size according to our requirement. The use some symbolic codes, which were easier
function that reallocates the memory is realloc. to understand by novice people. After that
The syntax of realloc is given below. high-level languages like COBOL, FORTRAN
were developed.
void realloc (void * ptr, size_t size ) ;
Top down Structured Programming
Memory Leak
Basically, a problem is broken into small pieces
This is an error while managing memory or modules and each small piece corresponds
allocation. Suppose there was a pointer to a function. Following are its basic points:
pointing to a memory chunk through heap and
under some circumstance it got deleted or  Divide and Conquer
removed. Now there is no pointer for that
memory chunk and we cannot use this memory
 Single entry Single exit
in any of the programs. This can result is loss  Comment your programs
of every piece of memory if it continues. This
result in system halt or system crash and Placement of Variable declarations
computer can be rebooted to get that memory This has to do with the declaration of the
back after refreshing. For avoiding this variables inside the code. In C language, all
condition we should always free( ) the memory the variables are declared at the top of the
before exiting the pointer. The second function or code block and then we can use
necessary thing is that after freeing the them later on in the code.
memory, explicitly assign NULL to the pointer.
Its benefit is that this pointer can be checked if Inline Functions
it is pointing to some memory. While using macros, we use the name of the
Dangling Pointers macro in our program. Before the compilation
process starts the macro names are replaced
This is the opposite of memory leak. In this by the preprocessor with their definitions
case the pointer for memory chunk exists but (defined with #define).
somehow that memory gets deallocated and
when we use such a pointer to write a program Inline functions also work more or less in the
in the memory, it can cause unwanted same manner as macros. The functions are
problems. declared inline by writing inline keyword before
the name of the function. This is a directive to
the compiler and it causes the full definition of
the function to be inserted in each place the
History of C++ function is called. Inserting individual copies of
functions eliminates the overhead of calling a
function (such as loading parameters onto the we create variables of a class, a special name
stack). is used for them i.e. Objects.

Overloaded Functions “Instances of a class are called objects”.

Function overloading has the same concept With the definition of class, we have a new
that the name of the function will remain same data type like int, char etc. Here int i; means ‘i’
but its behavior may change. For example, if is an instance of data type int. When we take a
we want to take square root of a number. That variable of a class, it becomes the instance of
number can be an integer, float or a double that class, called object.
and depending on the type of the argument, we
may need to do different calculation.
While overloading functions, we will write
separate functions for separate data types but PRIVATE
the function name will remain same. Return
It is the keyword of hiding data from outside but
type can be different if we want to change, for
the data under private is accessible by its own
example in the above case we might want to
data members of class which are public.
return an int for square root function for int and
double for a square root of a double typed PUBLIC
variable. Now, we will declare them as under:
This keyword simply allows data members of
int sqrt (int i); class to be accessible or readable from outside
the class.
double sqrt (double d);
UTILITY FUNCTIONS
Now, we have two functions with the same
name. How will they be differentiated inside the These are a utility used by other methods of
program? The differentiation comes from the the class. However, they are not functions,
parameters, which are passed to these supposed to be accessed from outside the
functions. So the overloaded functions are class. So they are kept private.
differentiated using type and number of
arguments passed to the function and not by
the return type. CONSTRUCTORS: Generally, a constructor
initializes the object into a state that is
What is the advantage of this function
recognizable and acceptable. The default
overloading? Our program is more readable
constructor does not take any parameter. We
after using function overloading. Instead of
can have many constructors of a class by
having lot of functions doing the same kind of
overloading them.
work but with different names.
Types of Constructors
Classes and Objects
1. Compiler Generated Constructor
“A class includes both data members as well 2. Simple Constructor
as functions to manipulate that data”. 3. Parameterized Constructor
These functions are called ‘member
functions’. We also call them methods. So a DESTRUCTORS: The name of the
class has data (the variables) and functions to destructor is the same as that of a class with a
manipulate that data. A class is a ‘user preceding tilde sign (~).
defined’ data type. This way, we expand the
language by creating a new data type. When
The destructor cannot be overloaded. This delete iptr; // Allocated is freed and returned to
means that there will be only one destructor for the free store.
a class.
STRUCTURES IN C++
The destructor is used normally for this
purpose to make sure that any allocated Structures and classes in C++ are quite similar. C+
+ structure is declared with the same keyword
memory is de-allocated and returned to free
struct as in C. Unlike C structure, C++ structure
store (heap). can have data and member functions. The
The destructors take no arguments. The difference between class and structure is of
destructors don’t return a value. So they don’t visibility. Every data member or function written
inside the structure is public (visible from outside)
have a return type and no return statement in
by default unless declared otherwise. Similarly,
the body.
everything declared inside a class is private (not
visible from outside) by default unless declared as
public.

TIPS Messages and Methods


• Explicitly write keyword private in the class When we create an object, we ask that object
definition. to do something by calling a function. This way
• Separate the interface and implementation. of asking objects in Windows operating system
is called Messaging or in other words function
• The default constructor has no arguments. calling is sending a message to the object.
• Constructor has the same name as of class. Sending a message is a synonym of calling a
method of an object. The word ‘method’ is from
• The data members of the class are initialized the fact that it is a way of doing something. So
at runtime. the whole program is sending messages and
• Initializing the data members in the definition getting responses back. It is a different way of
of the class is a syntax error. looking at things.

Tips
MEMORY Allocation in C++ - Classes are one way of extending the C++
language.
NEW: The new operator is used in C++ for - Whenever new operator is used, no number of
memory allocation and its syntax is bytes or sizeof operator is required and no cast is
applied to convert the pointer to the required type.
new int;
- Whenever new operator is called to create an
int *iptr; object, the constructor is also called for that object.
iptr = new int; It is a good practice that whenever you write a
class, use a constructor function to initialize the
DELETE: Delete operator is used to free the data members to some meaningful values.
memory when the allocation is done by using - The usual practice is to use constructor to allocate
new as shown below: memory or system resources and destructors to de-
allocate or return the resources back to the system.
int *iptr;
- In C language, the region of memory allocated at
iptr = new int [10]; // Memory for 10 ints is runtime is called heap. However, in C++, the region
allocated dynamically. of available memory is called free store. There are
different functions in C and C++ to manipulate declare the friend functions at the top of the
memory at runtime. However, all C functions are class definition. So, the friend functions are
useable in C++ code. declared at the start of the class definition,
- The memory allocated from free store or heap is followed by the private data and public data.
a system resource and is not returned back to the friend return_type friend_function_name(int, char);
system unless explicitly freed using delete or free
operators. FRIEND CLASS
- If the memory in the free store is not sufficient A friend class works same as a friend function.
enough to fulfill the request, malloc() function In this programmer can create a friend class
returns NULL pointer. Similarly, the new function
and this class would have access to all the
returns 0 in case the request could not be fulfilled.
data members of that class in which its
- Whenever we use new operator, the returned prototype is declared. Its syntax is as:
value from the new should be checked against 0
for any possible failures. friend class class-name ;

- While writing classes, good programming practice SUMMARY


is to write private keyword explicitly, despite the
fact that this is the default scope. Additionally, the The principles of friendship of functions and
good practice is to write public or private classes are that the friendship is granted, not
keywords only once in the class or structure taken. So a class declares its friend functions
definitions, though there is no syntactical or logical and friend classes. If a class declares another
problems in writing them multiple times. class as a friend, it is not always reciprocal. So
declaration and granting of a right is one way.
FRIEND FUNCTION The owner of the right grants it. So the class
itself grants the privilege of access to outsider
Friend functions are not member functions of
functions or to other classes. It is not transitive.
the class. The class itself declares the friend
It does not go ‘A is a friend of B and B is a
functions. The prototype of friend functions is
friend of C therefore A is a friend of C’. It does
written in the definition of the class with the
not work that way. It is restricted to a one-step
keyword ‘friend’. These functions have access
relationship. If A is a friend of B, and B is a
to the private data member of the class,
friend of C. If A wants C to be a friend, it
which means they have access to everything in
has to declare, “C is my friend”.
the class. Normally we pass an object of the
class to these functions in the argument list so REFERENCE
that it can manipulate the data of the object.
The reference in a way keeps the address of
Question is how to declare and call it?
the data entity. But it is not really an address it
Answer: If we have a class, suppose ‘Date’ and is a synonym, it is a different name for the
want to declare a friend function of this class. entity. We have to initialize the reference when
In the definition of the class, we will write the we declare it. It has to point to some existing
friend function’s prototype with the keyword data type or data value. In other words, a
‘friend’. To access the private data, friend reference cannot be NULL. So immediately,
function will need the object. Therefore, usually when we define a reference, we have to
in the parameter list of friend function, we declare it. This rule does not apply to functions.
provide the object of that class. Normally, the When we are writing the argument list of a
programmers work this way. As the friend function and say that it will get a reference
function is not affected by the private or public argument, here it is not needed to initialize the
keyword, so we can declare it anywhere inside reference. This reference will be passed by the
the class definition. Programmers generally calling function. But in the main program if we
declare a reference then we have to initialize it. • Reference variables must be initialized
When a reference is initialized, we cannot immediately when they are declared.
reassign any other value to it. For example, we
• To avoid dangling reference, don’t return the
have ref that is a reference to an integer. In the
reference of a local variable from a function.
program we write the line int &ref = j;
• In functions that return reference, use global
The difference between pointers and
or static variables.
references is that we can do arithmetic with
pointers. We can increment, decrement and • The reference data types are used as
reassign a pointer. This cannot be done with ordinary variables without any dereference
references. We cannot increment, decrement operator.
or reassign references.

OPERATOR OVERLOADING
Operator Overloading is quite similar to
References as Return Values
Function Overloading. There are two types of
A function itself can return a reference. The operators to overload: unary and binary. C++
syntax of declaration of such a function will be built-in operators work for built-in (primitive)
as under. types but for user defined data types, user has
to write his/her own operators.
datatype& function_name (parameter list)
There are some restriction while performing
Suppose we have a function myfunc that Operator Overloading. For example, only
returns the reference to an integer. The existing C++ operators are overloaded without
declaration of it will be as: creating a new one in the language. Also, it
int & myfunc() ; should not impact the type, semantics
(behavior), arity (number of operands
Dangling Reference required), precedence and associativity of the
When a reference is declared to a local operator. Following operators cannot be
variable and somehow that variable dies; now overloaded.
the reference call is to nowhere and this is . : :: .* ? sizeof
termed as dangling reference.
For binary member operators, operands on the
To avoid such situations, one can always try to left drives (calls) the operation.
reference only variables in global scope rather
than local scope, as global variable always Operator functions written as non-members but
exists and cannot be removed accidentally by friends of the class, get both the operands as
a function. Or you can also declare a reference their arguments. Operators can be written as
for static variables. non-members and even without making them
friends. But this is tedious and less efficient
Tips way, therefore, it is not recommended.
• The use of reference data type is the this pointer
implementation of call by reference in an
elegant way. Whenever an object calls a member function,
the function implicitly gets a pointer from the
• We cannot do arithmetic with references like
calling object. That pointer is known as this
pointers.
pointer. ‘this’ is a key word. We cannot use it
as a variable name. ‘this’ pointer is present in
the function, referring to the calling object.
Syntax is as:
date;
this -> date;
(this*).date;

You might also like