C++ Short Note Object Oriented Programming Paradigm

:
Oops is a better way of solving problems in computers compared to the procedural language programming such as in C. oops is designed around the data being operated upon as opposed to the operations, these operations are designed to fit data. A type of programming in which programmers define not only the data type of a data structure, but also the types of operations that can be applied to the data structure. In this way, the data structure becomes an object that includes both data and functions. In addition, programmers can create relationships between one object and another. For example, objects can inherit characteristics from other objects. One of the principal advantages of object-oriented programming techniques over procedural programming techniques is that they enable programmers to create modules that do not need to be changed when a new type of object is added. A programmer can simply create a new object that inherits many of its features from existing objects. This makes object-oriented programs easier to modify. To perform object-oriented programming, one needs an object-oriented programming language such as Java C++ etc. The C++ programming language provides a model of memory and computation that closely matches that of most computers. In addition, it provides powerful and flexible mechanisms for abstraction; that is, language constructs that allow the programmer to introduce and use new types of objects that match the concepts of an application. Thus, C++ supports styles of programming that rely on fairly direct manipulation of hardware resources to deliver a high degree of efficiency plus higher-level styles of programming that rely on user-defined types to provide a model of data and computation that is closer to a human s view of the task being performed by a computer. These higher-level styles of programming are often called data abstraction, object-oriented programming, and generic programming.

[Type text]

Page 1

C++ Short Note
Important Features of OOPs are the following:
y y y y y y y y y y

Encapsulation Data abstraction Inheritance Polymorphism Message passing Extensibility Persistence Delegation Genericity Multiple Inheritance

OOP:
OOP uses objects as its fundamental building blocks. Each object is an instance of some class. Classes allow the mechanism of data abstraction for creating new data types. Inheritance allows building of new classes from existing classes. Hence if any of these elements are missing in a program we cannot consider that program as objected oriented program. Object oriented programming is a programming methodology that associates data structures with a set of operators which act upon it. In OOP s terminology an instance of such an entity is known as an object. It gives importance to relationships between objects rather than implementation details. Hiding the implementation details within an object results in the user being more concerned with an objects relationship to the rest of the system, than the implementation of the object s behavior.

Objects:
Objects are the basic run-time entities in an object-oriented system. Every object is associated with data and functions which define meaningful operations on that object.

An Object is a collection of data members and associated member functions also known as methods.

[Type text]

Page 2

C++ Short Note
Encapsulation
It is a mechanism that associates the code and the data it manipulates into a single unit to and keeps them safe from external interference and misuse. In C++ this is supported by construct called class. An instance of an object is known as object which represents a real world entity.

What is Data Abstraction
A data abstraction is a simplified view of an object that includes only features one is interested in while hides away the unnecessary details. In programming languages, a data abstraction becomes an abstract data type or a userdefined type. In OOP, it is implemented as a class.

What is Inheritance
Inheritance is a means of specifying hierarchical relationships between types C++ classes can inherit both data and function members from other (parent) classes. Terminology: "the child (or derived) class inherits (or is derived from) the parent (or base) class"

What is Multiple Inheritance
The mechanism by which a class is derived from more than one base class is known as multiple inheritance. Instances of classes with multiple inheritance have instance variables for each of the inherited base classes. C++ supports multiple inheritance.

What is Polymorphism
Polymorphism is in short the ability to call different functions by just using one type of function call. It is a lot useful since it can group classes and their functions together. Polymorphism means that the same thing can exist in two forms. This is an important characteristic of true object oriented design - which means that one could develop good OO design with data abstraction and inheritance, but the real power of object oriented design seems to surface when polymorphism is used. In C++, polymorphism means that if the same message is sent to different objects, the object s behavior depends on the nature of the object itself. This is sort of obvious for completely different objects, but the concept starts making sense when combined with inheritance.

What is Message passing
It is the process of invoking an operation on an object. In response to a message the corresponding method is executed in the object.

What is Extensibility
C++ allows the extension of the functionality of the existing software components. In C++ this is achieved through abstract classes and inheritance.

What is Persistence
The phenomenon where the object (data) outlives the program execution time and exists between executions of a program is known as persistence. All data base systems support persistence. In c++ it is not supported. However the user can build it explicitly using file streams in a program.

What is Delegation
Delegation is a way of making object composition as powerful as inheritance. In delegation two objects are involved in handling a request a receiving object delegates operations to its delegate. This is analogous to child class sending requests to the parent class.

What is Genericity
It is technique for defining software components that have more than one interpretation depending on the data type of parameters. Thus it allows the declaration of data items without specifying their exact data type.

[Type text]

Page 3

C++ Short Note
Overloading:
Overloading is one type of Polymorphism. It allows an object to have different meanings, depending on its context. When an existing operator or function begins to operate on new data type, or class, it is understood to be overloaded.

Reusability:
This term refers to the ability for multiple programmers to use the same written and debugged existing class of data. This is a time saving device and adds code efficiency to the language. Additionally, the programmer can incorporate new features to the existing class, further developing the application and allowing users to achieve increased performance. This time saving feature optimizes code, helps in gaining secured applications and facilitates easier maintenance on the application. The implementation of each of the above object-oriented programming features for C++ will be highlighted in later sections.

A sample program to understand the basic structure of C++
Sample Code 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32.

//program to read employee details and to output the data ////////// code begins here ///////////////////////////// #include <iostream> //&#8594; Preprocessor directive using namespace std; class employee //&#8594; Class Declaration { private: char empname[50]; int empno; public: void getvalue() { cout<<"INPUT Employee Name:"; cin>>empname; cout<<"INPUT Employee Number:"; cin>>empno; } void displayvalue() { cout<<"Employee Name:"<<empname<<endl; cout<<"Employee Number:"<<empno<<endl; } }; main() { employee e1; e1.getvalue();

//&#8594; Creation of Object

[Type text]

Page 4

C++ Short Note
33. e1.displayvalue(); 34. } 35. 36. ///// code ends here ////////////// 37.    The // in first line is used for representing comment in the program. The second line of the program has a # symbol which represents the preprocessor directive followed by header file to be included placed between < >. The next structure present in the program is the class definition. This starts with the keyword class followed by class name employee. Within the class are data and functions. The data defined in the class are generally private and functions are public. These explanations we will be detailed in later sections. The class declaration ends with a semicolon. main() function is present in all C++ programs. An object e1 is created in employee class. Using this e1 the functions present in the employee class are accessed and there by data are accessed. The input namely ename and eno is got using the input statement namely cin and the values are outputted using the output statement namely cout. 



[Type text]

Page 5

bool. A variable name must begin with a letter. float. . Variable names written in capital letters differ from variable names with the same name but written in small letters. Pointer c. the variable name EXFORSYSdiffers from the variable name exforsys. Float d. Double c.C++ Short Note Data Types in C++: 1. constants and data types in C++. Constants and Data types in C++ In this C++ tutorial. Enumerated d. punctuation symbols or other characters are not permitted to denote variable name. Derived Type a. Reference Enum Data Type:  Assigning a number to constant  Benefits over DEFINE : Makes program readable Compiler automatically assigns integer values to the constants Required very low maintenance Variable. Structure b. . Array b. for example: character _ Rules for defining variable name: y y y y y A variable name can have one or more letters or digits or underscore for example character _. Function d. User Defined: a. Built-In: a. short int. Union c. char. long double. For example. digits or underscore. double. int. Char 3. The variable name is a sequence of one or more letters. Void e. C++ is a case-sensitive language. Variable names cannot be keywords or any reserved words of the C++ programming language. A variable is identified or denoted by a variable name. Page 6 [Type text] . long int. . . Variables A variable is the storage location in memory that is stored by its value. White space. Int b. you will learn about variable. rules for defining variable name. Class 2. declaring variables and constants.

long int) are further assigned a value of signed or unsigned. the variable must first be declared. [Type text] Page 7 . This declares a variable name a of type int. The date type can be int or float or any of the data types listed above. y and z all of data type int. signed int z.z This declares 3 variables x. The syntax for declaring variable names is data type variable name. Signed integers signify positive and negative number value. By default. If there exists more than one variable of the same type.C++ Short Note As previously explained. The amount of memory used to store a single character is different from that of storing a single integer. For example: int a. The data type using integers (int. Declaring Variables: In order for a variable to be used in C++ programming language. Unsigned integers signify only positive numbers or zero. For example it is declared as unsigned short int a. int b=5. short int. such variables can be represented by separating variable names using comma. is declared a signed integer It is possible to initialize values to variables: data type variable name = value. Example: int a=0. Example: int a. A variable name is given based on the rules for defining variable name (refer above rules). The amount of memory allocated or occupied by each variable differs as per the data stored. For instance int x.y. unspecified integers signify a signed integer. a variable is the storage location in memory that is stored by variable value. A variable must be declared for the specific data type.

C++ Short Note Constants Constants have fixed value.1567 4. Octal notation is represented with the number preceded by a zero character. Integer constants are represented as decimal notation. Decimal notation is represented with a number.02e24 These examples are valid floating point constants. and hexadecimal notation. Example 80 represent decimal 0115 represent octal 0x167 represent hexadecimal By default. Character constants have single character presented between single quotes. Example: Exforsys Training is an example of string constant. The long integer constant is represented with character l. the integer constant is represented with a number. Example 2. A hexadecimal number is preceded with the characters 0x. Example: 78 represent int 85u present unsigned int 78l represent long Floating point constants are numbers with decimal point and/or exponent. like variables. [Type text] Page 8 . Floating point constants can be represented with f for floating and l for double precision floating point numbers. Example c a are all character constants. These sequence of characters are represented between double quotes. contain data type. octal notation. The unsigned integer constant is represented with an appended character u. Strings are sequences of characters signifying string constants. Constants.

Theprivate member is inaccessible from outside the class. There are three main types of access specifiers in C++ programming language: y y y y private public protected A private member within a class denotes that only members of the same class have accessibility. but they are used to instantiate objects. class exforsys { data. member functions. A class is specified with a name after the keyword class. this unit of objects make up a class. Therefore.. they cannot be accessed from outside the class but can be accessed from the derived class. }. A protected access specifier is a stage between private and public access. If member functions defined in a class are protected. How to write a Class: In Structure in C programming language. the body of the class is defined with the member functions data. A class is an extended concept similar to that of structure in C programming language. Page 9 y y [Type text] . Classes are not objects. Features of Class: Classes contain data known as members and member functions.C++ Short Note An Overview about Objects and Classes In object-oriented programming language C++. The C++ programming language extends this concept. Public members are accessible from outside the class. Following the flower brace symbol. The starting flower brace symbol. There are different access specifiers for defining the data and functions present inside a class. In C++ programming language. a structure is specified with a name. the data and functions (procedures to manipulate the data) are bundled together as a self-contained unit called an object. the collection of members and member functions is an object. Then the class is closed with a flower brace symbol} and concluded with a colon. . Access specifiers: Access specifiers are used to identify access rights for the data and member functions of the class. this class describes the data properties alone. . class describes both the properties (data) and behaviors (functions) of objects. {is placed at the beginning of the code. As a unit.

public or protectedwhen needed. }. the members are defaulted to private access. Generally. General Template of a class: General structure for defining a class is: class classname { acess specifier: data member. followed by a semicolon and then define the data and member functions under it. acess specifier: data member.y. the member x and y are defined as private access specifiers. The member function sum is defined as a public access specifier.y. Private is the default access level for specifiers. member functions. in class. public: void sum() { [Type text] Page 10 . the programmer must use the keywords: private. member functions. class exforsys { int x. If no access specifiers are identified for members of a class. class exforsys { private: int x. all members (data) would be declared as private and the member functions would be declared as public. In the code above.C++ Short Note When defining access specifiers. public: void sum() { } }.

C++ Short Note } }. Objects are also declared as: class name followed by object name. public: void sum() { } }. exforsys e1. Just as we declare a variable of data type int as: int x. } The object can also be declared immediately after the class definition. main() { exforsys e1. This declares e1 to be an object of class exforsys. [Type text] Page 11 . exforsys would have the default access specifier as private. for members x and y of the class exforsys there are no access specifiers identified. one or more objects can be created from the class as objects are instance of the class.y. Creation of Objects: Once the class is created. In this example. For example a complete class and object declaration is given below: class exforsys { private: int x. In other words the object name can also be placed immediately before the closing flower brace symbol } of the class declaration.

C++ Short Note For example class exforsys { private: int x. It is important to understand that in object-oriented programming language. Then the member access is written as: e1. The programmer now understands declaration of a class. b. For example.y. A class and object are defined below: class exforsys { int a. The dot operator is used to connect the object and the member function. The private data of a class can be accessed only through the member function of that class. difference between struct and class and scope resolution operator. creation of an object and accessibility of members of a class. when a class is created no memory is allocated.sum(5. public: void sum(int. This concept is similar to that of accessing structure members in C programming language. Where e1 is the object of class exforsys and sum() is the member function of the class. General syntax to access class member: Object_name.int). It is possible to access the class members after a class is defined and objects are created. you will learn how to access Class members. It is also possible to declare more than one object within a class: [Type text] Page 12 . public: void sum() { } }e1 . It is only when an object is created is memory then allocated. How to Access C++ Class Members In this C++ tutorial. ) used above is called the dot operator or class member access operator. The above code also declares an object e1 of class exforsys.function_name (arguments).6). } e1. The dot ( . dot operator or class member access operator.

//Here access specifier is public by default }.C++ Short Note class exforsys { private: int a. main() { exforsys e1. class exforsys { int x. declaration of member function alone can occur within the class. //Here access specifier is private by default }. In a situation such as this.e2. the access specifier for members of a class is private. Sometimes. } In these two objects e1 and e2 are declared of class exforsys. The programmer may choose to place the definition outside the class. It is not always the case that the member function declaration and definition takes place within the class itself. By default. This is an important difference to recognize and understand in object-oriented C++ programming language. whereas struct exforsys { int x. public: void sum(int) { } }. it is important to [Type text] Page 13 . The default access specifier for a structure is public.

e2. This is performed by using the operator :: this is called scope resolution operator. class exforsys { private: int a.C++ Short Note understand the identifying member function of a particular class. // Only Member Function declaration is done void exforsys :: getvalues() // Here Member Function is defined { } main() { exforsys e1. public: void getvalues() }. } [Type text] Page 14 .

It is also possible to request input for more than one variable in a single input stream statement. The cin statement waits for input from the user s keyboard that is then stored in the integer variable prog. For inputting. cin >> sample. Syntax for using the standard input stream is cin followed by the operator >> followed by the variable that stores the data extracted from the stream. This duration is dependent on the user pressing the RETURN key on the keyboard. cin >> prog. which is an object. The overloaded operator of extraction. example. two values are input by the user. The input stream cin waits for the user to press the RETURN key then begins to process the command. is used on the standard input stream. In both of the above cases. cin >> y. For example: int prog. Standard Input Stream Generally. the variable prog is declared as an integer type variable. C++ programming language uses the concept of streams to perform input and output operations using the keyboard and to display information on the monitor of the computer. The standard input and output stream objects of C++ are declared in the header file iostream. cin >> example. the keyword cin is used. The input stream cin wait before proceeding for processing or storing the value. What is a Stream? A stream is an object where a program can either insert or extract characters to or from it. >>. you will learn about standard input stream and standard output stream explained along with syntax and examples. } Header File Inclusion Statement [Type text] Page 15 . is the same as: cin >> x. one value for the variable x and another value for the variable y. The next statement is the cin statement. In the example above. // This is a sample program This is a comment Statement #include <iostream.C++ Short Note C++ Standard Input Output Stream In this C++ tutorial. in this case: cin stream. the device used for input is the keyboard. A single cin statement is as follows: cin >> x >> y.h> void main() { int sample.

two integer variables are input with values. The above gives output as: Training given by Exforsys If a programmer chooses to use constant strings of characters. The second statement outputs the value of the variable exforsys. which is an object. The vital point to note is cin stops when it encounters a blank space. In the above example. It is also possible to display a sentence as follows: cout << Training given by Exforsys . cout << prog. the comments should follow after a pair of slashes denoted by //. In the above. the variable prog is declared as an integer type variable. The programmer can produce input of any data type. As previously explained. The insertion operator << is used on the standard output cout stream. it is important to note the difference between the two statements below: cout << "exforsys". the extraction operator >> can be used more than once in a single cin statement. For this purpose. Standard Output Stream By default. it is possible to use the insertion operator << more than once in a cout statement. For example: int prog. Similarly. This information is then stored in the integer variable prog. the device used for output is the screen of the computer. It is also possible to input strings in C++ program using cin. This is performed using the same procedures. then the above approach would be tiresome. they must be enclosed between double quotes . The value of prog is displayed on the screen by the standard output stream cout. In the above example. When using a cin. it is possible to produce only one word. This produces output on the screen as: Exforsys gives excellent training [Type text] Page 16 . the first statement displays on the screen as exforsys. cin >> prog. there is a function in C++ called getline. If a user wants to input a sentence. The next statement is the cin statement that waits for input from the user s keyboard. The syntax for using the standard output stream is cout followed by the operator << followed by the value to be inserted or output by the insertion operator. In this situation.C++ Short Note If a programmer wants to write comments in C++ program. All the characters after the // are ignored by C++ compiler and the programmer can choose to comment after the //. cout << exforsys. For example cout << "Exforsys" << "gives" << "excellent training". For outputting values the keywordcout is used.

For example int a=50. The above produces output as: Exforsys Training An important point to note from the above example is cout does not give a line break unless specified. This produces the output as: Exforsys has given 50 numbers of trainings Below is one more example: cout << Exforsys . gives output as [Type text] Page 17 . for example cout << "Exforsys\n ". cout << Training . cout << "Training". it must be explicitly specified in cout by using the \n which denotes newline character. the programmer chooses to display a combination of string constants andvariables. If the programmer chooses to display output in a new line.C++ Short Note The above concept is mainly used if the programmer chooses to print string constants followed by variables. In this next example. cout << "Exforsys has given" << a << "numbers of trainings".

For example cout << "Exforsys" << endl.h> void main() { int a. gives the same output as Exforsys Training Example to demonstrate the use of input andoutput streams // Example to demonstrate the use of Input and Output streams #include <iostream. cin >> a. } [Type text] Page 18 .C++ Short Note Exforsys Training There is also another way for specifying newline that is by using endl manipulator.b. cout << Value of b is: <<b. b=a+10. cout << Enter the value of a: . cout << "Training".

&& operator. The following table reflects the value of || operator: false true false false false false || Operator x y x || y true true true true false true false true true false false false Conditional Operator The conditional operator evaluates an expression returning a value if that expression is true and a different value if the expression is evaluated as false. &&. Logical Operators The logical operators used are : !. conditional operator. you will learn about logical operators. bitwise operator and sizeof() operator. comma operator. [Type text] Page 19 . The following table reflects the value of &&operator: && Operator x y x && y true true true true false false The operator || corresponds with Boolean logical operation OR. This has a single operand which reverses its value. The operator produces a true value if either one of its two operands are true and produces a false value only when both operands are false. For example: !true gives the value of false !false gives the value of true The operator && corresponds with Boolean logical operation AND. || operator. || The operator ! is called NOT operator. This operator returns the value of true if both its operands are true or if it returns false.C++ Short Note C++ Operators Part I Operators in C++ Part II In this C++ tutorial.

and it is used to separate two or more expressions. Comma Operator This is denoted by. x+3). Here value of 5 is assigned to x and then the value of x+3 is assigned to the variable exfor.C++ Short Note The syntax is: condition ? value1 : value2 For example: In 7>5 ? x : y Since 7 is greater than 5. This operator returns the size in bytes of the variable or data type. For example: exfor = (x=5. Hence. [Type text] Page 20 . y y For example: x = sizeof (char). value of the variable exfor is 8. true is returned and hence the value x is returned. Bitwise Operators The following are the bitwise operators available in C++: y y y y y y y & AND Bitwise AND | OR Bitwise Inclusive OR ^ XOR Bitwise Exclusive OR ~ NOT Unary complement (bit inversion) << SHL Shift Left >> SHR Shift Right Explicit type casting operator y sizeof() Operator y This operator accepts a single parameter and this can be a variable or data type.

C++ Short Note y This returns the size of char in bytes. The data is manipulated by the programmer s choice of display. In this example.h> void main( ) { int x1=12345. C++ Manipulators In this C++ tutorial. The syntax is: setw(x) Here setw causes the number or string that follows it to be printed within a field of x characters wide and x is the argument set in setw manipulator.h> #include <iostream.h> #include <iomanip. } The output of the above example is: [Type text] Page 21 . setfill manipulator and setprecision manipulator explained along with syntax and examples. Some of the more commonly used manipulators are provided here below: endl Manipulator: This manipulator has the same functionality as the \n newline character. x3=7892. The header file that must be included while using setwmanipulator is <iomanip. For example: cout << "Exforsys" << endl. cout << setw(8) << Exforsys << setw(20) << Values << endl << setw(8) << E1234567 << setw(20)<< x1 << end << setw(8) << S1234567 << setw(20)<< x2 << end << setw(8) << A1234567 << setw(20)<< x3 << end.x2= 23456. produces the output: Exforsys Training setw Manipulator: This manipulator sets the minimum field width on output. There are numerous manipulators available in C++. What is a Manipulator? Manipulators are operators used in C++ for formatting output. you will learn what a manipulator is. cout << "Training". endl manipulator. setw manipulator. the size is 1 byte which is assigned to variable x.

If a value does not entirely fill a field. setprecision Manipulator: The setprecision Manipulator is used with floating point numbers.h> void main( ) { float x = 0.1. #include <iostream. The keyword fixed before the setprecision manipulator prints the floating point number in fixed notation.C++ Short Note setw(8) setw(20) Exforsys Values E1234567 12345 S1234567 23456 A1234567 7892 setfill Manipulator: This is used after setw manipulator. It is used to set the number of digits printed to the right of the decimal point. So the remaining 8 positions are filled with $ symbol which is specified in the setfill argument.h> #include <iomanip. #include <iostream. The keyword scientific before the setprecision manipulator prints the floating point number in scientific notation. This may be used in two forms: y y fixed scientific These two forms are used when the keywords fixed or scientific are appropriately used before thesetprecision manipulator.h> #include <iomanip. cout << fixed << setprecision(3) << x << endl. then the character specified in the setfill argument of the manipulator is used for filling the fields. } The output of the above program is $$$$$$$$5033 This is because the setw sets 10 width for the field and the number 50 has only 2 positions in it. cout << sceintific << x << endl.h> void main( ) { cout << setw(10) << setfill('$') << 50 << 33 << endl. } [Type text] Page 22 .

100. || The operator ! is called NOT operator.100 1. &&. || operator. The operators used for this purpose in C++ are: y y y y y y == Equal to != Not equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to Operators in C++ Part II In this C++ tutorial. The second cout produces the output in scientific notation. This operator returns the value of true if both its operands are true or if it returns false. This has a single operand which reverses its value. The default value is used since no setprecision value is provided. && operator. Relational and Equality Operators These operators are used for evaluating a comparison between two expressions.000000e-001 The first cout statement contains fixed notation and the setprecision contains argument 3. comma operator. The following table reflects the value of &&operator: && Operator x y x && y true true true true false false false true false [Type text] Page 23 . This means that three digits after the decimal point and in fixed notation will output the first coutstatement as 0. bitwise operator and sizeof() operator.C++ Short Note The above gives ouput as: 0. conditional operator. The value returned by the relational operation is a Boolean value (true or false value). For example: !true gives the value of false !false gives the value of true The operator && corresponds with Boolean logical operation AND. you will learn about logical operators. Logical Operators The logical operators used are : !.

C++ Short Note false false false The operator || corresponds with Boolean logical operation OR. The syntax is: condition ? value1 : value2 For example: In 7>5 ? x : y Since 7 is greater than 5. true is returned and hence the value x is returned. [Type text] Page 24 . The following table reflects the value of || operator: || Operator x y x || y true true true true false true false true true false false false Conditional Operator The conditional operator evaluates an expression returning a value if that expression is true and a different value if the expression is evaluated as false. The operator produces a true value if either one of its two operands are true and produces a false value only when both operands are false.

Bitwise Operators The following are the bitwise operators available in C++: y y y y y y y & AND Bitwise AND | OR Bitwise Inclusive OR ^ XOR Bitwise Exclusive OR ~ NOT Unary complement (bit inversion) << SHL Shift Left >> SHR Shift Right Explicit type casting operator y sizeof() Operator y This operator accepts a single parameter and this can be a variable or data type. the size is 1 byte which is assigned to variable x. and it is used to separate two or more expressions. In this example. This operator returns the size in bytes of the variable or data type. y y For example: x = sizeof (char). value of the variable exfor is 8. y This returns the size of char in bytes. Hence. Here value of 5 is assigned to x and then the value of x+3 is assigned to the variable exfor. For example: exfor = (x=5. [Type text] Page 25 .C++ Short Note Comma Operator This is denoted by. x+3).

The function of initialization is automatically carried out by the use of a special member function called a constructor... Also called one argument constructor. } Copy constructor: This constructor takes one argument. also used to copy an object. What is the use of Destructors and General Syntax of Destructors. b=0. public: Exforsys(). [Type text] Page 26 . The syntax generally is as given below: new" operator. Exforsys :: Exforsys() { a=0.b. What is the use of Constructor. Destructors. }. Constructors: What is the use of Constructor The main use of constructors is to initialize objects. Both the above formats can be sued to invoke a copy constructor. or Exforsys e3=e2. There are several forms in which a constructor can take its shape namely: Default Constructor: This constructor has no arguments in it. For example to invoke a copy constructor the programmer writes: Exforsys e3(e2). Constructors.. The copy constructor allows the programmer to create a new object from an existing one by initialization. The main use of copy constructor is to initialize the objects while in creation. . Default Constructor is also called as no argument constructor. General Syntax of Constructor Constructor is a special member function that takes the same name as the class name.C++ Short Note Class Constructors and destructors in C++ In this C++ tutorial you will learn about Class Constructors and destructors in C++ viz. General Syntax of Constructor. For example: class Exforsys { private: int a.

cout<< \ne3= . Destructors What is the use of Destructors Destructors are also special member functions used in C++ programming language. Destructors are used to free memory. The constructor must be a public member. public: Exforsys() {} Exforsys(int w) { a=w.result().e3. volatile. } }. Destructors are automatically named when an object is destroyed. } Exforsys(Exforsys& e) { a=e. or const volatile.C++ Short Note For Example: #include <iostream.h> class Exforsys() { private: int a. cout<< Example of Copy Constructor . Like constructors. No return type is specified for a constructor. void main() { Exforsys e1(50). Exforsys e3(e1). Destructors have the opposite function of a constructor. nor can the programmer declare a constructor as const. release resources and to perform other clean up. Overloading of constructors is possible. The constructor must be defined in the public. The programmer cannot declare a constructor as virtual or static. } In the above the copy constructor takes one argument an object of type Exforsys which is passed by reference. This will be explained in later sections of this tutorial. [Type text] Page 27 . } void result() { cout<< a. The output of the above program is Example of Copy Constructor e3=50 Some important points about constructors: y y y y y A constructor takes the same name as the class name. destructors also take the same name as that of the class name.a. The main use of destructors is to release dynamic allocated memory.

C++ Short Note General Syntax of Destructors ~ classname(). For example: class Exforsys { private: public: Exforsys() {} ~ Exforsys() {} } [Type text] Page 28 . the destructor must also be defined in the public. The Destructor does not take any argument which means that destructors cannot be overloaded. The destructor must be a public member. In the above. No return type is specified for destructors. the symbol tilda ~ represents a destructor which precedes the name of the class. Like the constructor. Some important points about destructors: y y y y Destructors take the same name as the class name. The above is the general syntax of a destructor.

Defining Static Function: This is done by using the keyword static before the member function which is to be declared as static function General syntax: static return_data_type fucntionname() //Static function defined with keyword static { statement1...h> class example { private: static int sum... statement2..... //Statements for execution inside static function . The main usage of static function is when the programmer wants to have a function which is accessible even when the class is not instantiated...... When a member is declared as static that is a static member of class have only one such data for the entire class even though there are many objects created for the class...C++ Short Note Static Functions .... . //Static data int x. To recollect a normal member function gets accessed using the object and an operator called as the dot member access operator. .. The function declared as static or static functions gets accessed using just the class name and the operator called as scope resolution operator which is not possible in case of normal member functions.. x=sum..... } Accessing Static Function: We have seen in our earlier sections about accessing a normal member function.. } ~example() //Destructor of the class [Type text] Page 29 .... public: example() //Constructor of the class { sum=sum+1.. Let us see an example to understand the declaration of static member function and how to access static member function in detail: #include <iostream... } For example if a function exforsys returning nothing is to be declared as staic function it is done as follows: static void exforsys() { ..An Introduction The static member functions have a class scope and they do not have access to the 'this' pointer of the class..

But the normal member function number() is accessed using the object name and the dot member access operator as [Type text] Page 30 . We can see that the static function is accessed using the class name example and the scope resolution operator :: as example::exforsys().number(). e3 and e4 are created for the class example. e2. We see that four objects e1. example::exforsys(). e4. //Normal member function accessed using object e1 and the dot member access operator . } The output of the above program is: Result is: 1 Result is: 4 Number is: 1 Number is: 2 Number is: 3 Number is: 4 In the above we have seen that the function exforsys() s defined as static function and the integer data type sum is declared as static data type. } void number() //Normal member function number( ) { cout<<"\nNumber is: "<<x. } }.e4.number(). void main() { example e1. e3.number().number(). The constructor of the class example increments the sum by 1 and the destructor of the class decrements sum by 1.e3. } static void exforsys() //Static function exforsys( ) defined with keyword static { cout<<"\nResult is: "<<sum.C++ Short Note { sum=sum-1. example::exforsys(). e1. //Static function exforsys() accessed using class name example and the scope resolution operator :: example e2. e2.

This aspect is well achieved with high performance by the concept of abstraction in C++. One must note the following while using static member functions: A static member function can access only static member data. Modularity is very important in any programming language. it provides flexibility to users for using the programming language.number() e4. The main idea behind data abstraction is to give a clear separation between properties of data type and the associated implementation details. Because a static member function can be called. 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. abstraction forms the basic platform for the creation of user-defined data types called objects. But it is not the case with static member functions.number() e2. static member functions and data and functions outside the class. A non-static member functions can be declared as virtual but care must be taken not to declare a static member function as virtual. for each separate object of the class the static data gets created and initialized only once. It is possible to declare a data member of a class as static irrespective of it being public or private type in class definition. Thus.e3 and e4 created which makes the sum to gets incremented thrice from 1 in the constructor of the corresponding class namely example making the value of sum as 4 which is displayed in the second result. Just like the concept of static data. So one must take essential care not to use static member function like a non-static member function which can access all of the above including the static data member. C++ Abstraction Abstraction is one of the most powerful and vital features provided by object-oriented C++ programming language. in which the variables are shared by all objects of the class in static functions also it apply to all objects of the class A non-static member function can be called only after instantiating the class as an object. In object-oriented programming language the programmer can abstract both data and code when needed. What is Abstraction The concept of abstraction relates to the idea of hiding data that are not needed for presentation. One must first understand the concept of static data also while learning the context of static functions. Data abstraction is the process of refining data to its [Type text] Page 31 . even when a class is not instantiated. Also for accessing static function one can use the class name followed by the scope resolution operator as seen in example above.When the static function exforsys() is called the second time there were three more objects e2. That is unlike non-static data members that are created again and again.C++ Short Note e1. If a data is declared as static then the static data gets created and initialized only once.number() e3.number() The first time when the static function exforsys() is called there was one object created and this the sum gets incremented by 1 in the constructor printing the result of sum as 1. From the above explanation it is clear that the static function operate on the class and not in object generally. Also a static member function cannot have access to the 'this' pointer of the class.

Data abstraction refers to the data that can be used without taking into account how the data are stored. The concept of abstraction brings forth another related term known as encapsulation. This concept is called data hiding which is similar in concept to data abstraction. This approach makes the application development easier. For example. 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. access to the function is provided through a specific interface defined to invoke the function. in data abstraction. There are various ways of achieving abstraction in object-oriented programming language C++. it is possible to replace code without recompilation. Easier Replacement: With the concept of abstraction in object-oriented programming language. access to the data is provided through a specific set of operations defined to examine and manipulate the data. These functions can be reused when needed. 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. Encapsulation is the process of combining or packaging data with functions and thereby allowing users to create a new data type. Defining module types allow the module to be an abstract data type. The modular based approach helps to centralize all data of a similar type. this problem is resolved through the concept of friend functions. For instance. This makes the process easier and saves time for users. this means that users are using the concept of data abstraction. there is a small drawback associated with the approach to accessing module type. known as functions. a programmer might write a function for computing an average and another programmer might write a function for computing salary. How Types of Abstraction Differs: There are two broad types of abstraction. This new data type is termed abstract data type. functional abstraction and data abstraction. when a programmer is using C++ standard data types. There is also a difference in the way the access takes place in functional abstraction and data abstraction. In C++.C++ Short Note essential form. One approach is to take modular based code that is broken apart into smaller segments. Enhanced Security: Abstraction gives access to data or details that are needed by users and hide the implementation details. The programmer can decide which user to give or grant access to and hide the other details. In functional abstraction. it is termed [Type text] Page 32 . by anyone. In object-oriented programming language C++. Though the new data type is similar to that of built-in data type. Reasons for the need of Abstraction Flexibility in approach: By hiding data or abstracting details that are not needed for presentation. under the control of a type module. Modular Approach: In object-oriented programming language C++. Then all modules are integrated and ultimately tested together. When using data types. giving enhanced security to application. the programmer achieves greater flexibility in approach. In contrast. In many other programming languages. Friend functions resolve the problem by associating with one of the classes or some of its members as friends of the other class. it is possible to create and provide an interface that accesses only certain elements of data types. the abstraction concept helps users to divide the project application into modules and test each of them separately. This functional or modular approach helps the code to be reused again and again when needed. 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.

Neither too much access nor too much control must be placed on the operations in order to make the class user friendly. Encapsulation clearly represents the ability to bundle related data and functionality within a single... the data members integer x. the programmer cannot directly access the data. Using the method of encapsulation.. In the above example..example(char* se).endfunc() and other member functions are bundled and put inside a single autonomous entity called class Exforsys. There are advantages of using this encapsulated approach in C++. Data hiding is the implementation details of a class that are hidden from the user. This exemplifies the concept of Encapsulation. Attention must be paid to ensure that the class is designed properly.. autonomous entity called a class. Data encapsulation led to the important concept of data hiding. int example(char *se) int endfunc().C++ Short Note abstract data type because it enables users to abstract a concept from the problem space into the solution space. Hiding the implementation details and providing restrictive access leads to the concept of abstract data type... all the features that hold for built-in types also hold for abstract data types... For instance: class Exforsys { public: int sample(). .... //Other member functions private: int x... [Type text] Page 33 .... One advantage is that it reduces human errors. The concept of restricted access led programmers to write specialized functions or methods for performing the operations on hidden members of the class. It is clear from the above example that the encapsulated objects act as a black box for other parts of the program through interaction. Type checking process that are performed for built-in types are also achieved in the same way and level for abstract data types.. float sq and other data members and member functions sample()...... C++ Encapsulation Introduction Encapsulation is the process of combining data and functions into a single unit called class.. . . This special feature is available in object-oriented language C++ but not available in procedural language C. //Other data members }.. Although encapsulated objects provide functionality... the calling objects will not know the implementation details. Apart from the above.... This enhances the security of the application. Encapsulation leads to the concept of data hiding. . Data is only accessible through the functions present inside the class. but the concept of encapsulation must not be restricted to information hiding. float sq.... The data and functions bundled inside the class take total control of maintenance and thus human errors are reduced.

In order to benefit from the powerful feature of encapsulation in object-oriented programming language C++. operations or objects that behave differently in different contexts. C++ Polymorphism Introduction Polymorphism is the ability to use an operator or function in different ways. If an application needs to be extended or customized in later stages of development. Features and Advantages of the concept of Encapsulation: * Makes Maintenance of Application Easier: Complex and critical applications are difficult to maintain. Polymorphism refers to codes. protected or private. the object-oriented programming language C++ created the concept of encapsulation which bundles data and related functions together as a unit called class. * Improves the Understandability of the Application * 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. To resolve this maintenance difficulty. Elements placed after the keyword protected are accessible only to the methods of the class or classes derived from that class. A class placed after the keyword public is accessible to all the users of the class. there exists the protected access specifier. The programmer is then able to utilize the concept of friend functions. The cost associated with maintaining the application is higher than that of developing the application properly. Encapsulation alone is a powerful feature that leads to information hiding. This prevents unauthorized access. Polymorphism gives different meanings or functions to the operators or functions. there by giving an additional security to existing application. In between the public and the private access specifiers. Poly. The elements placed after the keyword private are accessible only to the methods of the class. signifies the many uses of these operators and functions. abstract data type and friend functions. the task of adding new functions becomes easier without breaking existing code or applications. This adds security. To maximize the benefits of encapsulation.C++ Short Note 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. The concept of encapsulation shows that a non-member function cannot access an object's private or protected data. the programmer must use encapsulation properly. but in some cases the programmer might require an unrelated function to operate on an object of two different classes. the user must minimize the implementation details in external interfaces as needed. referring to many. Thus. making maintenance much easier on the class level. Below is a simple example of the above concept of polymorphism: 6 + 10 [Type text] Page 34 . A single function usage or an operator functioning in many ways can be called polymorphism.

The above concept leads to operator overloading. Another convenient approach the programmer can take is to define a base class named Shape and then create an instance of that class. Polymorphism refers to the ability to call different functions by using only one type of function call. The same + operator can be used with different meanings with strings: "Exforsys" + "Training" The same + operator can also be used for floating point addition: 7. rectangles. The member function must be declared virtual in the base class. float or strings referring the concept ofpolymorphism. In order for this to occur. One way to define each of these classes is to have a member function for each that makes vehicles of each shape.C++ Short Note The above refers to integer addition. When the exiting operator or function operates on new data type it isoverloaded. In the above example. a single function or an operator functioning in many ways depends upon the usage to function properly. squares. A single operator + behaves differently in different contexts such as integer. The concept of overloading is also a branch of polymorphism. Features and Advantages of the concept of Polymorphism: [Type text] Page 35 . the shapes of vehicles (circle. the member function for making the vehicle should be made as virtual to the base class. This is the basis for Virtual function implementation. the following conditions must apply: y y All different classes must be derived from a single base class. etc. 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. In the above example. In polymorphism. rectangle) are from the single base class called Shape. as per the shape desired. Suppose a programmer wants to code vehicles of different shapes such as circles. triangle. by inserting pointers into the defined array.15 + 3. This feature of polymorphism leads to the concept of virtual methods. Polymorphism is used to give different meanings to the same concept.78 Polymorphism is a powerful feature of the object oriented programming language C++. This approach leads to different functions executed by the same function call.

C++ Short Note Applications are Easily Extendable: Once an application is written using the concept of polymorphism. It is unnecessary to recompile original programs by adding new types. By utilizing the concept of polymorphism. y y y Virtual functions Function name overloading Operator overloading In addition to the above three types of polymorphism. Types of Polymorphism: C++ provides three different types of polymorphism. This is the greatest achievement of C++ object-oriented programming. Helps in achieving robustness in applications. time and work effort is reduced in addition to making future maintenance easier. it can easily be extended. In general. 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. providing new objects that conform to the original interface. there has always been a need for adding and customizing. In programming language. Provides easier maintenance of applications. 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. y y y Helps in reusability of code. compile-time: The compile-time polymorphism is implemented with templates. there are two main categories ofPolymorphism namely [Type text] Page 36 . there exist other kinds of polymorphism: y y y y run-time compile-time ad-hoc polymorphism parametric polymorphism Other types of polymorphism defined: run-time: The run-time polymorphism is implemented with inheritance and virtual functions. Only re-linking is necessary to exhibit the new changes along with the old application.

The main difference between a non-virtual C++ member function and a virtual member function is in the way they are both resolved. For example: a Make function in a class Vehicle may have to make a Vehicle with red color. C++ Virtual Functions What are Virtual Functions? Virtual. the Make function for FourWheeler should now have a different functionality from the one at the class called Vehicle. Virtual Functions are resolved during run-time or dynamic binding y y y Virtual functions are member functions of a class. may have to use a blue background and 4 tires as wheels. The objectoriented programming language C++ implements the concept of virtual function as a simple member function. Templates or parametric classes fall under the category of Pure Polymorphism. The functionality of virtual functions can be over-ridden in its derived classes. detailed in an example below. A class called FourWheeler.C++ Short Note y y Ad Hoc Polymorphism Pure Polymorphism Overloading concepts fall under the category ofAd Hoc Polymorphism and Virtual methods. derived or inherited from Vehicle. The concept of virtual function is the same as a function. the general syntax to declare a Virtual Function uses: class classname //This denotes the base class of C++ virtual function [Type text] Page 37 . Virtual functions are also simple member functions. Function overloading is a different concept and will be explained in later sections of this tutorial. Need for Virtual Function: The vital reason for having a virtual function is to implement a different functionality in the derived class. Properties of Virtual Functions: y Dynamic Binding Property: Virtual Functions are resolved during run-time or dynamic binding. For example. Virtual function takes a different functionality in the derived class. as the name implies. The programmer must pay attention not to confuse this concept with function overloading. but it does not really exist although it appears in needed places in a program. Virtual function is a mechanism to implement the concept of polymorphism (the ability to give different meanings to one function). like all member functions of the class. Virtual functions are declared with the keyword virtual. Declaration of Virtual Function: Virtual functions are member functions declared with the keyword virtual. A non-virtual C++ member function is resolved during compile time or static binding. is something that exists in effect but not in reality. This concept is called Virtual Function. For this scenario.

... the declaration of Virtual function would take the shape below: class Vehicle //This denotes the base class of C++ virtual function { public: virtual void Make() //This denotes the C++ virtual function { cout <<"Member function of Base Class Vehicle Accessed"<<endl.. . it is written as: class Vehicle //This denotes the base class of C++ virtual function { public: virtual void Make() //This denotes the C++ virtual function { cout <<"Member function of Base Class Vehicle Accessed"<<endl. When the class FourWheeler is derived or inherited from Vehicle and defined by the virtual function in the class FourWheeler... } }... In this derived class. the derived class is defined. After the virtual function is declared...C++ Short Note { public: virtual void memberfunctionname() //This denotes the C++ virtual function { ...... Referring back to the Vehicle example..... the new definition of the virtual function takes place.. } }.. } }.. class FourWheeler : public Vehicle { public: [Type text] Page 38 ..

This is used by the compiler whenever a virtual function is needed. In this derived class. Declaration of Pure Virtual Function: Since pure virtual function has no body. } In the above example. the compiler creates a v-table each time a virtual function is declared. } }. explained with examples. General Syntax of Pure Virtual Function takes the form: [Type text] Page 39 . the base class member function is always called because linking takes place during compile time and is therefore static. C++ Pure Virtual Function and Virtual Base Class In this C++ tutorial. class FourWheeler is derived from the base class Vehicle. To achieve the concept of dynamic binding in C++. making it dynamic binding and thus the derived class member function is called. you will learn about pure virtual function. void main() { Vehicle *a. a->Make(). the programmer must add the notation =0 for declaration of the pure virtual function in the base class. If the member function has not been declared as virtual. the member function is declared virtual and the address is bounded only during run time. b->Make(). In this example. it is evidenced that after declaring the member functions Make() as virtual inside the base class Vehicle. declaration of pure virtual function and virtual base class. virtual base class and how to implement a virtual base class. This v-table contains classes and pointers to the functions from each of the objects of the derived class. b = new FourWheeler(). *b. the new implementation for virtual function Make() is placed. The programmer might be surprised to see the function call differs and the output is then printed as above. What is Pure Virtual Function: Pure Virtual Function is a Virtual function with no body.C++ Short Note void Make() { cout<<"Virtual Member function of Derived class FourWheeler Accessed"<<endl. a = new Vehicle().

//Denotes pure virtual Function Definition }. To understand the declaration and usage of Pure Virtual Function. } }. Exf1 e1. } [Type text] Page 40 . arra[1]->example(). arra[0]->example(). arra[1]=&e2. class Exf2:public Exforsys { public: void example() { cout<<"To Training". arra[0]=&e1.C++ Short Note class classname //This denotes the base class of C++ virtual function { public: virtual void virtualfunctioname() = 0 //This denotes the pure virtual function in C++ }. The other concept of pure virtual function remains the same as described in the previous section of virtual function. class Exf1:public Exforsys { public: void example() { cout<<"Welcome". Exf2 e2. refer to this example: class Exforsys { public: virtual void example()=0. } }. void main() { Exforsys* arra[2].

a list of pointers is defined to the base class. Special care must be taken not to remove the statement of declaration of the pure virtual function in the base class. As shown in the above diagram. [Type text] Page 41 . }. The pure virtual function example() takes up new definition. In the main function. the output is as in the above example. the Training class is derived from both of the derived classes Exf1 and Exf2. The programmer must clearly understand the concept of pure virtual functions having no body in the base class and the notation =0 is independent of value assignment. The two derived class named Exf1 and Exf2 are derived from the base class Exforsys. Two objects named e1 and e2 are defined for derived classes Exf1 and Exf2. the pure virtual function example() is declared with notation =0 in the base class Exforsys. The pointers should point to the base class Exforsys. The notation =0 simply indicates the Virtual function is a pure virtual function as it has no body. if a user has a member function in the class Training where the user wants to access the data or member functions of the class Exforsys it would result in error if it is performed like this: class Exforsys { protected: int x. there are two derived classes Exf1 and Exf2 from the base class Exforsys. accessing statements of the pure virtual function such as. arra[0]->example() and arra[1]->example() would result in an error. The address of the objects e1 and e2 are stored in the array pointers which are then used for accessing the pure virtual function example() belonging to both the derived class EXf1 and EXf2 and thus.C++ Short Note Since the above example has no body. Some programmers might want to remove this pure virtual function from the base class as it has no body but this would result in an error. In this scenario. Without the declaration of the pure virtual function in the base class. Virtual Base Class In the above example.

This means that each of the subobjects have Exforsys member data and member functions and each have one copy of member data x. class Training:public Exf1. class Exf2:public Exforsys { }. For Example: class Exforsys { protected: int x. Both of the derived classes Exf1 and Exf2 are created as virtual base classes. } }. resulting in a compile time error. This results in an error because the derived classes Exf1 and Exf2 (derived from base class Exforsys) create copies of Exforsys called subobjects. Virtual base class is used. class Exf2:virtual public Exforsys { }. class Training:public Exf1. class Exf1:virtual public Exforsys { }.C++ Short Note class Exf1:public Exforsys { }. The above program results in a compile time error as the member function example() of class Training tries to access member data x of class Exforsys. When the member function of the class Training tries to access member data x. confusion arises as to which of the two copies it must access since it derived from both derived classes. .public Exf2 [Type text] Page 42 .public Exf2 { public: int example() { return x. When this occurs. meaning they should share a common subobject in their base class.

y y y y y [Type text] Page 43 . a friend function is an ordinary function or a member of another class. A class can allow non-member functions and other classes to access its own private data. would have the rights to access the private members of the class. This results in only one copy that the member function example() of Class Training can access the member data x. For handling such cases. This enables them to share a common subobject of their base class Exforsys. Some important points to note while using friend functions in C++: y The keyword friend is placed only in the function declaration of the friend function and not in the function definition. C++ Friend Functions In this C++ tutorials. seen in example below. when a data is declared as private inside a class. The function can be invoked without the use of an object.C++ Short Note { public: int example() { return x. the concept of Friend functions is a useful tool. The friend function has its argument as objects. even though it is not a member function. In the above example. } }. then it is not accessible from outside the class. need for friend function. It is possible to declare the friend function as either private or public. . except the function declaration of these functions is preceded with the keyword friend. It is possible to declare a function as friend in any number of classes. . When a class is declared as a friend. . The friend function must have the class to which it is declared as friend passed to it in argument. . A programmer may have a situation where he or she would need to access private data from nonmember functions and external classes. Need for Friend Function: As discussed in the earlier sections on access specifiers. both Exf1 and Exf2 are created as Virtual base classes by using the keyword virtual. . What is a Friend Function? A friend function is used for accessing the non-public members of a class. A friend function. you will learn about friend functions. the friend class has access to the private data of the class that made this a friend. Thus. explained with example. by making them friends. A function that is not a member or an external class will not be able to access the private data. how to define and use friend function and few important points regarding friend function. How to define and use Friend Function in C++: The friend function is written as any other normal function.

C++ Short Note Example to understand the friend function: #include class exforsys { private: int a. } friend int compute(exforsys e1) //Friend Function Declaration with keyword friend and with the object of class exforsys to which it is friend passed to it }.test().b)-5. the function has access to the private data a and b of the class exforsys. the [Type text] Page 44 . The function definition is written as a normal function and thus. } The output of the above program is The result is:295 The function compute() is a non-member function of the class exforsys. b=200. //Calling of Friend Function with object as argument. In order to make this function have access to the private data a and b of class exforsys .a+e2. </compute(e). int compute(exforsys e1) { //Friend Function Definition which has access to private data return int(e1. It is declared as friend inside the class. cout<<"The result is:"<<compute(e). As a first step.b. e. } main() { exforsys e. the function compute() is declared as friend in the class exforsys as: friend int compute (exforsys e1) The keyword friend is placed before the function. public: void test() { a=100. it is created as a friend function for the class exforsys.

...h> [Type text] Page 45 .. . General syntax: static return_data_type fucntionname() //Static function defined with keyword static { statement1. Example: The declaration of static member function and how to access static member function: #include <iostream.. 5 is subtracted from the result.. } For example if a function exforsys returning nothing is to be declared as staic function it is done as follows: static void exforsys() { . Defining Static Function: Static function is defined by using the keyword static before the member function that is to be declared as static function.... //Statements for execution inside static function statement2.C++ Short Note private data values a and b are added.. C++ Static Functions Static member functions have a class scope and they do not have access to the 'this' pointer of the class.. giving 295 as the result.... .. When a member is declared as static. ... a static member of class.......... The functions declared static or static functions are accessed using only the class name and the scope resolution operator. The main usage of static function is when the programmer wants to have a function which is accessible even when the class is not instantiated..... This is returned by the function and thus the output is displayed as shown above... } Accessing Static Function: A normal member function is accessed using the object and an operator called the dot member access operator.. it has only one data for the entire class even though there are many objects created for the class. unlike in normal member functions where these are not used.

//Normal member function accessed using object e1 and the dot member access operator.e4. e4. e1. //Static function exforsys() accessed using class name example and the scope resolution operator :: example e2. e2. x=sum.C++ Short Note class example { private: static int sum.number(). example::exforsys(). e3. } void number() //Normal member function number( ) { cout<<"\nNumber is: "<<x. } //Destructor of the class static void exforsys() //Static function exforsys( ) defined with keyword static { cout<<"\nResult is: "<<sum. void main() { example e1. } The output of the above program is: [Type text] Page 46 . int x. } }. example::exforsys(). public: example() { sum=sum+1.number().e3.number(). } //Static data //Constructor of the class ~example() { sum=sum-1.number().

But the normal member function number() is accessed using the object name and the dot member access operator as e1. as non-static member function can access all of the above including the static data member. e3 and e4 are created for the class example.number() e4. it is clear that the static function operates on the class and not in object. A non-static member function can be declared as virtual but care must be taken not to declare a static member function as virtual. .C++ Short Note Result is: 1 Result is: 4 Number is: 1 Number is: 2 Number is: 3 Number is: 4 In the above example. followed by the scope resolution operator. The constructor of the class example increments the sum by 1 and the destructor of the class decrements sum by 1.When the static function exforsys() is called the second time. If a data is declared as static. static member functions and data and functions outside the class. Four objects e1. the sum is incremented by 1 in the constructor printing the result of sum as 1. As in the concept [Type text] Page 47 . then the static data is created and initialized only once. . as seen in example above. e2.number() e2. The programmer must first understand the concept of static data while learning the context of static functions.e3 and e4 created which results in the sum incremented thrice from 1 in the constructor of the corresponding class example. The programmer must note the following while using static member functions: y y y A static member function can only access static member data. To access static function the programmer can use the class name. which is displayed in the second result. Non-static data members are created again and again. The programmer must take note not to use static member function in the same manner as non-static member function. It is possible to declare a data member of a class as static irrespective of it being a public or a private type in class definition. the static data is created and initialized only once. the function exforsys() is defined as static function and the integer data type sum is declared as static data type. For each separate object of the class. The static function is accessed using the class name example and the scope resolution operator :: as example::exforsys(). Applying the above explanation. there were three more objects e2. resulting in the value of sum as 4.number() e3.number() The first time the static function exforsys() is called. there was one object created and thus.

A static member function cannot have access to the 'this' pointer of the class. If a user writes the statement: exf=&f. . all objects of the class in static functions share the variables. y C++ Void Pointer and Null Pointer In this C++ tutorial. Then this statement produces an error.C++ Short Note y of static data. These pointers will be discussed in conjunction with syntax. if the programmer tries to place the address of an integer variable to a float pointer. Similarly. The address of the float variable is stored in an integer pointer that is incorrect. it is known that the data type the pointer variable defines is the same as the data type the pointer points to. For example: int i. void pointers and Null Pointer. The address placed in a pointer must have the same type as the pointer. then exf=&i. Referring back to pointer definitions and usage. This applies to all objects of the class. int* exf. Is correct because the address of integer variable is stored in an integer pointer. float* test. Void is used as a keyword. This is not the case with static member functions. float f. . even when a class is not instantiated. A static member function can be called. [Type text] Page 48 . such as: test=&i. usage and example. A non-static member function can be called only after instantiating the class as an object. Pointer to Void General Syntax: void* pointer_variable. you will learn about two interesting types of pointers.

The programmer must change the pointer to void as any other pointer type that points to valid data types such as. exforsys=0. The Pointer to Void is a special type of pointer that the programmer can use to point to any data type. This is. sample=&i. char. the programmer declares pointer to void in this manner: void* sample. Using the above example s definition and assigning the pointer to void to the address of an integer variable is perfectly correct. sample=&f. however. Using the above example to define the pointer to void and assign the pointer to void to the address of a float variable as below is also perfectly correct. Using the above example. [Type text] Page 49 . Direct dereferencing of void pointer is not permitted. Pointer to void. This denotes that NULL pointer does not point to any valid memory address. This conversion of pointer to some other valid data type is achieved by using the concept of type-casting (refer to type-casting section of this tutorial). not mandatory. The concept of dereferencing using the operator * has been explained in an earlier section of this tutorial. is a special type of pointer that has a great facility of pointing to any data type. This shows that exforsys has a NULL pointer value. or a void pointer. NULL Pointer: The concept of NULL pointer is different from the above concept of void pointer. There are limitations in the usage of void pointers that are explained below.C++ Short Note The above statement will also show an error. NULL pointer is a type of pointer of any data type and generally takes a value as zero. int. The above statement denotes exforsys as an integer pointer type that does not point to a valid memory address. The programmer must note that void pointers cannot be de-referenced in the same manner. For example: int* exforsys. float and then dereference it.

h> int *exforsys=NULL. } The output of the above program is NULL POINTER ASSIGNMENT The above program will result in a runtime error. NULL pointers can take any pointer type. void main() { *exforsys=100. It is important to note that a NULL pointer is different from a pointer that is not initialized.C++ Short Note The difference between void pointers and NULL pointers: A Void pointer is a special type of pointer of void and denotes that it can point to any data type. but do not point to any valid reference or memory address. attempting to access the address 0 gives the above error message. For example. This means that the pointer variable exforsys is not assigned any valid address and. [Type text] Page 50 . therefore. if a programmer uses the program below: #include <iostream.

the programmer should make it a practice to first assign them a value. In the above example. This operator can be used to create object of any type. Memory Management Operators: Need: The concept of arrays has a block of memory reserved. The disadvantage with the concept of arrays is that the programmer must know. the size of memory to be allocated in addition to the array size remaining constant. In the above statement. the programmer can opt to reserve as much memory as possible. assigning the maximum memory space needed to tackle this situation. while programming. The pointer variable a holds the address of memory space allocated. New operator: The new operator in C++ is used for dynamic storage allocation.C++ Short Note Scope Resolution Operator: It refers to the global variable always. Therefore. For example: int *a=new int. Dynamic variables are never initialized by the compiler. Memory management operators are used to handle this situation in C++ programming language What are memory management operators? There are two types of memory management operators in C++: y y new delete These two memory management operators are used for allocating and freeing memory blocks in efficient and convenient ways. The assignment can be made in either of the two ways: [Type text] Page 51 . the new operator allocates sufficient memory to hold the object of datatype int and returns a pointer to its starting point. In programming there may be scenarios where programmers may not know the memory needed until run time. This would result in wastage of unused memory spaces. In this case. new is a keyword and the pointer variable is a variable of type datatype. General syntax of new operator in C++: The general syntax of new operator in C++ is as follows: pointer variable = new datatype.

C++ Short Note int *a = new int. We know that sizeof operator is used for computing the size of the object. . Null pointer is returned by the new operator when there is insufficient memory available for allocation. } The output of the above program is [Type text] Page 52 . Overloading of new and delete operator is possible (to be discussed in detail in later section on overloading).h> void main() { //Allocates using new operator memory space in memory for storing a integer datatype int *a= new a. cout << " The Output is:a="<<a. delete operator: The delete operator in C++ is used for releasing memory space when the object is no longer needed. Some of the important points the programmer must note while using memory management operators are described below: y y y y y The programmer must take care not to free or delete a pointer variable that has already been deleted. . In the above example. General syntax of delete operator in C++: The general syntax of delete operator in C++ is as follows: delete pointer variable. it is efficient to use the corresponding delete operator for release of memory. The programmer must take care not to free or delete pointer variables that have not been allocated using a new operator. Using memory management operator. . delete is a keyword and the pointer variable is the pointer that points to the objects already created in the new operator. *a=100. or int *a = new int(20). Once a new operator is used. Example: to understand the concept of new and delete memory management operator in C++: #include <iostream. the size of the object is automatically computed. . //Memory Released using delete operator delete a. *a = 20.

The memory allocated by the new operator for storing the integer variable pointed by a is released using the delete operator as: delete a. Like any operator new and delete can be overloaded Inline Function: The function which expands in line is called as Inline Function. the statement: int *a= new a. The statement: *a=100 This denotes that the value present in address location pointed by the pointer variable a is 100 and this value of a is printed in the output statement giving the output shown in the example above. It Automatically return the correct pointer type so we need not have to type cast it 3.C++ Short Note The Output is:a=100 In the above program. [Type text] Page 53 . Advantages of new over malloc: 1. The situations in which you can t use Inline Function are:  In switch or goto  Static variables  Recursive function Static Data members:  Only visible in the class but the lifetime is entire program  Only one copy exist and entire class shares that copy  Initialized to zero when the first object of its class is created. We need not have to use sizeof operator as it automatically calculates the size of the operator 2. Holds memory space in memory for storing a integer data type. It Saves memory.

Sign up to vote on this title
UsefulNot useful