0% found this document useful (0 votes)
5 views18 pages

OOP Basic Tutorial

Uploaded by

Ahmad Raza
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)
5 views18 pages

OOP Basic Tutorial

Uploaded by

Ahmad Raza
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/ 18

Course : Object Oriented Paradigm

Teacher : Prof. Nabeel Sabir

In this Short Tutorial, you will learn the basics of the following concepts with Examples :

 Dynamic memory allocation using functions


 Basics of constructors and destructors ( both default and overloaded)
 Concept of default parameter constructor
 Memory leakage if we don’t use our own destructor
 Passing object to a member function by value and by reference
 Returning object by value and reference (using this pointer)

1. Constructor :
First question came in our mind when we hear a new word that what is it ? So
constructor is basically a method in a class which is automatically invoked by compiler when the
object of the class is created. In Simple and short words, Constructor is used to create an object
at a valid state.

In Object oriented paradigm functions in classes are called Methods. Its general syntax is
:

class_name (arguments)
{
// Body of Constructor
}

Nabeel baloch
Some more points to clear the concept of constructors :

 Constructor is used to allocate memories for an object or to initialize the values to the
data members of the class.
 Constructor name is same as the name of the class.
 It doesn’t have a return type (even not a void) . if you write any return type even void ,
compiler will give you an error.
 It may or may not have arguments. You must supply arguments to a constructor, if you
don’t supply, compiler will generate default constructor for you with no arguments and
empty body.
 It must be a public member function.
 We can create more than one constructor in a class.
 When we don’t create a constructor explicitly, compiler does that for us implicitly at
backend and invoke it at the time of creation of the object.
 The constructor which compiler creates implicitly, contains no arguments an empty
body .
 Constructor are of Default , Parameterized and Copy Constructors.

We will discuss just default and parameterized constructors in this tutorial.


Here is an simple example given below which further explains the concepts of a constructor :

Nabeel baloch
When this program will compiled and executed, it will generate the following ouput :

In this example, the is a class named Line which contains the prototypes of setter, getter, and a
constructor which are written offline.

Void line :: setlength(double len) : It receives a double value as a parameter and initialize it to
data member of class length in its body .

Nabeel baloch
Double line :: getlength(void) : It has no parameter because it just returns the value of private
data member (length) /

Offline Method: Method whose prototype are declared in a class and defined outside that class
using scope resolution operator (::).

2. Default Constructor :
A default constructor is a constructor that either has no
parameters, or if it has parameters, all the parameters have default values. It is a good
programming practice to write our own default constructor (constructor which has no
parameters) . In above example, method Line () is a default constructor with no argument.

Overloaded Constructors :
As we know that functions can be overloaded. So constructors are
also functions they can also be overloaded like any other simple functions . This will help
to create many constructors in a class, means we can create an object in different states
(containing different values). Different constructor can allow creation of objects with desired
type of values.

Overloading a constructor is very similar to function overloading. Just change the


signature (no. of arguments and type of arguments) of the constructor.

Its syntax is :
<class name> <object_name> (arguments to pass);
e.g Box b; or Box b2(9);

Now here we will discuss the simple example of overloading constructors.

Nabeel baloch
Nabeel baloch
and its output is

This is a simple example to show the concept of overloaded constructors. This program just
takes 1 , 2 or 3 values for (height , width and length of a Box) as arguments, then simply stores
and shows it on console .

Nabeel baloch
Box :: Box() : This default constructor (which is defined as offline Methods) just Create an
object with all data member values as zero .

Box :: Box(int k) : This is an overloaded constructor (which is defined as offline Methods), it


Creates an object with all data member same values with the value we are passing from
in line 50 that is :
Box b2(9) ;
So value 9 in k parameter will be initialized in this overloaded function.

Box :: Box (int x, int y, int z) : This is an another overloaded constructor (which is defined same
as other offline Methods), it contains three parameters x , y , and z. x is initializing width
private data member , y to height and z to length .

So all three constructors (one default and two overloaded constructors) are creating objects at
three different states.

Void Box :: show () : This function is just displaying the value of private members on console.

3. Concept of Default Parameters In Constructor


what are default parameters ?
A default argument/parameter is a value given in the declaration that the compiler
automatically inserts if you don’t provide a value in the function/Constructor call.

Nabeel baloch
Some Basic Problems while dealing with default parameters.

In constructor header line 8 , we must provide a left value first because compiler copy first left
argument of signature to first left prototype argument and then copy second left argument of
signature to second left prototype argument and so on mapping from left to right .

when we will pass values of hours and minutes, it will automatically use third default value i.e
Time (int h , int m , int s=56);
Now in main line 29 , we can pas
Time T2 (1,2);
Time T2 (1,26,36);

In constructor header line 8 , we can also pass values of hours just, it will automatically use
second and third default value i.e
Time (int h , int m=25 , int s=56);
Now in main line 29 , we can pas

Nabeel baloch
Time T2 (1);
Time T2 (1,26);
Time T2 (1,26,25);

And last condition is in the picture above having all default values.

4. Destructor
A destructor is also a special member function whose name is theclass name
proceeded by the ~ character. It is executed whenever an object of it's class goes out of scope
or whenever the delete expression is applied to a pointer to the object of that class. It is
invoked as reverse order in which constructors are invoked .

Its general syntax is :

~ class_name () // with no arguments


{
// Body of Destructor
}

Some more points about destructor to clear its concept.

 It finalizes objects of the class type.


 Typically, a destructor de-allocates the memory allocated in heap for any data
member of the class by using delete.
 It does not have any return type therefore doesn’t need return statements in its
body.
 Its name is also same as the class name.

 Destructors contains no arguments because it is a special function use to just de-


allocate memory allocated in Heap.
 It should be written under public access specifier.
 It can not be overloaded.
 Destructor can be very useful for releasing resources before coming out of the
program like closing files, releasing memories etc.

Note: For a good programming practice, always write destructor when you are using a pointer
as a data member in your class.

Nabeel baloch
Commonly Problem :
While writing the body of the destructor mostly programmers face this issue.

e.g
~ Student()
{
If(Name=NULL) // Error, Missing ! operator before =
{
Delete [] Name ;
}
}

Explaining more about destructor by taking same example discussed earlier

Nabeel baloch
And its output is

Line :: ~ Line () : Destructor in this case is not doing anything in this program except just
displaying that object is destroyed when it’s scope goes out. I wrote a getch() function in
destructor to just show the it is executed before going out of object’s scope .

5. Memory Leakage Issue Occur without using destructor


What is Memory Leakage ?
Memory leaks occur when new memory is allocated dynamically (On Heap) and never
de-allocated. In C programs, new memory is allocated by the malloc or calloc functions, and de-
allocated by the free function. In C++, new memory is usually allocated by the new operator
and de-allocated by the delete or the delete [] operator .
Mostly programmers allocate memory on heap in there programs but forget to delete
them, then it may cause many errors and most of the time there program crashes.
Another common mistake is overwriting a variable containing dynamic memory without
freeing any existing memory first. For example, assume that Name is a data member of a class,
and in one of the methods (other than the constructor ) programmers do such mistakes
Name = new char [size] ; // cause memory leakage
Even it should be like
Delete [] Name ;
Name = new char [size] ;

Nabeel baloch
Without using destructor allocated memory on heap can not be de-allocated.
Using a simple Example now

And its output is

In this example if we can not create a destructor it will leak memory allocate in heap in
constructor of class student.

Nabeel baloch
6. Dynamic Memory Allocation Using Functions
The memory we use in our C++ program s divided in to two parts.

Stack: All variables that we declare in a function reserves memory in stack or memory
allocated at compile time.

Heap: To allocate memory at runtime we use heap and c,c++ provides us there standard
functions and keywords to allocate memory on heap .

Many times, you are not aware in advance how much memory you will need to store particular
information in a defined variable and the size of required memory can be determined at run
time.
You can allocate memory at run time within the heap for the variable of a given type using a
special operator in C++ which returns the address of the space allocated. This operator is
called new operator.
If you are not in need of dynamically allocated memory anymore, you can use delete operator,
which de-allocates memory previously allocated by new operator.

Syntax of Using new Operator :


Pointer variable = New data_type ; // for single location
Pointer variable = New data_type [] ; // for Array / Consecutive locations

Syntax of Using delete operator :


Delete pointer ; // to de-allocate a single location
Delete [] pointer ; // to de-allocate an Array

In above picture :

Memory for private data member name which is a character pointer is Allocated in Heap .
We can also create our own function to allocate memory on heap. E.g
Here this is a generic function to allocate memory of any data type on heap.

template <typename T>


void Dynamic_Memory_Allocation (T *Array , size_t size)
{

Nabeel baloch
Array = new T[size];
}

7. When an object is Passed By Reference to a Function :


The copy constructor is a constructor which creates an object by initializing it with an object of
the same class, which has been created previously. The copy constructor is used to:

 Initialize one object from another of the same type.


 Copy an object to pass it as an argument to a function.
 Copy an object to return it from a function.

If a copy constructor is not defined in a class, the compiler itself defines one.If the class has
pointer variables and has some dynamic memory allocations, then it is a must to have a copy
constructor. The most common form of copy constructor is shown here:

We can pas objects of a class by reference to any function. It also has advantages and
disadvantages . In Passing by reference, it will not call copy constructor and drawback is object
is at risk because any statement can change its data member value so for a good programming
practice we must receive an object in a constant parameter like in a user defined copy
constructor.

When an object is passed by value, compiler creates a copy constructor, invokes it and do a
shallow copy. For deep copy we have to make a user defined copy constructor with parameter
passed by reference.

Nabeel baloch
Output Is :

Nabeel baloch
In pass by reference we can also make a deep copy of that particular object. All members
whose memories are allocated in heap are also copied as shown in copy constructor .

8. When an object is returned through a function (Using this


Pointer)
Example in which object is return by value :

Output :

Example in which object is return by Reference :

Nabeel baloch
2nd Example func() is returning a reference to current object.
1st code func() is returning the copy (by value) of the object.

For 2nd case, If you decide to return by value then prefer to return a const reference; i.e. const
demo& fun(); and later you can copy it if needed. Simply returning reference makes the object
modifiable, which may accidently edit the content without intent

For 1st case, Do NOT return the object by value, because it can create unnecessary temporary
copy which will effect the memory/performance of your code

In code 2 Demo obj creates a fresh copy of demo obj is initialized using demo's default
constructor 'demo():a(9){}'. Obj.func() returns a reference to (already existing) obj.

In code 1 obj.func() creates a new Demo type object using demo's copy constructor (in your
case it is compiler generated) and returns that copy to the caller.

Nabeel baloch
Nabeel baloch

You might also like