C++ Object Oriented ”; Previous Next The prime purpose of C++ programming was to add object orientation to the C programming language, which is in itself one of the most powerful programming languages. The core of the pure object-oriented programming is to create an object, in code, that has certain properties and methods. While designing C++ modules, we try to see whole world in the form of objects. For example a car is an object which has certain properties such as color, number of doors, and the like. It also has certain methods such as accelerate, brake, and so on. There are a few principle concepts that form the foundation of object-oriented programming − Object This is the basic unit of object oriented programming. That is both data and function that operate on data are bundled as a unit called as object. Class When you define a class, you define a blueprint for an object. This doesn”t actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object. Abstraction Data abstraction refers to, providing only essential information to the outside world and hiding their background details, i.e., to represent the needed information in program without presenting the details. For example, a database system hides certain details of how data is stored and created and maintained. Similar way, C++ classes provides different methods to the outside world without giving internal detail about those methods and data. Encapsulation Encapsulation is placing the data and the functions that work on that data in the same place. While working with procedural languages, it is not always clear which functions work on which variables but object-oriented programming provides you framework to place the data and the relevant functions together in the same object. Inheritance One of the most useful aspects of object-oriented programming is code reusability. As the name suggests Inheritance is the process of forming a new class from an existing class that is from the existing class called as base class, new class is formed called as derived class. This is a very important concept of object-oriented programming since this feature helps to reduce the code size. Polymorphism The ability to use an operator or function in different ways in other words giving different meaning or functions to the operators or functions is called polymorphism. Poly refers to many. That is a single function or an operator functioning in many ways different upon the usage is called polymorphism. Overloading The concept of overloading is also a branch of polymorphism. When the exiting operator or function is made to operate on new data type, it is said to be overloaded. Print Page Previous Next Advertisements ”;
Category: cplusplus
C++ Web Programming
C++ Web Programming ”; Previous Next What is CGI? The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script. The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows − The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers. The current version is CGI/1.1 and CGI/1.2 is under progress. Web Browsing To understand the concept of CGI, let”s see what happens when we click a hyperlink to browse a particular web page or URL. Your browser contacts the HTTP web server and demand for the URL ie. filename. Web Server will parse the URL and will look for the filename. If it finds requested file then web server sends that file back to the browser otherwise sends an error message indicating that you have requested a wrong file. Web browser takes response from web server and displays either the received file or error message based on the received response. However, it is possible to set up the HTTP server in such a way that whenever a file in a certain directory is requested, that file is not sent back; instead it is executed as a program, and produced output from the program is sent back to your browser to display. The Common Gateway Interface (CGI) is a standard protocol for enabling applications (called CGI programs or CGI scripts) to interact with Web servers and with clients. These CGI programs can be a written in Python, PERL, Shell, C or C++ etc. CGI Architecture Diagram The following simple program shows a simple architecture of CGI − Web Server Configuration Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI directory and by convention it is named as /var/www/cgi-bin. By convention CGI files will have extension as .cgi, though they are C++ executable. By default, Apache Web Server is configured to run CGI programs in /var/www/cgi-bin. If you want to specify any other directory to run your CGI scripts, you can modify the following section in the httpd.conf file − <Directory “/var/www/cgi-bin”> AllowOverride None Options ExecCGI Order allow,deny Allow from all </Directory> <Directory “/var/www/cgi-bin”> Options All </Directory> Here, I assume that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell etc. First CGI Program Consider the following C++ Program content − #include <iostream> using namespace std; int main () { cout << “Content-type:text/htmlrnrn”; cout << “<html>n”; cout << “<head>n”; cout << “<title>Hello World – First CGI Program</title>n”; cout << “</head>n”; cout << “<body>n”; cout << “<h2>Hello World! This is my first CGI program</h2>n”; cout << “</body>n”; cout << “</html>n”; return 0; } Compile above code and name the executable as cplusplus.cgi. This file is being kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program make sure you have change mode of file using chmod 755 cplusplus.cgi UNIX command to make file executable. My First CGI program The above C++ program is a simple program which is writing its output on STDOUT file i.e. screen. There is one important and extra feature available which is first line printing Content-type:text/htmlrnrn. This line is sent back to the browser and specify the content type to be displayed on the browser screen. Now you must have understood the basic concept of CGI and you can write many complicated CGI programs using Python. A C++ CGI program can interact with any other external system, such as RDBMS, to exchange information. HTTP Header The line Content-type:text/htmlrnrn is a part of HTTP header, which is sent to the browser to understand the content. All the HTTP header will be in the following form − HTTP Field Name: Field Content For Example Content-type: text/htmlrnrn There are few other important HTTP headers, which you will use frequently in your CGI Programming. Sr.No Header & Description 1 Content-type: A MIME string defining the format of the file being returned. Example is Content-type:text/html. 2 Expires: Date The date the information becomes invalid. This should be used by the browser to decide when a page needs to be refreshed. A valid date string should be in the format 01 Jan 1998 12:00:00 GMT. 3 Location: URL The URL that should be returned instead of the URL requested. You can use this filed to redirect a request to any file. 4 Last-modified: Date The date of last modification of the resource. 5 Content-length: N The length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file. 6 Set-Cookie: String Set the cookie passed through the string. CGI Environment Variables All the CGI program will have access to the following environment variables. These variables play an important role while writing any CGI program. Sr.No Variable Name & Description 1 CONTENT_TYPE The data type of the content, used when the client is sending attached content to the server. For example file upload etc. 2 CONTENT_LENGTH The length of the query information that is available only for POST requests. 3 HTTP_COOKIE Returns the set cookies in the form of key & value pair. 4 HTTP_USER_AGENT The User-Agent request-header field contains information about the user agent originating the request. It is a name of the web browser. 5 PATH_INFO The path for the CGI script. 6 QUERY_STRING The URL-encoded information that is sent with GET method request. 7 REMOTE_ADDR The IP address of the remote host making the request. This can be useful for logging or for authentication purpose. 8 REMOTE_HOST The fully qualified name of the host making the request. If this information is not available then
C++ Variable Types
C++ Variable Types ”; Previous Next A variable provides us with named storage that our programs can manipulate. Each variable in C++ has a specific type, which determines the size and layout of the variable”s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C++ is case-sensitive − There are following basic types of variable in C++ as explained in last chapter − Sr.No Type & Description 1 bool Stores either value true or false. 2 char Typically a single octet (one byte). This is an integer type. 3 int The most natural size of integer for the machine. 4 float A single-precision floating point value. 5 double A double-precision floating point value. 6 void Represents the absence of type. 7 wchar_t A wide character type. C++ also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Reference, Data structures, and Classes. Following section will cover how to define, declare and use various types of variables. Variable Definition in C++ A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type, and contains a list of one or more variables of that type as follows − type variable_list; Here, type must be a valid C++ data type including char, w_char, int, float, double, bool or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here − int i, j, k; char c, ch; float f, salary; double d; The line int i, j, k; both declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j and k of type int. Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows − type variable_name = value; Some examples are − extern int d = 3, f = 5; // declaration of d and f. int d = 3, f = 5; // definition and initializing d and f. byte z = 22; // definition and initializes z. char x = ”x”; // the variable x has the value ”x”. For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is undefined. Variable Declaration in C++ A variable declaration provides assurance to the compiler that there is one variable existing with the given type and name so that compiler proceed for further compilation without needing complete detail about the variable. A variable declaration has its meaning at the time of compilation only, compiler needs actual variable definition at the time of linking of the program. A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use extern keyword to declare a variable at any place. Though you can declare a variable multiple times in your C++ program, but it can be defined only once in a file, a function or a block of code. Example Try the following example where a variable has been declared at the top, but it has been defined inside the main function − Live Demo #include <iostream> using namespace std; // Variable declaration: extern int a, b; extern int c; extern float f; int main () { // Variable definition: int a, b; int c; float f; // actual initialization a = 10; b = 20; c = a + b; cout << c << endl ; f = 70.0/3.0; cout << f << endl ; return 0; } When the above code is compiled and executed, it produces the following result − 30 23.3333 Same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. For example − // function declaration int func(); int main() { // function call int i = func(); } // function definition int func() { return 0; } Lvalues and Rvalues There are two kinds of expressions in C++ − lvalue − Expressions that refer to a memory location is called “lvalue” expression. An lvalue may appear as either the left-hand or right-hand side of an assignment. rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment. Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement − int g = 20; But the following is not a valid statement and would generate compile-time error − 10 = 20; Print Page Previous Next Advertisements ”;
C++ Variable Scope
Variable Scope in C++ ”; Previous Next A scope is a region of the program and broadly speaking there are three places, where variables can be declared − Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters. Outside of all functions which is called global variables. We will learn what is a function and it”s parameter in subsequent chapters. Here let us explain what are local and global variables. Local Variables Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. Following is the example using local variables − Live Demo #include <iostream> using namespace std; int main () { // Local variable declaration: int a, b; int c; // actual initialization a = 10; b = 20; c = a + b; cout << c; return 0; } Global Variables Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the life-time of your program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables − Live Demo #include <iostream> using namespace std; // Global variable declaration: int g; int main () { // Local variable declaration: int a, b; // actual initialization a = 10; b = 20; g = a + b; cout << g; return 0; } A program can have same name for local and global variables but value of local variable inside a function will take preference. For example − Live Demo #include <iostream> using namespace std; // Global variable declaration: int g = 20; int main () { // Local variable declaration: int g = 10; cout << g; return 0; } When the above code is compiled and executed, it produces the following result − 10 Initializing Local and Global Variables When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows − Data Type Initializer int 0 char ”” float 0 double 0 pointer NULL It is a good programming practice to initialize variables properly, otherwise sometimes program would produce unexpected result. Print Page Previous Next Advertisements ”;
C++ Dynamic Memory
C++ Dynamic Memory ”; Previous Next A good understanding of how dynamic memory really works in C++ is essential to becoming a good C++ programmer. Memory in your C++ program is divided into two parts − The stack − All variables declared inside the function will take up memory from the stack. The heap − This is unused memory of the program and can be used to allocate the memory dynamically when program runs. 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 that was previously allocated by new operator. new and delete Operators There is following generic syntax to use new operator to allocate memory dynamically for any data-type. new data-type; Here, data-type could be any built-in data type including an array or any user defined data types include class or structure. Let us start with built-in data types. For example we can define a pointer to type double and then request that the memory be allocated at execution time. We can do this using the new operator with the following statements − double* pvalue = NULL; // Pointer initialized with null pvalue = new double; // Request memory for the variable The memory may not have been allocated successfully, if the free store had been used up. So it is good practice to check if new operator is returning NULL pointer and take appropriate action as below − double* pvalue = NULL; if( !(pvalue = new double )) { cout << “Error: out of memory.” <<endl; exit(1); } The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc() function. The main advantage of new over malloc() is that new doesn”t just allocate memory, it constructs objects which is prime purpose of C++. At any point, when you feel a variable that has been dynamically allocated is not anymore required, you can free up the memory that it occupies in the free store with the ‘delete’ operator as follows − delete pvalue; // Release memory pointed to by pvalue Let us put above concepts and form the following example to show how ‘new’ and ‘delete’ work − Live Demo #include <iostream> using namespace std; int main () { double* pvalue = NULL; // Pointer initialized with null pvalue = new double; // Request memory for the variable *pvalue = 29494.99; // Store value at allocated address cout << “Value of pvalue : ” << *pvalue << endl; delete pvalue; // free up the memory. return 0; } If we compile and run above code, this would produce the following result − Value of pvalue : 29495 Dynamic Memory Allocation for Arrays Consider you want to allocate memory for an array of characters, i.e., string of 20 characters. Using the same syntax what we have used above we can allocate memory dynamically as shown below. char* pvalue = NULL; // Pointer initialized with null pvalue = new char[20]; // Request memory for the variable To remove the array that we have just created the statement would look like this − delete [] pvalue; // Delete array pointed to by pvalue Following the similar generic syntax of new operator, you can allocate for a multi-dimensional array as follows − double** pvalue = NULL; // Pointer initialized with null pvalue = new double [3][4]; // Allocate memory for a 3×4 array However, the syntax to release the memory for multi-dimensional array will still remain same as above − delete [] pvalue; // Delete array pointed to by pvalue Dynamic Memory Allocation for Objects Objects are no different from simple data types. For example, consider the following code where we are going to use an array of objects to clarify the concept − Live Demo #include <iostream> using namespace std; class Box { public: Box() { cout << “Constructor called!” <<endl; } ~Box() { cout << “Destructor called!” <<endl; } }; int main() { Box* myBoxArray = new Box[4]; delete [] myBoxArray; // Delete array return 0; } If you were to allocate an array of four Box objects, the Simple constructor would be called four times and similarly while deleting these objects, destructor will also be called same number of times. If we compile and run above code, this would produce the following result − Constructor called! Constructor called! Constructor called! Constructor called! Destructor called! Destructor called! Destructor called! Destructor called! Print Page Previous Next Advertisements ”;
C++ STL Tutorial
C++ STL Tutorial ”; Previous Next Hope you have already understood the concept of C++ Template which we have discussed earlier. The C++ STL (Standard Template Library) is a powerful set of C++ template classes to provide general-purpose classes and functions with templates that implement many popular and commonly used algorithms and data structures like vectors, lists, queues, and stacks. At the core of the C++ Standard Template Library are following three well-structured components − Sr.No Component & Description 1 Containers Containers are used to manage collections of objects of a certain kind. There are several different types of containers like deque, list, vector, map etc. 2 Algorithms Algorithms act on containers. They provide the means by which you will perform initialization, sorting, searching, and transforming of the contents of containers. 3 Iterators Iterators are used to step through the elements of collections of objects. These collections may be containers or subsets of containers. We will discuss about all the three C++ STL components in next chapter while discussing C++ Standard Library. For now, keep in mind that all the three components have a rich set of pre-defined functions which help us in doing complicated tasks in very easy fashion. Let us take the following program that demonstrates the vector container (a C++ Standard Template) which is similar to an array with an exception that it automatically handles its own storage requirements in case it grows − Live Demo #include <iostream> #include <vector> using namespace std; int main() { // create a vector to store int vector<int> vec; int i; // display the original size of vec cout << “vector size = ” << vec.size() << endl; // push 5 values into the vector for(i = 0; i < 5; i++) { vec.push_back(i); } // display extended size of vec cout << “extended vector size = ” << vec.size() << endl; // access 5 values from the vector for(i = 0; i < 5; i++) { cout << “value of vec [” << i << “] = ” << vec[i] << endl; } // use iterator to access the values vector<int>::iterator v = vec.begin(); while( v != vec.end()) { cout << “value of v = ” << *v << endl; v++; } return 0; } When the above code is compiled and executed, it produces the following result − vector size = 0 extended vector size = 5 value of vec [0] = 0 value of vec [1] = 1 value of vec [2] = 2 value of vec [3] = 3 value of vec [4] = 4 value of v = 0 value of v = 1 value of v = 2 value of v = 3 value of v = 4 Here are following points to be noted related to various functions we used in the above example − The push_back( ) member function inserts value at the end of the vector, expanding its size as needed. The size( ) function displays the size of the vector. The function begin( ) returns an iterator to the start of the vector. The function end( ) returns an iterator to the end of the vector. Print Page Previous Next Advertisements ”;
C++ Strings
C++ Strings ”; Previous Next C++ provides following two types of string representations − The C-style character string. The string class type introduced with Standard C++. The C-Style Character String The C-style character string originated within the C language and continues to be supported within C++. This string is actually a one-dimensional array of characters which is terminated by a null character ””. Thus a null-terminated string contains the characters that comprise the string followed by a null. The following declaration and initialization create a string consisting of the word “Hello”. To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word “Hello.” char greeting[6] = {”H”, ”e”, ”l”, ”l”, ”o”, ””}; If you follow the rule of array initialization, then you can write the above statement as follows − char greeting[] = “Hello”; Following is the memory presentation of above defined string in C/C++ − Actually, you do not place the null character at the end of a string constant. The C++ compiler automatically places the ”” at the end of the string when it initializes the array. Let us try to print above-mentioned string − Live Demo #include <iostream> using namespace std; int main () { char greeting[6] = {”H”, ”e”, ”l”, ”l”, ”o”, ””}; cout << “Greeting message: “; cout << greeting << endl; return 0; } When the above code is compiled and executed, it produces the following result − Greeting message: Hello C++ supports a wide range of functions that manipulate null-terminated strings − Sr.No Function & Purpose 1 strcpy(s1, s2); Copies string s2 into string s1. 2 strcat(s1, s2); Concatenates string s2 onto the end of string s1. 3 strlen(s1); Returns the length of string s1. 4 strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. 5 strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1. 6 strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1. Following example makes use of few of the above-mentioned functions − Live Demo #include <iostream> #include <cstring> using namespace std; int main () { char str1[10] = “Hello”; char str2[10] = “World”; char str3[10]; int len ; // copy str1 into str3 strcpy( str3, str1); cout << “strcpy( str3, str1) : ” << str3 << endl; // concatenates str1 and str2 strcat( str1, str2); cout << “strcat( str1, str2): ” << str1 << endl; // total lenghth of str1 after concatenation len = strlen(str1); cout << “strlen(str1) : ” << len << endl; return 0; } When the above code is compiled and executed, it produces result something as follows − strcpy( str3, str1) : Hello strcat( str1, str2): HelloWorld strlen(str1) : 10 The String Class in C++ The standard C++ library provides a string class type that supports all the operations mentioned above, additionally much more functionality. Let us check the following example − Live Demo #include <iostream> #include <string> using namespace std; int main () { string str1 = “Hello”; string str2 = “World”; string str3; int len ; // copy str1 into str3 str3 = str1; cout << “str3 : ” << str3 << endl; // concatenates str1 and str2 str3 = str1 + str2; cout << “str1 + str2 : ” << str3 << endl; // total length of str3 after concatenation len = str3.size(); cout << “str3.size() : ” << len << endl; return 0; } When the above code is compiled and executed, it produces result something as follows − str3 : Hello str1 + str2 : HelloWorld str3.size() : 10 Print Page Previous Next Advertisements ”;
C++ References
C++ References ”; Previous Next A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable. References vs Pointers References are often confused with pointers but three major differences between references and pointers are − You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage. Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time. A reference must be initialized when it is created. Pointers can be initialized at any time. Creating References in C++ Think of a variable name as a label attached to the variable”s location in memory. You can then think of a reference as a second label attached to that memory location. Therefore, you can access the contents of the variable through either the original variable name or the reference. For example, suppose we have the following example − int i = 17; We can declare reference variables for i as follows. int& r = i; Read the & in these declarations as reference. Thus, read the first declaration as “r is an integer reference initialized to i” and read the second declaration as “s is a double reference initialized to d.”. Following example makes use of references on int and double − Live Demo #include <iostream> using namespace std; int main () { // declare simple variables int i; double d; // declare reference variables int& r = i; double& s = d; i = 5; cout << “Value of i : ” << i << endl; cout << “Value of i reference : ” << r << endl; d = 11.7; cout << “Value of d : ” << d << endl; cout << “Value of d reference : ” << s << endl; return 0; } When the above code is compiled together and executed, it produces the following result − Value of i : 5 Value of i reference : 5 Value of d : 11.7 Value of d reference : 11.7 References are usually used for function argument lists and function return values. So following are two important subjects related to C++ references which should be clear to a C++ programmer − Sr.No Concept & Description 1 References as Parameters C++ supports passing references as function parameter more safely than parameters. 2 Reference as Return Value You can return reference from a C++ function like any other data type. Print Page Previous Next Advertisements ”;
C++ Abstraction
Data Abstraction in C++ ”; Previous Next Data abstraction refers to providing only essential information to the outside world and hiding their background details, i.e., to represent the needed information in program without presenting the details. Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation. Let”s take one real life example of a TV, which you can turn on and off, change the channel, adjust the volume, and add external components such as speakers, VCRs, and DVD players, BUT you do not know its internal details, that is, you do not know how it receives signals over the air or through a cable, how it translates them, and finally displays them on the screen. Thus, we can say a television clearly separates its internal implementation from its external interface and you can play with its interfaces like the power button, channel changer, and volume control without having any knowledge of its internals. In C++, classes provides great level of data abstraction. They provide sufficient public methods to the outside world to play with the functionality of the object and to manipulate object data, i.e., state without actually knowing how class has been implemented internally. For example, your program can make a call to the sort() function without knowing what algorithm the function actually uses to sort the given values. In fact, the underlying implementation of the sorting functionality could change between releases of the library, and as long as the interface stays the same, your function call will still work. In C++, we use classes to define our own abstract data types (ADT). You can use the cout object of class ostream to stream data to standard output like this − Live Demo #include <iostream> using namespace std; int main() { cout << “Hello C++” <<endl; return 0; } Here, you don”t need to understand how cout displays the text on the user”s screen. You need to only know the public interface and the underlying implementation of ‘cout’ is free to change. Access Labels Enforce Abstraction In C++, we use access labels to define the abstract interface to the class. A class may contain zero or more access labels − Members defined with a public label are accessible to all parts of the program. The data-abstraction view of a type is defined by its public members. Members defined with a private label are not accessible to code that uses the class. The private sections hide the implementation from code that uses the type. There are no restrictions on how often an access label may appear. Each access label specifies the access level of the succeeding member definitions. The specified access level remains in effect until the next access label is encountered or the closing right brace of the class body is seen. Benefits of Data Abstraction Data abstraction provides two important advantages − Class internals are protected from inadvertent user-level errors, which might corrupt the state of the object. The class implementation may evolve over time in response to changing requirements or bug reports without requiring change in user-level code. By defining data members only in the private section of the class, the class author is free to make changes in the data. If the implementation changes, only the class code needs to be examined to see what affect the change may have. If data is public, then any function that directly access the data members of the old representation might be broken. Data Abstraction Example Any C++ program where you implement a class with public and private members is an example of data abstraction. Consider the following example − Live Demo #include <iostream> using namespace std; class Adder { public: // constructor Adder(int i = 0) { total = i; } // interface to outside world void addNum(int number) { total += number; } // interface to outside world int getTotal() { return total; }; private: // hidden data from outside world int total; }; int main() { Adder a; a.addNum(10); a.addNum(20); a.addNum(30); cout << “Total ” << a.getTotal() <<endl; return 0; } When the above code is compiled and executed, it produces the following result − Total 60 Above class adds numbers together, and returns the sum. The public members – addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that the user doesn”t need to know about, but is needed for the class to operate properly. Designing Strategy Abstraction separates code into interface and implementation. So while designing your component, you must keep interface independent of the implementation so that if you change underlying implementation then interface would remain intact. In this case whatever programs are using these interfaces, they would not be impacted and would just need a recompilation with the latest implementation. Print Page Previous Next Advertisements ”;
C++ Encapsulation
Data Encapsulation in C++ ”; Previous Next All C++ programs are composed of the following two fundamental elements − Program statements (code) − This is the part of a program that performs actions and they are called functions. Program data − The data is the information of the program which gets affected by the program functions. Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding. Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user. C++ supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. We already have studied that a class can contain private, protected and public members. By default, all items defined in a class are private. For example − class Box { public: double getVolume(void) { return length * breadth * height; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; The variables length, breadth, and height are private. This means that they can be accessed only by other members of the Box class, and not by any other part of your program. This is one way encapsulation is achieved. To make parts of a class public (i.e., accessible to other parts of your program), you must declare them after the public keyword. All variables or functions defined after the public specifier are accessible by all other functions in your program. Making one class a friend of another exposes the implementation details and reduces encapsulation. The ideal is to keep as many of the details of each class hidden from all other classes as possible. Data Encapsulation Example Any C++ program where you implement a class with public and private members is an example of data encapsulation and data abstraction. Consider the following example − Live Demo #include <iostream> using namespace std; class Adder { public: // constructor Adder(int i = 0) { total = i; } // interface to outside world void addNum(int number) { total += number; } // interface to outside world int getTotal() { return total; }; private: // hidden data from outside world int total; }; int main() { Adder a; a.addNum(10); a.addNum(20); a.addNum(30); cout << “Total ” << a.getTotal() <<endl; return 0; } When the above code is compiled and executed, it produces the following result − Total 60 Above class adds numbers together, and returns the sum. The public members addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that is hidden from the outside world, but is needed for the class to operate properly. Designing Strategy Most of us have learnt to make class members private by default unless we really need to expose them. That”s just good encapsulation. This is applied most frequently to data members, but it applies equally to all members, including virtual functions. Print Page Previous Next Advertisements ”;