Saturday, 14 April 2012

Need for C++/Features of C++

Object Oriented:

C++ is object oriented, unlike C which focuses mainly on Function/procedure based approach to solve problems.The object oriented approach allows us to model the real world objects/scenarios by creating objects/instances which combine both the properties and behavior of real life objects.


Consider an electric bulb:
it has two states on,off, the behavior is it can be turned on to glow, turned off.

class bulb
int state=0;
//state 0 indicates bulb is off, 1 indicates it is on
void turnon()
  //if it is off turn it on
void turnoff()
  //if it is on turn it off
};//end of class bulb


encapsulation literally means to hold something, through the concept of classes, C++ provides for encapsulation of the Data members and functions , that is  the data members and the functions are bound together by the class.

In the Bulb class, only the functions turnon() and turnoff() can change the state of the bulb, it is not possible to change the state directly.

void main()
//declare an object
bulb b=new bulb();
//refer article on declaration of objects,constructors for more details
//change the state of bulb to on
state=1;//invalidgives an error state can be changed only through the member functions.


abstraction is hiding the data, abstraction hides the finer implementation details and allows the user to focus on the functionality required.
an end user wants the bulb to be turned on, he can just call the turnon() function, the data related to state of bulb which causes it to turn on is hidden from the user.

refer the source code given for Encapsulation, same holds good for abstraction.


Abstraction and encapsulation go hand in hand, they are two closely related terms, often they are confused.


polymorph means a single entity existing in many forms, C++ supports for the entities to exist in many forms ie each form has a different behavior.
Imagine an electric bulb capable of giving different colours of light depending on input voltage.

function overloading and overriding are two standard examples of polymorphism in C++.

Dynamic Memory Management:

C++ supports for dynamic memory allocation and deallocation, this can be done by using new and delete keywords.The requires blocks of memory are assigned during run time, a combination of dynamic memory allocation and deallocation after its not needed can make the program more efficient in terms of memory usage.


Inheritance is a concept which enables a child class to inherit the features from a parent class ie it provides for code reusability, the child class inherits the functions and data members from the parent class.
consider the shape class as parent of all geometric shapes.

here circle,square,triangle, inherit the draw and erase functions from the parent class shape.

No comments:

Post a Comment