Pages

Monday, February 21, 2011

Another Example Of Class Using Arrays

#include

#include
class video
{
char title[20];
float length;
char type;
public:
void getvideo()
{
cout<<"Title ";
cin>>title;
cout<<"Length (In Hours) ";
cin>>length;
cout<<"Type (M For Music, D for Dance ";
cin>>type;
}
void printvideo()
{
cout<<"Title "<
cout<<"Length "<
cout<<"Type (M-Music,D-Dance "<
}
int gettype()
{
return type;
}
};


void main()
{
clrscr();
int mcnt=0,dcnt=0;
video v[3];
for(int i=0;i<3;i++)
{
cout<<"\nEnter Details of video "<
v[i].getvideo();
}
for(i=0;i<3;i++)
{
v[i].printvideo();
if(v[i].gettype()=='M' || v[i].gettype()=='m')
mcnt++;
else
dcnt++;
cout<<"\n===========================";
}

cout<<"\nNo. of Music Videos "<
cout<<"\nNo. of Dance Videos "<
}


Description

The above code has a class named "video", which contains 3 member variables - title,length and type. The methods "getvideo" and "printvideo" have been used to enter and display their values respectively. The third method named "gettype()" is used to return the "type" of the video which is either "M" or "D" for "Music" and "Dance". Inside "main()", instead of declaring three different objects of the class we have created a single object named "v" but in the form of an array. In terms of memory occupied, this is equivalent to declaring three individual objects of the class but declaring an array object gives us the freedom to use a loop which can not be used with individual objects.
Inside the first loop we have called the "getvideo()" which asks the user to enter the details of the video. After accepting the value for 3 videos, the program runs the second loop which not only prints the data but also checks for their type by calling the "gettype()". Two counter variables named "mcnt" and "dcnt" are incremented each time a "music" or "dance" video is found and the result is printed on the screen.

Monday, February 14, 2011

Declaring a class


After learning the OOPS concepts, let's now learn how to declare a class. Declaring a class is somewhat similar to declaring a structure in C. The difference is that in a structure all the members are "public" by default whereas in a class all the members are by default "private". Another difference is that a structure can only contain member variables but a class can not only contain variables but also functions or methods.

Syntax

class classname
{

members...
};


Example
class vehicle
{
int vehno;
char vehtype[12];
void getveh()
{}
void showveh()
{}
};

Description :

"vehicle" is the name of the class, which can be any logical name within the rules of declaration.Inside the class there are four members - int vehno, char vehtype,void getveh() and void showveh(). A class can have as many members as required. Generally a class should have at least two functions - one for initialising the member variables and another for printing the output. Declaration of other functions depends on the need of the program. The class body must end with a ";" which is called the "class terminator".

Example 1 -- The student class
class student
{
private:
int admno;
char sname[15];
char grade;
public:
void get_data()
{
cout<<"Adm. No. ";
cin>>admno;
cout<<"Student Name ";
cin>>sname;
cout<<"Grade ";
cin>>grade;
}


void show_data()
{
cout<<"Adm. No. ";
cout<<"Name of the student ";
cout<<"Grade ";
}


};


Description
The student class has 3 member variables -- int admno,char sname[15] and char grade. The class also has 2 methods "get_data()" and "show_data()". The member variables have the "private" access specifier while the methods have a "public" visibility. Why ? The reason for this is a concept called "data hiding". A general user of this program will either need to intialise the data variables or print their values. For both the purposes we have already defined the functions "get_data()" and "show_data()". If the user wants to initialise the variable he can call the "get_data()" method and to print the same the second method can be called. Now, when both the tasks are being performed by the methods why should we allow the variable to come out of the class. This is why we have specified them as "private". The variables can be accessed from within the class but to access them from outside - either of the two methods can be used.

Why not public ?

It can be questioned here that what is the harm in specifing the variables as public also. The answer is "prevention of accidental modification". If the variables are also specified as "public" there are chances that their values are accidently modified. For example before making a call to the method "show_data()", if the user writes a statement like "admno=0", the second method will print 0 and not the value entered by the user. By creating public methods we have created a proper channel through which the variables can be initialised and printed. The "private" specifier helps us in specifying the accessiblility of the variables making them inaccessible from outside.

Note : "endl" denotes "end line" and is used to print different outputs on different lines as "\n" in C.

Using the "student" class

After declaring a class, we now need to call or access its members. To access a class member we must first create an object. As mentioned earlier an object is an instance of class. Once we declare an object we can call the members of the class using "objectname.membername" syntax. Take a look at the following example which is in continuation with the last example.

Example 1 -- Using the student class

class student
{
private:
int admno;
char sname[15];
char grade;
public:
void get_data()
{
cout<<"Adm. No. ";
cin>>admno;
cout<<"Student Name ";
cin>>sname;
cout<<"Grade ";
cin>>grade;
}


void show_data()
{
cout<<"Adm. No. ";
cout<<"Name of the student ";cout<<"Grade ";
}


};

void main()
{
student objstud;
objstud.get_data()
objstud.show_data();
}


Description
In the main(), we have created an object name "objstud". Remeber, that a class is an user defined dataytype therefore to use it a variable of the class should be defined. After declaring the variable (object, to be precise), we can access the class members using the syntax like objstud.get_data(). The above program will first ask the user to enter the student data and then will print the same.

Sunday, February 13, 2011

Access specifiers

Access specifiers are keywords used to identify access rights for the data and member functions of the class. These specifiers are used to denote the "power" of members(variables or methods) when they are accessed
from outside the class. Inside the class all members are "public", which means that all the methods have an access to them. If none of the access specifier is given the default specifier is "private".


A member of a class can be accessed from

a) Within a class

b) In the sub class

c) From a class object.


There are three main types of access specifiers in C++ programming language:


  1. Private : A private member within a class denotes that only members of the same class have accessibility. The private member is inaccessible from outside the class. We can access the private members of the class from inside the xlass but not from an object or a sub class.
  2. Public  : Public members are accessible from outside the class. Such members are available to all the child classes and objects of the class. A sub class can use the "public" members of the base class as its own whereas a class object can access them using the "object.member" syntax.
  3. Protected : A protected access specifier is a combination of both "private" and "public" specifier.A protected member is accessible from a child class just like a public member but when it comes to accessing from an object a protected member acts like a private member and refuses to be accessed. The protected specifier comes into picture only when there is inheritance. If there is no need to inherit a class, the public and private specifiers are sufficient to describle the accessibility.

Look at the following table for a more clear understanding.


Access Specifier
SpecifierOwn ClassSub ClassObject Of The Class
PrivateAccessibleNot AccessibleNot Accessible
PublicAccessibleAccessibleAccessible
ProtectedAccessibleAccessibleNot Accessible

OOPS Features - Inheritance

Inheritance like other OOPS features is also a real life concept. In real world children acquire or inherit the properties and behaviour of their parents. These properties can be biological like color of hair, color of eyes, facial similarities or monetary like land, money, house etc. Similarly the behavioural characteristics of a child are also similar to his or her parents. When a child inherits these properties from parents he doesn't need to earn them again. He can use the inherited property (house,money) of his parent as if he owns them. What the child earns on his own can be said to be as a kind of "bonus" for him.

In OOPS, the concept of inheritance is the same as it happens in real. A class can "inherit" properties and behaviours from another class, which be now be called as its parent. By inheriting the properties of an existing class, the other class is promoting "reusability" which has its own advantages.

To define "Inheritance is the process of declaring a class using the properties and behaviours of an existing class". The main benefit in inheritance is that the members of the existing class can be used by the child class without having to re declare them.


Definitions


1. Base Class : The class that is being inherited by other classes is called a "base" class. It can also be called as "parent" or "super" class. A base class can decide which properties or behaviour it wants the child to access and which ones to hide. This is done using the access specifiers like "private", "public" etc.


2. Sub Class : The class that is inheriting the properties is called a "sub" or "child" or "derived" class. A class can inherit the properties from a single or multiple parent classes. A child class can also act as a parent for yet another class.


Advantages of Inheritance

1. Saves memory : Any thing which is needed more than once can be declared in the base class. Any class which needs an already defined member can simply inherit the base class resulting in saving of memory.

2. Saves time : Reusing the same code saves time in terms of retyping the code and debugging. Debugging or removing the errors of the program is done only once since the same code is being used by all the child classes.

3. Uniformity : Since the child classes are not declaring its own members there is no possibility of declaring same variable with different type and size in different classes. For example a variable named "address" can be defined in the first class with a size of "20" while the same variable can be defined with a different size in the second class. Inheritance will make sure that all the classes are using the same variable leading to standardisation of the program.

Wednesday, February 9, 2011

OOPS Features - Polymorphism

The word "Polymorphism" is made up of two word "Poly" which means many and "morphos" which means "forms". Therefore the word polymorphism means "many forms". The concept of polymorphism is present not only in OOPS but also in real life. For example, in the english language there are many words which have the same spelling like the word "patient" or "bank". The word "patient", for instance can mean a sick person in medical context and at the same time the word can mean as in "to be patient". What exactly is the meaning of the word can only be understood only when the context is known. Such words can be called called "polymorphed" in OOPS.
 
In OOPS, Polymorphism is the ability to use an operator or function in different ways. Polymorphism gives different meanings or functions to the operators or functions. Poly, referring to many, signifies the many uses of these operators and functions. A single function usage or an operator functioning in many ways can be called polymorphism. Polymorphism refers to codes, operations or objects that behave differently in different contexts.
To understand polymorphism better, take a look at the "*" operator. The symbol "*" has different meanings in computing. While performing calculation the "*" signs stands for multiplication and is an example arithmetic operator. While working with pointers the same symbol is used for pointer declaration. Therefore it can be said that "*" symbol is polymorphed since it has different meanings in different conditions.
  
Polymorphism is a powerful feature of the object oriented programming language C++. A single operator + behaves differently in different contexts such as integer, float or strings referring the concept of polymorphism. The above concept leads to operator overloading. The concept of overloading is also a branch of polymorphism. When the exiting operator or function operates on new data type it is overloaded. This feature of polymorphism leads to the concept of virtual methods.
Polymorphism refers to the ability to call different functions by using only one type of function call. Suppose a programmer wants to code vehicles of different shapes such as circles, squares, rectangles, etc. One way to define each of these classes is to have a member function for each that makes vehicles of each shape. Another convenient approach the programmer can take is to define a base class named Shape and then create an instance of that class. The programmer can have array that hold pointers to all different objects of the vehicle followed by a simple loop structure to make the vehicle, as per the shape desired, by inserting pointers into the defined array. This approach leads to different functions executed by the same function call. Polymorphism is used to give different meanings to the same concept. This is the basis for Virtual function implementation.
 
In polymorphism, a single function or an operator functioning in many ways depends upon the usage to function properly. In order for this to occur, the following conditions must apply:
 
All different classes must be derived from a single base class. In the above example, the shapes of vehicles (circle, triangle, rectangle) are from the single base class called Shape. The member function must be declared virtual in the base class. In the above example, the member function for making the vehicle should be made as virtual to the base class.
 
Features and Advantages of the concept of Polymorphism:
 
  • Applications are Easily Extendable:  Once an application is written using the concept of polymorphism, it can easily be extended, providing new objects that conform to the original interface. It is unnecessary to recompile original programs by adding new types. Only re-linking is necessary to exhibit the new changes along with the old application. This is the greatest achievement of C++ object-oriented programming. In programming language, there has always been a need for adding and customizing. By utilizing the concept of polymorphism, time and work effort is reduced in addition to making future maintenance easier.
      
  • Helps in reusability of code. Provides easier maintenance of applications.  
  • Helps in achieving robustness in applications.
 
Types of Polymorphism:
 
C++ provides three different types of polymorphism.  
  • Virtual functions
  • Function name overloading
  • Operator overloading
 
In addition to the above three types of polymorphism, there exist other kinds of polymorphism:  
  • Run-time: The run-time polymorphism is implemented with inheritance and virtual functions.  
  • Compile-time: The compile-time polymorphism is implemented with templates.  
  • Ad-hoc polymorphism: If the range of actual types that can be used is finite and the combinations must be individually specified prior to use, this is called ad-hoc polymorphism.
  • Parametric polymorphism:  If all code is written without mention of any specific type and thus can be used transparently with any number of new types it is called parametric polymorphism.

Tuesday, February 8, 2011

OOPS Features - Encapsulation

Introduction

Encapsulation is the process of combining data and functions into a single unit called class. Using the method of encapsulation, the programmer cannot directly access the data. Data is only accessible through the functions present inside the class. Data encapsulation led to the important concept of data hiding. Data hiding is the implementation details of a class that are hidden from the user. The concept of restricted access led programmers to write specialized functions or methods for performing the operations on hidden members of the class. Attention must be paid to ensure that the class is designed properly.
Neither too much access nor too much control must be placed on the operations in order to make the class user friendly. Hiding the implementation details and providing restrictive access leads to the concept of abstract data type. Encapsulation leads to the concept of data hiding, but the concept of encapsulation must not be restricted to information hiding. Encapsulation clearly represents the ability to bundle related data and functionality within a single, autonomous entity called a class.


For instance:
class sample
{
int var1;
char var2[20];
public:
void getdata(int v1,char v2[])
{
var1=v1;
strcpy(var2,v2);
}
void showdata()
{
cout<
cout<
}
};

In the above example, the data members var1 and var2 and member functions getdata(),showdata() packaged inside a single autonomous entity called class "sample". This is the concept of Encapsulation. This special feature is available in object-oriented languages like C++, Java etc. There are advantages of using this encapsulated approach in C++. One advantage is that it reduces human errors. The data and functions bundled inside the class take total control of maintenance and thus human errors are reduced. It is clear from the above example that the encapsulated objects act as a black box for other parts of the program through interaction. Although encapsulated objects provide functionality, the calling objects will not know the implementation details. This enhances the security of the application.

The key strength behind Data Encapsulation in C++ is that the keywords or the access specifiers can be placed in the class declaration as public, protected or private. A class placed after the keyword public is accessible to all the users of the class. The elements placed after the keyword private are accessible only to the methods of the class. In between the public and the private access specifiers, there exists the protected access specifier. Elements placed after the keyword protected are accessible only to the methods of the class or classes derived from that class.

The concept of encapsulation shows that a non-member function cannot access an object's private or protected data. This adds security, but in some cases the programmer might require an unrelated function to operate on an object of two different classes. The programmer is then able to utilize the concept of friend functions. Encapsulation alone is a powerful feature that leads to information hiding, abstract data type and friend functions.

Features and Advantages of the concept of Encapsulation:

  •  Makes Maintenance of Application Easier: Complex and critical applications are difficult to maintain. The cost associated with maintaining the application is higher than that of developing the application properly. To resolve this maintenance difficulty, the object-oriented programming language C++ created the concept of encapsulation which bundles data and related functions together as a unit called class. Thus, making maintenance much easier on the class level.
  • Improves the Understandability of the Application : Since the code is divided into small methods or functions, it makes the whole program easier to understand and debug.
  • Enhanced Security: There are numerous reasons for the enhancement of security using the concept of Encapsulation in C++. The access specifier acts as the key strength behind the concept of security and provides access to members of class as needed by users. This prevents unauthorized access. If an application needs to be extended or customized in later stages of development, the task of adding new functions becomes easier without breaking existing code or applications, there by giving an additional security to existing application.

OOPS Features - Abstraction

Abstraction is the process of hiding irrelevant data from the user and showing only the important part.The concept of abstraction relates to the idea of hiding data that are not needed for presentation. The main idea behind data abstraction is to give a clear separation between properties of data type and the associated implementation details. This separation is achieved in order that the properties of the abstract data type are visible to the user interface and the implementation details are hidden. Thus, abstraction forms the basic platform for the creation of user-defined data types called objects. Data abstraction is the process of refining data to its essential form. An Abstract Data Type is defined as a data type that is defined in terms of the operations that it supports and not in terms of its structure or implementation.

In object-oriented programming language like C++, it is possible to create and provide an interface that accesses only certain elements of data types. We can decide which the level of access for a user and can hide some data . This concept is called data hiding which is similar in concept to data abstraction. To hide or show the data the access specifiers like - private, public and protected are used in C++.

Abstraction is one of the most powerful and vital features provided by object-oriented C++ programming language. Modularity is very important in any programming language, it provides flexibility to users for using the programming language. This aspect is well achieved with high performance by the concept of abstraction in C++. In object-oriented programming language the programmer can abstract both data and code when needed.


How Types of Abstraction Differs:

There are two broad types of abstraction; functional abstraction and data abstraction. The main difference between functional abstraction and data abstraction is that functional abstraction refers to a function that can be used without taking into account how the function is implemented. Data abstraction refers to the data that can be used without taking into account how the data are stored. There is also a difference in the way the access takes place in functional abstraction and data abstraction. In functional abstraction, access to the function is provided through a specific interface defined to invoke the function. In contrast, in data abstraction, access to the data is provided through a specific set of operations defined to examine and manipulate the data. For instance, when a programmer is using C++ standard data types, this means that users are using the concept of data abstraction. When using data types, the users are not concerned with how the data is stored but they are concerned with what operations are provided and what properties are supported.

Reasons for the need of Abstraction
  • Flexibility in approach:  By hiding data or abstracting details that are not needed for presentation, the programmer achieves greater flexibility in approach.
  • Enhanced Security: Abstraction gives access to data or details that are needed by users and hide the implementation details, giving enhanced security to application.
  • Easier Replacement: With the concept of abstraction in object-oriented programming language, it is possible to replace code without recompilation. This makes the process easier and saves time for users.
  • Modular Approach: In object-oriented programming language C++, the abstraction concept helps users to divide the project application into modules and test each of them separately. Then all modules are integrated and ultimately tested together. This approach makes the application development easier.
There are various ways of achieving abstraction in object-oriented programming language C++. One approach is to take modular based code that is broken apart into smaller segments, known as functions. This functional or modular approach helps the code to be reused again and again when needed. For example, a programmer might write a function for computing an average and another programmer might write a function for computing salary. These functions can be reused when needed, by anyone. The modular based approach helps to centralize all data of a similar type, under the control of a type module. Defining module types allow the module to be an abstract data type. In many other programming languages, there is a small drawback associated with the approach to accessing module type.