Class is a key feature in C++. It makes programming much easier. To implement the class we need to create objects for that class. So, let's start with 'what is a class and an object?'
How to create a class
To create a class you need to use the 'class' keyword. After that you need to specify the name of the class. The body of the class should be enclosed with curly braces. At the end you have to add a semicolon. For example,
class Circle(){ private: int r; public: getdata(); area(); };
This is a way you create a class. You can write the function in the class and also outside the class. In the above example only the name of the function is written. This means that the function needs to be written outside the class. If you wanted you can write the function there itself like:
class Circle(){ private: int r; public: getdata(){ cout<<"Enter the radius: "<<endl; cin>>r; } area(){ float a; a=3.14*r*r; cout<<"The area is : "<<a<<endl; } };
If you want to write the function outside the class you have to use the scope resoulion operator (::). Consider the following example:
void Circle::getdata(){ cout<<"Enter the radius: "<<endl; cin>>r; }
Access Specifiers
They are used to specify which functions can access the data of a function. Private is an access specifier that is used to secure the data to restrict the other functions from accessing the data in a function. If you use the 'public' access specifier it can exchange the data with other functions and classes. If you don't specify anything, C++ will consider it as private.
Objects
Now to access those functions you need to create an object. To create an object you have to do it in the main function. You have to specify the name of the class. For example,
int main(){ Circle c1; c1.getdata(); c1.area(); getch(); return 0; }
Advantage of using classes
DYNAMIC MEMORY ALLOCATION:
Dynamic memory allocation is the means by which a program can obtain memory while it is running. Global variables are allocated storage at compile time. Nonstatic , local variables use the stack. However, niether global nor local variables can be added during program execution. Yet there will be times when the storage needs of a program cannot not known ahead of time. For example , a program might want to use a dynamic data structure,such as a linked list or a binary tree.Such structures are inherently dynamic in nature,growing and shrinking as needed. To implement such a data structure requires that a program to be able to allocate and free memory as needed.
Memory allocated by c’s dynamic allocation functions is obtained from the heap. The heap is free memory that is not used by your program,the os,or any other proram running in your computer. The size of the heap cannot usually be known in advance,but it typically contains a very large amount of free memory.
The following functions are used in C for dynamic memory allocation:
- Alloc ( ): The alloc function is used to aloocate a region or block of size bytes in length of the heap. The general declaration of the alloc() function is:
Char *alloc(size)
Unsigned int size;
Some C compiler versions fill the allocated region with zeros. All versions return some kind of an error when there is no more space left to allocate, either 0,-1 or printing a message to the system .
- Malloc ( ): The malloc () function is used to allocate heap storage. Its name stands for memory allocation .The allocated regiojn is not filled with zeros. The starting address is returned if the function is successful. A zero is returned if the function attempts to get a block of memory fails
Char *malloc(size)
Unsigned int size;
- Calloc ( ): The calloc function is used to allocate the continuous memory or element by element basis. The name stands for calculated allocation.It is useful in arrays and array like structures where continuity of memory is required. The starting address of the area is returned if the function is successful.A zero is returned if the function attempt to get a block a memory fails.
The general declaration of calloc function is given as:
Char *calloc(elements,element size)
Unsigned int elements;
Unsigned int element_size;
- Realloc (): The realloc function is used to increase or decrease the size of the block of heap memory to the size , specific by size preserving the address and contents of the beginning of the block. The function reealloc() can diminish the size of the allocated area.
The general declaration of realloc() function is:
Char *realloc(old block,size)
Char *old block;
Unsigned int size;
The realloc function returns the address of the newly allocated region which is same as the old block. It returns a zero if an attempt to create a new block is unsuccessful.
- Free(): the free function is used to free a portion of storage within the heap previously allocated by alloc(),malloc(),calloc(),or realloc(). The storage returns to heap,making it available for further heap activity. The pointer that is the arguments to free() is the starting address for the region allocated.
Its general declaration is:
Int free (pointer)
Char *pointer;
This is a technique to sort a given array in an acending order.
Here is the steps we follow while performing quick sort :-
- The last element of array is assumed to be "infinity".
- " i " (which is an integer type variable) point to the lowest index and " j " (another integer type variable) points to the highest index of the array.
- First element is assinged asthe "pivot" element.
- " i " is incremented till larger or equal element than pivot is found.
- " j " is decremented till smaller or equal element then pivot is found.
- If " i " is less than " j " then interchange a[i] with a[j] and repeat the steps 4 and 5, else interchange a[j] and "pivot".
When the element (a[j]) is exchanged with "pivot" then the position of that element is fixed in the array and divides the array into two parts ie. on the right of the array all maximum elemnts will be there and on the left of the array all minimum elements will be there. Now sort the two parts in the same manner as of the parent array.
Now as we see that the no. of iterations will be " n log2(n )" since " 2x " times of comparison is made in one iteration and total number of iterations is "n", hence the total number of iterations will be " n X 2x " ie. " n log2(n) ".
Hence, the complexcity of this sorting technique is n log2(n).
" n " here is the size of the array.
Now we will discuss how did the term log2(n) came.
Since 2x iterations are made and in the worst case the "2x = n".
Then,
x = log2(n)
Where " log2 " refers to the base of logarithmic function ie. 2.
Hope when you read this article your understanding will we enhanced and you will be able to write the coding efficiently.
When objects are declared that is constructed for a particular class then this objects will occupy certain memory locations. The data members of these objects will have garbage values. In object oriented applications we will prefer that this values should not be garbage rather the datamember of the objects should be automatically initialised with some predefined values.
For eg:- When we declare object of class count we will prefer its initial value to be zero than garbage. Similarly if we declare object of class abc we may prefer the side of the abc as units than the garbage ( unit abc)The constructors are the fn which are used for automatic initialization of data members of the objects.
Constructors function:
The constructor fn is a fn that has got same name as that of the class.
Construction function without parameter / default constructor:
Develop a class cube with data member side. The class should have following member function.
Setside ( ) ; 2) getside ( ) ; 3) display ( ) ; 4) A function to calculate and return the volume of the cube. 5) a construction fn that will initialize side of the cube with 1
# include
class cube ;
{
int side ;
public:
void setside (int) ;
void getside ( ) ;
void display ( ) ;
int volume ( ) ;
cube ( ) ;
};
{
cube :: cube ( ) ;
side=1 ;
}
void cube :: setside ( int s )
{
side = s ;
}
void cube :: display ( )
{
cout<<"side= "<
}
int cube :: volume ( )
{
return side x side x side ;
}
void main ( )
{
cube C1 ;
C1.display ( ) ;
cout<<"volume="<
C1.setside (5) ;
C1. display ( ) ;
cout<<"volume="<
}
side=1
volume=1
side=5
volume=125.
In the above program we declare constructor function without parameter.
Consider the declaration cube C1; with this statement we declare i.e. we construct object C1 of class cube. Memory space of two bytes will be allocated for the object ( ). The constructor fn gets called automatically for the object C1. And hence C1. Side will be initialized with value 1. Thus automatic object initialization with predefined value is obtained using constructor fn.
Limitation:-
In the above program whenever object of class cube is constructed its side will be automatically initialized with 1. It is better than having the garbage value for the side. However the limitation is the side will be compulsorily initialized with one. We overcome this limitation by writing constructor with parameter.
Develop a class cube whose description is very similar to the previous program. The only difference is define 2 construction fn within this class. One without parameter and other with parameter. Write suitable main fn.
# include
class cube{
int side ;
public:
void setside (int) ;
void getside ( ) ;
void display ( ) ;
int volume ( ) ;
cube ( ) ;
cube (int) ;
};
cube :: cube ( )
{
side=1 ;
}
cube :: cube (int 5)
{
side=5 ;
}
void cube :: setside (int s)
{
side=s ;
}
void cube :: getside ( )
{
cin>>side ;
}
void cube :: display ( )
{
cout<<"side="<
}
int cube :: volume ( )
{
return side*side*side ;
}
void main ( ) ;
{
Cube C1, C2 (4), C3=5 ;
C1.display ( ) ;
Cout<<"volume="C1.volume ( ) <<'\n' ;
C2.display ( ) ;
Cout<<"volume="<
C3.display ( );
Cout<<"volume="<
}
Side=1
volume=1
side=4
volume=6
side= 5
volume=125.
In the above class we have declare two constructors one with without parameter and other with parameters.
# include
class cube
{
int side ;
public:
: : : :
: : : :
};
cube :: cube (int 5 )
{
Side=5 ;
}
The body of set side, get side, display, volumes main will be same as that of the previous program.
Explanation:-
For object C1 since the parameter is not passed the constructor will utilized default value and hence C1.side = 1, for object C2 and C3. Since the parameter is present the default value will not be ustilised and C2.side and C3.side will be initialized with 4 and 5 respectively.
Explicit call of the constructor.Develop a class counter with data member count.
The class should have following member fn:
get count ( ) 2) display ( ) 3) increment ( ) 4) decrement ( ) 5) A constructor function that will intilise the count with the accepted value and if the value is not supplied the count should be initialized with zero.
# include
class counter{
int count ;
public:
void getcount ( ) ;
void display ( ) ;
void increment ( ) ;
void decrement ( ) ;
counter (int=0) ;
};
void counter :: get count ( )
{
cin>>count ;
}
void counter :: increment ( )
{
count ++ ;
}
void counter :: decrement ( )
{
count - - ;
}
void counter :: display ( )
{
cout<<"count="<
In the above statement the constructor fn is called explicitly for object C2 and 50 is passed as parameters. The C2.count is initialized with 50.the C2.count is initialized when the program is running. Thus the dynamic initialization is obtained using the constructor function. Similar explanation is applicable for C1.counter (10);
- Copy constructor:
Consider the following eg:-
# include
Class pqr
{
int data ;
public:
void display ( ) ;
pqr ( int=0) ; // Normal constructor
pqr (pqr &) ; // Copy constructor
};
void pqr :: display ( )
{
cout<
-
The destructor has got same name as that of the class.
-
The destructor do not have any return type not even void
-
The name of the destruction fn will be proceed i.e. preferred with the character
-
The destructor fn will called automatically when the objects are deallocated i.e. destructed from the memory.
-
The destructor also comes in picture when dynamically allocated objects are made free i.e. deleted.
Develop a class counter with datamember count.one class will have following member fn
get count ( ) ; display ( ) ; increment ( ) ; decrement ( ) ;
constructor with default parameter destructor fn with appropriate logic.
# include
class counter
{
int count ;
public:
void getcount ( ) ;
void display ( ) ;
void increment ( ) ;
void decrement ( ) ;
counter ( int=0 ) ;
~ counter ( ) ;
};
void counter :: getcount ( )
{
cin>>count ;
}
void counter :: display ( )
{
cout<
Object with value 25 will be destructed object with value a will been destructed object with value has been destructed.
Explanation:
→ In the above program we declare destructor function within the class counter. In the main function we declare i.e we construct objects C1,C2 and C3. Constructor fn will be called automatically for all the three objects in the order C1,C2, and C3.
→ When main fn is about to finish then the complies will understand that the objects are deallocated from the memory. The destructor fn will be called automatically for all the three objects in the order C3, C2,and C1. For every object the destructor fn is called first and once the destructor fn execution is finished the corresponding object is deallocated from the memory.
- A fn to get the CN from user.
- A fn to display the CN
- A fn to add the two CN which are accepted as parameters.
- Multiply
- Subtract
- Divide
Method II
Addition of two CN.
#include
class complex
{
float r, i ;
public:
void getcomplex ( );
void display ( );
complex add (complex);
complex subtract (complex);
complex multiply (complex);
complex divide (complex);
};
void complex :: get complex ( )
{
cin>>r>>i;
}
void complex :: display ( ).
{
cout< } complex complex :: add (complex c) { complex temp; temp.r = r+c.r; temp.i = i+c.i; return temp ; } complex complex :: multiply (complex c) { complex temp; temp.r = r * c.r – i * c.i ; temp.i = i * c.r + r* c.i ; return temp ; } complex complex :: divide (complex c) { temp.r = (r*c.r + i * c.i) / ( c.r*c.r+c.i+c.i) temp.i = (1*c.r – r* c.1) / (c.r*c.r+c.i*c.i) ; return temp ; } complex complex :: subtract (complex) { temp.r = r – c.r ; temp.i = i – c.i ; return temp ; } void main ( ) { complex c1, c2, a, s, m, d ; cout<<"Enter CN = \n" ; c1.getcomplex ( ) ; cout<<"Enter CN = \n" ; c2.get complex ( ); a = c1.add (c2) ; s= c2.sbutract (c2) ; m = c1.multiply (c2) ; d = c1.divide (c2) ; cout<<"Addition=\n" ; a.display ( ); cout<<"subtraction=\n"; a.display ( ) ; cout<<"multiplication = \n" ; m.display ( ) ; cout<<"division=\n" ; d.display ( ); }
More Articles …
Page 1 of 21