C++ IMP Points
C++ IMP Points
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.
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
9 ncapsulation
9 £ata abstraction
9 Inheritance
9 Polymorphism
9 ºessage passing
9 xtensibility
9 Persistence
9 £elegation
9 Ñenericity
9 ºultiple Inheritance
OOP uses objects as its fundamental building blocks. ach 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 are the basic run-time entities in an object-oriented system. very 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.
It is the process of invoking an operation on an object. In response to a message the corresponding method is
executed in the object.
"
C++ allows the extension of the functionality of the existing software components. In C++ this is achieved through
abstract classes and inheritance.
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.
£elegation 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.
#
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.
$
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.
%
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.
c
Sample Code
1.
2. ÕÕ
3.
4. ÕÕÕÕÕÕÕÕÕÕ
ÕÕÕÕÕÕÕÕÕÕÕÕÕÕÕÕÕÕÕÕÕÕÕÕÕÕÕÕÕ
5. include <iostream> //& 594; Preprocessor directive
6. using namespace std;
7. class employee ÕÕ
.
9. private:
10. char empname[50];
11. int empno;
12.
13. public:
14. void getvalue()
15.
16. cout<<"INPUT mployee Name:";
17. cin>>empname;
1 . cout<<"INPUT mployee Number:";
19. cin>>empno;
20. }
21.
22. void displayvalue()
23.
24. cout<<"mployee Name:"<<empname<<endl;
25. cout<<"mployee Number:"<<empno<<endl;
26. }
27. };
2 .
29. main()
30.
31. employee e1; ÕÕ
32. e1.getvalue();
&
Assigning a number to constant
Benefits over £FIN :
X ºakes program readable
X Compiler automatically assigns integer values to the constants
X Required very low maintenance
A 'c
c
In this C++ tutorial, you will learn about variable, constants and data types in C++, rules for defining
variable name, short int, int, long int, float, double, long double, char, bool, declaring variables and
constants.
A
A variable is the storage location in memory that is stored by its value. A variable is identified or denoted
by a variable name. The variable name is a sequence of one or more letters, digits or underscore, for
example: character _
%
$
9 A variable name can have one or more letters or digits or underscore for example character _.
.
9 White space, punctuation symbols or other characters are not permitted to denote variable name. .
9 A variable name must begin with a letter.
.
9 Variable names cannot be keywords or any reserved words of the C++ programming language.
.
9 C++ is a case-sensitive language. Variable names written in capital letters differ from variable names
with the same name but written in small letters. For example, the variable name FORSYSdiffers
from the variable name exforsys.
For instance
int x,y,z
This declares 3 variables x, y and z all of data type int.
The data type using integers (int, short int, long int) are further assigned a value of signed or unsigned.
Signed integers signify positive and negative number value. Unsigned integers signify only positive
numbers or zero.
For example it is declared as
unsigned short int a;
signed int z;
By default, unspecified integers signify a signed integer.
For example:
int a;
is declared a signed integer
It is possible to initialize values to variables:
data type variable name = value;
"
int a=0;
int b=5;
"
0 represent decimal
0115 represent octal
0x167 represent hexadecimal
By default, the integer constant is represented with a number.
The unsigned integer constant is represented with an appended character u. The long integer constant is
represented with character l.
"
7 represent int
5u present unsigned int
7 l represent long
Floating point constants are numbers with decimal point and/or exponent.
"
2.1567
4.02e24
These examples are valid floating point constants.
Floating point constants can be represented with f for floating and l for double precision floating point
numbers.
Character constants have single character presented between single quotes.
"
͚c͛
͚a͛
are all character constants.
Strings are sequences of characters signifying string constants. These sequence of characters are
represented between double quotes.
"
͞xforsys Training͟
is an example of string constant.
In object-oriented programming language C++, the data and functions (procedures to manipulate the
data) are bundled together as a self-contained unit called an . A
is an extended concept
similar to that of
in C programming language, this class describes the data properties alone. In
C++ programming language,
describes both the properties (data) and behaviors (functions) of
objects.
are not
, but they are used to instantiate
.
c
Classes contain data known as members and member functions. As a unit, the collection of members
and member functions is an object. Therefore, this unit of objects make up a class.
( c
In Structure in C programming language, a structure is specified with a name. The C++ programming
language extends this concept. A class is specified with a name after the keyword class.
The starting flower brace symbol, is placed at the beginning of the code. Following the flower brace
symbol, the body of the class is defined with the member functions data. Then the class is closed with a
flower brace symbol} and concluded with a colon;.
class exforsys
data;
member functions;
͙͙͙͙͙
};
There are different access specifiers for defining the data and functions present inside a class.
Access specifiers are used to identify access rights for the data and member functions of the class. There
are three main types of access specifiers in C++ programming language:
9 private
9 public
9 protected
9 A member within a class denotes that only members of the same class have accessibility.
The member is inaccessible from outside the class.
.
9
members are accessible from outside the class.
.
9 A protected access specifier is a stage between and
access. If member functions
defined in a class are , they cannot be accessed from outside the class but can be accessed
from the derived class.
class exforsys
private:
int x,y;
public:
void sum()
͙͙͙
͙͙͙
}
};
In the code above, the member and are defined as private access specifiers. The member function
sum is defined as a public access specifier.
Ñeneral structure for defining a class is:
class classname
acess specifier:
data member;
member functions;
acess specifier:
data member;
member functions;
};
Ñenerally, in class, all members (data) would be declared as private and the member functions would be
declared as public. Private is the default access level for specifiers. If no access specifiers are identified
for members of a class, the members are defaulted to private access.
class exforsys
int x,y;
public:
void sum()
͙͙͙
͙͙͙
In this example, for members x and y of the class
there are no access specifiers identified.
would have the default access specifier as private.
c
Once the class is created, one or more objects can be created from the class as objects are instance of
the class. Just as we declare a variable of data type as:
int x;
Objects are also declared as:
class name followed by object name;
exforsys e1;
This declares ! to be an object of class exforsys. For example a complete class and object declaration is
given below:
class exforsys
private:
int x,y;
public:
void sum()
͙͙͙
͙͙͙
}
};
main()
exforsys e1;
͙͙͙͙͙
͙͙͙͙͙
}
The object can also be declared immediately after the class definition. In other words the object
name can also be placed immediately before the closing flower brace symbol } of the class
declaration.
(
c c
!
In this C++ tutorial, you will learn how to access Class members, dot operator or class member access
operator, difference between struct and class and scope resolution operator.
It is possible to access the class members after a class is defined and objects are created.
Ñeneral syntax to access class member:
Object_name.function_name (arguments);
The dot (͚.͛) used above is called the or
. The dot operator is
used to connect the object and the member function. This concept is similar to that of accessing
structure members in C programming language. The private data of a class can be accessed only through
the member function of that class.
" ,
A class and object are defined below:
class exforsys
int a, b;
public:
void sum(int,int);
} e1;
class exforsys
private:
int a;
public:
void sum(int)
͙͙͙
͙͙͙
}
};
main()
exforsys e1,e2;
͙͙͙͙
͙͙͙͙
}
class exforsys
int x; //Here access specifier is private by default
};
whereas
struct exforsys
int x; //Here access specifier is public by default
};
It is not always the case that the member function declaration and definition takes place within the class
itself. Sometimes, declaration of member function alone can occur within the class. The programmer
may choose to place the definition outside the class. In a situation such as this, it is important to
class exforsys
private:
int a;
public:
void getvalues() // Only ºember Function declaration is done
};
main()
exforsys e1,e2;
͙͙͙͙
}
Ñenerally, the device used for input is the keyboard. For inputting, the keyword is used, which is an
object. The overloaded operator of extraction, >>, is used on the standard input stream, in this
case: stream. Syntax for using the standard input stream is cin
"
variable
#
"
int prog;
cin >> prog;
In the example above, the variable is declared as an integer type variable. The next statement is
the statement. The statement waits for input from the user͛s keyboard that is then stored in the
integer variable .
The input stream wait before proceeding for processing or storing the value. This duration is
dependent on the user pressing the RTURN key on the keyboard. The input stream waits for the
user to press the RTURN key then begins to process the command. It is also possible to request input
for more than one variable in a single input stream statement. A single statement is as follows:
cin >> x >> y;
is the same as:
cin >> x;
cin >> y;
In both of the above cases, two values are input by the user, one value for the variable x and another
value for the variable y.
In the above example, two integer variables are input with values. The programmer can produce input
of any data type. It is also possible to input strings in C++ program using . This is performed using the
same procedures. The vital point to note is stops when it encounters a blank space. When using a
cin, it is possible to produce only one word. If a user wants to input a sentence, then the above
approach would be tiresome. For this purpose, there is a function in C++ called
.
By default, the device used for output is the screen of the computer. For outputting values the
keyword is used, which is an object. The insertion operator << is used on the standard
output stream. The syntax for using the standard output stream is followed by the
operator << followed by the value to be inserted or output by the insertion operator.
"
int prog;
cin >> prog;
cout << prog;
In the above example, the variable is declared as an integer type variable. The next statement is
the statement that waits for input from the user͛s keyboard. This information is then stored in the
integer variable prog. The value of is displayed on the screen by the standard output stream .
It is also possible to display a sentence as follows:
cout << ͞ Training given by xforsys͟;
The above gives output as:
Training given by xforsys
If a programmer chooses to use constant strings of characters, they must be enclosed between double
quotes ͞ ͟.
In this situation, it is important to note the difference between the two statements below:
cout << "exforsys";
cout << exforsys;
In the above, the first statement displays on the screen as exforsys. The second statement outputs the
value of the variable exforsys. As previously explained, the extraction operator >> can be used more
than once in a single statement. Similarly, it is possible to use the insertion operator << more than
once in a statement.
"
The above concept is mainly used if the programmer chooses to print string constants followed by variables.
In this next example, the programmer chooses to display a combination of string
and
.
"
int a=50;
cout << "xforsys has given" << a << "numbers of trainings";
xforsys Training
An important point to note from the above example is does not give a line break unless specified. If the
programmer chooses to display output in a new line, it must be explicitly specified in by using the \n which
denotes "
character.
"
gives output as
"
xforsys
Training
"
M
c
In this C++ tutorial, you will learn about logical operators, && operator, || operator, conditional operator, comma
operator, bitwise operator and sizeof() operator.
*
The logical operators used are : !, &&, ||
The operator ! is called ?$ operator. This has a single operand which reverses its value.
"
!true gives the value of false
!false gives the value of true
The operator && corresponds with Boolean logical operation x?. This operator returns the value of true if both
its operands are true or if it returns false. The following table reflects the value of operator:
--
" "--
The operator || corresponds with Boolean logical operation %. The operator produces a
false true false true value if either one of its two operands are true and produces a false value only when
both operands are false. The following table reflects the value of || operator:
&
"
"
In
7>5 ? x : y
Since 7 is greater than 5, true is returned and hence the value x is returned.
c
This is denoted by, and it is used to separate two or more expressions.
"
Here value of 5 is assigned to x and then the value of x+3 is assigned to the variable exfor. Hence, value of the
variable exfor is .
+
The following are the bitwise operators available in C++:
9 "
x = sizeof (char);
9 This returns the size of char in bytes. In this example, the size is 1 byte which is assigned to variable x.
c !
In this C++ tutorial, you will learn what a manipulator is, endl manipulator, setw manipulator, setfill manipulator
and setprecision manipulator explained along with syntax and examples.
! )
ºanipulators are operators used in C++ for formatting output. The data is manipulated by the programmer͛s
choice of display.
There are numerous manipulators available in C++. Some of the more commonly used manipulators are provided
here below:
"
cout << "xforsys" << endl;
cout << "Training";
include <iostream.h>
include <iomanip.h>
void main( )
int x1=12345,x2= 23456, x3=7 92;
cout << setw( ) << ͟xforsys͟ << setw(20) << ͟Values͟ << endl
<< setw( ) << ͞1234567͟ << setw(20)<< x1 << end
<< setw( ) << ͞S1234567͟ << setw(20)<< x2 << end
<< setw( ) << ͞A1234567͟ << setw(20)<< x3 << end;
}
include <iostream.h>
include <iomanip.h>
void main( )
cout << setw(10) << setfill('$') << 50 << 33 << endl;
}
!
The setprecision ºanipulator is used with floating point numbers. It is used to set the number of digits printed to
the right of the decimal point. This may be used in two forms:
9 fixed
9 scientific
These two forms are used when the keywords fixed or scientific are appropriately used before
thesetprecision manipulator. The keyword fixed before the setprecision manipulator prints the floating point
number in fixed notation. The keyword scientific before the setprecision manipulator prints the floating point
number in scientific notation.
include <iostream.h>
include <iomanip.h>
void main( )
float x = 0.1;
cout << fixed << setprecision(3) << x << endl;
cout << sceintific << x << endl;
}
The first cout statement contains fixed notation and the setprecision contains argument 3. This means that three
digits after the decimal point and in fixed notation will output the first coutstatement as 0.100. The
second cout produces the output in scientific notation. The default value is used since no setprecision value is
provided.
9 == qual to
9 != Not equal to
9 > Ñreater than
9 < Less than
9 >= Ñreater than or equal to
9 <= Less than or equal to
c
In this C++ tutorial, you will learn about logical operators, && operator, || operator, conditional operator, comma
operator, bitwise operator and sizeof() operator.
*
The logical operators used are : !, &&, ||
The operator ! is called ?$ operator. This has a single operand which reverses its value.
"
!true gives the value of false
!false gives the value of true
The operator && corresponds with Boolean logical operation x?. This operator returns the value of true if both
its operands are true or if it returns false. The following table reflects the value of operator:
--
" "--
The operator || corresponds with Boolean logical operation %. 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. The following table
reflects the value of || operator:
ll
" "ll
&
"
"
In
7>5 ? x : y
Since 7 is greater than 5, true is returned and hence the value x is returned.
Here value of 5 is assigned to x and then the value of x+3 is assigned to the variable exfor. Hence, value of the
variable exfor is .
+
The following are the bitwise operators available in C++:
9 "
x = sizeof (char);
9 This returns the size of char in bytes. In this example, the size is 1 byte which is assigned to variable x.
[Type text] Page 25
c
c
c
c
In this C++ tutorial you will learn about Class Constructors and destructors in C++ viz., Constructors, What is the
use of Constructor, Ñeneral Syntax of Constructor, £estructors, What is the use of £estructors and Ñeneral Syntax
of £estructors.
c
c
The main use of constructors is to initialize objects. The function of initialization is automatically carried out by the
use of a special member function called a constructor.
new" operator.
There are several forms in which a constructor can take its shape namely:
c
This constructor has no arguments in it. £efault Constructor is also called as
.
"
class xforsys
private:
int a,b;
public:
xforsys();
...
};
xforsys :: xforsys()
a=0;
b=0;
}
c
This constructor takes one argument. Also called one argument constructor. The main use of copy constructor is to
initialize the objects while in creation, also used to copy an object. The copy constructor allows the programmer to
create a new object from an existing one by initialization.
In the above the copy constructor takes one argument an object of type xforsys which is passed by reference. The
output of the above program is
£estructors are also special member functions used in C++ programming language. £estructors have the opposite
function of a constructor. The main use of destructors is to release dynamic allocated memory. £estructors are
used to free memory, release resources and to perform other clean up. £estructors are automatically named when
an object is destroyed. Like constructors, destructors also take the same name as that of the class name.
The above is the general syntax of a destructor. In the above, the symbol tilda È represents a destructor which
precedes the name of the class.
"
class xforsys
private:
͙͙͙͙͙
public:
xforsys()
}
È xforsys()
}
}
Let us see an example to understand the declaration of static member function and how to access static member
function in detail:
include <iostream.h>
class example
private:
static int sum; //Static data
int x;
public:
example() //Constructor of the class
sum=sum+1;
x=sum;
}
void main()
example e1;
example::exforsys();
//Static function exforsys() accessed using class name example and the scope resolution operator ::
example e2,e3,e4;
example::exforsys();
e1.number();
e2.number();
//Normal member function accessed using object e1 and the dot member access operator .
e3.number();
e4.number();
}
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. We see that four objects e1, e2, e3 and e4 are created for the class example. The
constructor of the class example increments the sum by 1 and the destructor of the class decrements sum by 1.
We can see that the static function is accessed using the class name example and the scope resolution operator ::
as
" "
-.1
But the normal member function number() is accessed using the object name and the dot member access operator
as
e1.number()
e2.number()
e3.number()
e4.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.When the static function exforsys() is called the
second time there were three more objects e2,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. From the above explanation it is clear that the static function operate on the class
and not in object generally. Also for accessing static function one can use the class name followed by the scope
resolution operator as seen in example above.
One must note the following while using static member functions:
A static member function can access only static member data, static member functions and data and functions
outside the class. 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.
A non-static member functions can be declared as virtual but care must be taken not to declare a static member
function as virtual.
One must first understand the concept of static data also while learning the context of static functions. It is
possible to declare a data member of a class as static irrespective of it being public or private type in class
definition. If a data is declared as static then the static data gets created and initialized only once. That is unlike
non-static data members that are created again and again, for each separate object of the class the static data gets
created and initialized only once. Just like the concept of static data, 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. But it is not the case with
static member functions. Because a static member function can be called, even when a class is not instantiated,
Also a static member function cannot have access to the 'this' pointer of the class.
c
Abstraction is one of the most powerful and vital features provided by object-oriented C++ programming language.
ºodularity is very important in any programming language, it provides flexibility to users for using the
programming language. This aspect is well achieved with high performance by the concept of abstraction in C++. In
object-oriented programming language the programmer can abstract both data and code when needed.
The concept of abstraction relates to the idea of hiding data that are not needed for presentation. The main idea
behind data abstraction is to give a clear separation between properties of data type and the associated
implementation details. This separation is achieved in order that the properties of the abstract data type are
visible to the user interface and the implementation details are hidden. Thus, abstraction forms the basic platform
for the creation of user-defined data types called objects. £ata abstraction is the process of refining data to its
In object-oriented programming language C++, it is possible to create and provide an interface that accesses only
certain elements of data types. The programmer can decide which user to give or grant access to and hide the
other details. This concept is called data hiding which is similar in concept to data abstraction.
(&
There are two broad types of abstraction;
and
. 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. £ata abstraction refers to the data that can be
used without taking into account how the data are stored. There is also a difference in the way the access takes
place in functional abstraction and data abstraction. In functional abstraction, access to the function is provided
through a specific interface defined to invoke the function. In contrast, in data abstraction, access to the data is
provided through a specific set of operations defined to examine and manipulate the data. For instance, when a
programmer is using C++ standard data types, this means that users are using the concept of data abstraction.
When using data types, the users are not concerned with how the data is stored but they are concerned with what
operations are provided and what properties are supported.
%
"
By hiding data or abstracting details that are not needed for presentation, the programmer achieves greater
flexibility in approach.
%
With the concept of abstraction in object-oriented programming language, it is possible to replace code without
recompilation. This makes the process easier and saves time for users.
!
In object-oriented programming language C++, the abstraction concept helps users to divide the project
application into modules and test each of them separately. Then all modules are integrated and ultimately tested
together. This approach makes the application development easier.
There are various ways of achieving abstraction in object-oriented programming language C++. One approach is to
take modular based code that is broken apart into smaller segments, known as functions. This functional or
modular approach helps the code to be reused again and again when needed. For example, a programmer might
write a function for computing an average and another programmer might write a function for computing salary.
These functions can be reused when needed, by anyone. The modular based approach helps to centralize all data
of a similar type, under the control of a type module. £efining module types allow the module to be an abstract
data type. In many other programming languages, there is a small drawback associated with the approach to
accessing module type.
The concept of abstraction brings forth another related term known as encapsulation. ncapsulation is the process
of combining or packaging data with functions and thereby allowing users to create a new data type. This new data
type is termed abstract data type. Though the new data type is similar to that of built-in data type, it is termed
c
ncapsulation is the process of combining data and functions into a single unit called class. Using the method of
encapsulation, the programmer cannot directly access the data. £ata is only accessible through the functions
present inside the class. £ata encapsulation led to the important concept of data hiding. £ata hiding is the
implementation details of a class that are hidden from the user. The concept of restricted access led programmers
to write specialized functions or methods for performing the operations on hidden members of the class. Attention
must be paid to ensure that the class is designed properly.
Neither too much access nor too much control must be placed on the operations in order to make the class user
friendly. Hiding the implementation details and providing restrictive access leads to the concept of abstract data
type. ncapsulation leads to the concept of data hiding, but the concept of encapsulation must not be restricted to
information hiding. ncapsulation clearly represents the ability to bundle related data and functionality within a
single, autonomous entity called a class.
class xforsys
public:
int sample();
int example(char *se)
int endfunc();
.........
......... //Other member functions
private:
int x;
float sq;
..........
......... //Other data members
};
In the above example, the data members integer x, float sq and other data members and member functions
sample(),example(char* se),endfunc() and other member functions are bundled and put inside a single
autonomous entity called class xforsys. This exemplifies the concept of ncapsulation. This special feature is
available in object-oriented language C++ but not available in procedural language C. There are advantages of
using this encapsulated approach in C++. One advantage is that it reduces human errors. The data and functions
bundled inside the class take total control of maintenance and thus human errors are reduced. It is clear from the
above example that the encapsulated objects act as a black box for other parts of the program through interaction.
Although encapsulated objects provide functionality, the calling objects will not know the implementation details.
This enhances the security of the application.
The key strength behind £ata ncapsulation in C++ is that the keywords or the access specifiers can be placed in
the class declaration as public, protected or private. A class placed after the keyword public is accessible to all the
users of the class. The elements placed after the keyword private are accessible only to the methods of the class.
In between the public and the private access specifiers, there exists the protected access specifier. lements
placed after the keyword protected are accessible only to the methods of the class or classes derived from that
class.
The concept of encapsulation shows that a non-member function cannot access an object's private or protected
data. This adds security, but in some cases the programmer might require an unrelated function to operate on an
object of two different classes. The programmer is then able to utilize the concept of friend functions.
ncapsulation alone is a powerful feature that leads to information hiding, abstract data type and friend functions.
$
* Makes MaM e a e AMaM EasMer:
Complex and critical applications are difficult to maintain. The cost associated with maintaining the application is
higher than that of developing the application properly. To resolve this maintenance difficulty, the object-oriented
programming language C++ created the concept of encapsulation which bundles data and related functions
together as a unit called class. Thus, making maintenance much easier on the class level.
* Imres e U
ersa
abMM e AMaM
* E a e
SerM:
There are numerous reasons for the enhancement of security using the concept of ncapsulation in C++. The
access specifier acts as the key strength behind the concept of security and provides access to members of class as
needed by users. This prevents unauthorized access. If an application needs to be extended or customized in later
stages of development, the task of adding new functions becomes easier without breaking existing code or
applications, there by giving an additional security to existing application.
In order to benefit from the powerful feature of encapsulation in object-oriented programming language C++, the
programmer must use encapsulation properly. To maximize the benefits of encapsulation, the user must minimize
the implementation details in external interfaces as needed.
c
Polymorphism is the ability to use an operator or function in different ways. Polymorphism gives different
meanings or functions to the operators or functions. Poly, referring to many, signifies the many uses of these
operators and functions. A single function usage or an operator functioning in many ways can be called
polymorphism. Polymorphism refers to codes, operations or objects that behave differently in different contexts.
Below is a simple example of the above concept of polymorphism:
6 + 10
The same + operator can be used with different meanings with strings:
"xforsys" + "Training"
The same + operator can also be used for floating point addition:
7.15 + 3.7
Polymorphism is a powerful feature of the object oriented programming language C++. A single operator +
behaves differently in different contexts such as integer, float or strings referring the concept of
. The
above concept leads to operator
. The concept of overloading is also a branch of
. When
the exiting operator or function operates on new data type it is
. This feature of polymorphism leads to
the concept of
.
Polymorphism refers to the ability to call different functions by using only one type of function call. Suppose a
programmer wants to code vehicles of different shapes such as circles, squares, rectangles, etc. One way to define
each of these classes is to have a member function for each that makes vehicles of each shape. Another
convenient approach the programmer can take is to define a base class named Shape and then create an instance
of that class. The programmer can have array that hold pointers to all different objects of the vehicle followed by a
simple loop structure to make the vehicle, as per the shape desired, by inserting pointers into the defined array.
This approach leads to different functions executed by the same function call. Polymorphism is used to give
different meanings to the same concept. This is the basis for &
implementation.
In polymorphism, a single function or an operator functioning in many ways depends upon the usage to function
properly. In order for this to occur, the following conditions must apply:
9 All different classes must be derived from a single base class. In the above example, the shapes of vehicles (circle, triangle,
rectangle) are from the single base class called Shape.
9 The member function must be declared virtual in the base class. In the above example, the member function for making
the vehicle should be made as virtual to the base class.
$
&
C++ provides three different types of polymorphism.
9 Virtual functions
9 Function name overloading
9 Operator overloading
In addition to the above three types of polymorphism, there exist other kinds of polymorphism:
9 run-time
9 compile-time
9 ad-hoc polymorphism
9 parametric polymorphism
r Mme:
The 'polymorphism is implemented with inheritance and virtual functions.
mMeMme:
The
' polymorphism is implemented with templates.
a
mr Msm:
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 ' polymorphism.
For example: a ºake function in a class Vehicle may have to make a Vehicle with red color. A class called
FourWheeler, derived or inherited from Vehicle, may have to use a blue background and 4 tires as wheels. For this
scenario, the ºake function for FourWheeler should now have a different functionality from the one at the class
called Vehicle. This concept is called Virtual Function.
A
Virtual Functions are resolved during run-time or dynamic binding. Virtual functions are also simple member
functions. The main difference between a non-virtual C++ member function and a virtual member function is in the
way they are both resolved. A non-virtual C++ member function is resolved during compile time or static binding.
Virtual Functions are resolved during run-time or dynamic binding
class classname //This denotes the base class of C++ virtual function
Referring back to the Vehicle example, the declaration of Virtual function would take the shape below:
class Vehicle //This denotes the base class of C++ virtual function
public:
virtual void ºake() //This denotes the C++ virtual function
cout <<"ºember function of Base Class Vehicle Accessed"<<endl;
}
};
After the virtual function is declared, the derived class is defined. In this derived class, the new definition of the
virtual function takes place.
When the class FourWheeler is derived or inherited from Vehicle and defined by the virtual function in the class
FourWheeler, it is written as:
class Vehicle //This denotes the base class of C++ virtual function
public:
virtual void ºake() //This denotes the C++ virtual function
cout <<"ºember function of Base Class Vehicle Accessed"<<endl;
}
};
void main()
Vehicle *a, *b;
a = new Vehicle();
a->ºake();
b = new FourWheeler();
b->ºake();
}
In the above example, it is evidenced that after declaring the member functions ºake() as virtual inside the base
class Vehicle, class FourWheeler is derived from the base class Vehicle. In this derived class, the new
implementation for virtual function ºake() is placed.
The programmer might be surprised to see the function call differs and the output is then printed as above. If the
member function has not been declared as virtual, the base class member function is always called because linking
takes place during compile time and is therefore static.
In this example, the member function is declared virtual and the address is bounded only during run time, making
it dynamic binding and thus the derived class member function is called.
To achieve the concept of dynamic binding in C++, the compiler creates a v-table each time a virtual function is
declared. This v-table contains classes and pointers to the functions from each of the objects of the derived class.
This is used by the compiler whenever a virtual function is needed.
c A
A +
c
In this C++ tutorial, you will learn about pure virtual function, declaration of pure virtual function and virtual base
class, virtual base class and how to implement a virtual base class, explained with examples.
A
Pure Virtual Function is a Virtual function with no body.
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.
To understand the declaration and usage of Pure Virtual Function, refer to this example:
class xforsys
public:
virtual void example()=0; //£enotes pure virtual Function £efinition
};
void main()
xforsys* arra[2];
xf1 e1;
xf2 e2;
arra[0]=&e1;
arra[1]=&e2;
arra[0]->example();
arra[1]->example();
}
Since the above example has no body, the pure virtual function example() is declared with notation =0 in the base
class xforsys. The two derived class named xf1 and xf2 are derived from the base class xforsys. The pure
virtual function example() takes up new definition. In the main function, a list of pointers is defined to the base
class.
Two objects named e1 and e2 are defined for derived classes xf1 and xf2. 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 f1 and f2 and thus, the output is as in the above example.
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 notation =0 simply indicates the Virtual function is a
pure virtual function as it 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. Without the declaration of the pure virtual function in the base class, accessing
statements of the pure virtual function such as, arra[0]->example() and arra[1]->example() would result in an error.
The pointers should point to the base class xforsys. Special care must be taken not to remove the statement of
declaration of the pure virtual function in the base class.
A +
c
In the above example, there are two derived classes xf1 and xf2 from the base class xforsys. As shown in the
above diagram, the Training class is derived from both of the derived classes xf1 and xf2. In this scenario, 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 xforsys it would result in error if it is performed like this:
class xforsys
protected:
int x;
};
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 xforsys. This results in an error because the derived classes xf1 and xf2 (derived
from base class xforsys) create copies of xforsys called subobjects.
This means that each of the subobjects have xforsys member data and member functions and each have one
copy of member data x. 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, resulting in a compile
time error.
When this occurs, Virtual base class is used. Both of the derived classes xf1 and xf2 are created as virtual base
classes, meaning they should share a common subobject in their base class.
For xample:
class xforsys
protected:
int x;
;
In the above example, both xf1 and xf2 are created as Virtual base classes by using the keyword virtual. This
enables them to share a common subobject of their base class xforsys. This results in only one copy that the
member function example() of Class Training can access the member data x.
c
In this C++ tutorials, you will learn about friend functions, need for friend function, how to define and use friend
function and few important points regarding friend function, explained with example.
As discussed in the earlier sections on access specifiers, when a data is declared as private inside a class, then it is
not accessible from outside the class. A function that is not a member or an external class will not be able to access
the private data. A programmer may have a situation where he or she would need to access private data from non-
member functions and external classes. For handling such cases, the concept of Friend functions is a useful tool.
)
A friend function is used for accessing the non-public members of a class. A class can allow non-member functions
and other classes to access its own private data, by making them friends. Thus, a friend function is an ordinary
function or a member of another class.
(
c
The friend function is written as any other normal function, except the function declaration of these functions is
preceded with the keyword friend. The friend function must have the class to which it is declared as friend passed
to it in argument.
c
9 The keyword friend is placed only in the function declaration of the friend function and not in the function
definition.
.
9 It is possible to declare a function as friend in any number of classes.
.
9 When a class is declared as a friend, the friend class has access to the private data of the class that made this a
friend.
.
9 A friend function, even though it is not a member function, would have the rights to access the private
members of the class.
.
9 It is possible to declare the friend function as either private or public.
.
9 The function can be invoked without the use of an object. The friend function has its argument as objects,
seen in example below.
include
class exforsys
private:
int a,b;
public:
void test()
a=100;
b=200;
}
friend int compute(exforsys e1)
//Friend Function £eclaration with keyword friend and with the object of class exforsys to which it is
friend passed to it
};
main()
exforsys e;
e.test();
cout<<"The result is:"<<compute(e);
</compute(e);
//Calling of Friend Function with object as argument.
}
The function compute() is a non-member function of the class exforsys. In order to make this function have access
to the private data a and b of class exforsys , it is created as a friend function for the class exforsys. As a first step,
the function compute() is declared as friend in the class exforsys as:
The keyword friend is placed before the function. The function definition is written as a normal function and thus,
the function has access to the private data a and b of the class exforsys. It is declared as friend inside the class, the
c
Static member functions have a class scope and they do not have access to the 'this' pointer of the class. When a
member is declared as static, a static member of class, it has only one data for the entire class even though there
are many objects created for the class. 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.
Static function is defined by using the keyword static before the member function that is to be declared as static
function.
#
"
For example if a function exforsys returning nothing is to be declared as staic function it is done as
follows:
"
The declaration of static member function and how to access static member function:
include <iostream.h>
void main()
example e1;
example::exforsys();
//Static function exforsys() accessed using class name example and the scope resolution operator ::
example e2,e3,e4;
example::exforsys();
e1.number();
//Normal member function accessed using object e1 and the dot member access operator.
e2.number();
e3.number();
e4.number();
}
In the above example, the function exforsys() is defined as static function and the
integer data type sum is declared as static data type. Four objects e1, e2, e3 and e4 are created for the class
example. The constructor of the class example increments the sum by 1 and the destructor of the class decrements
sum by 1.
The static function is accessed using the class name example and the scope resolution operator :: as
example::exforsys();
But the normal member function number() is accessed using the object name and the dot member access operator
as
e1.number()
e2.number()
e3.number()
e4.number()
The first time the static function exforsys() is called, there was one object created and thus, the sum is
incremented by 1 in the constructor printing the result of sum as 1.When the static function exforsys() is called the
second time, there were three more objects e2,e3 and e4 created which results in the sum incremented thrice
from 1 in the constructor of the corresponding class example, resulting in the value of sum as 4, which is displayed
in the second result. Applying the above explanation, it is clear that the static function operates on the class and
not in object. To access static function the programmer can use the class name, followed by the scope resolution
operator, as seen in example above.
The programmer must note the following while using static member functions:
9 A static member function can only access static member data, static member functions and data and functions outside the
class. The programmer must take note not to use static member function in the same manner as non-static member
function, as non-static member function can access all of the above including the static data member.
.
9 A non-static member function can be declared as virtual but care must be taken not to declare a static member function as
virtual.
.
9 The programmer must first understand the concept of static data while learning the context of static functions. 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. If
a data is declared as static, then the static data is created and initialized only once. Non-static data members are created
again and again. For each separate object of the class, the static data is created and initialized only once. As in the concept
void* pointer_variable;
Referring back to pointer definitions and usage, it is known that the data type the pointer variable defines is the
same as the data type the pointer points to. The address placed in a pointer must have the same type as the
pointer.
"
int i;
float f;
int* exf;
float* test;
then
exf=&i;
exf=&f;
Then this statement produces an error. The address of the float variable is stored in an integer pointer that is
incorrect.
Similarly, if the programmer tries to place the address of an integer variable to a float pointer, such as:
test=&i;
The Pointer to Void is a special type of pointer that the programmer can use to point to any data type.
Using the above example, 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=&i;
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.
sample=&f;
Pointer to void, or a void pointer, is a special type of pointer that has a great facility of pointing to any data type.
There are limitations in the usage of void pointers that are explained below.
The concept of dereferencing using the operator * has been explained in an earlier section of this tutorial. The
programmer must note that void pointers cannot be de-referenced in the same manner. £irect dereferencing of
void pointer is not permitted. The programmer must change the pointer to void as any other pointer type that
points to valid data types such as, int, char, float and then dereference it. 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).
3**
The concept of NULL pointer is different from the above concept of void pointer. NULL pointer is a type of pointer
of any data type and generally takes a value as zero. This is, however, not mandatory. This denotes that NULL
pointer does not point to any valid memory address.
"
int* exforsys;
exforsys=0;
The above statement denotes exforsys as an integer pointer type that does not point to a valid memory address.
This shows that exforsys has a NULL pointer value.
A Void pointer is a special type of pointer of void and denotes that it can point to any data type. NULL pointers can
take any pointer type, but do not point to any valid reference or memory address. It is important to note that a
NULL pointer is different from a pointer that is not initialized.
include <iostream.h>
int *exforsys=NULL;
void main()
*exforsys=100;
}
The above program will result in a runtime error. This means that the pointer variable exforsys is not assigned any
valid address and, therefore, attempting to access the address 0 gives the above error message.
%
It refers to the global variable always.
In programming there may be scenarios where programmers may not know the memory needed until run time. In
this case, the programmer can opt to reserve as much memory as possible, assigning the maximum memory space
needed to tackle this situation. This would result in wastage of unused memory spaces. ºemory management
operators are used to handle this situation in C++ programming language
9 new
9 delete
These two memory management operators are used for allocating and freeing memory blocks in efficient and
convenient ways.
The new operator in C++ is used for dynamic storage allocation. This operator can be used to create object of any
type.
#
" c
The general syntax of new operator in C++ is as follows:
pointer variable = new datatype;
In the above statement, new is a keyword and the pointer variable is a variable of type datatype.
"
int *a=new int;
In the above example, the new operator allocates sufficient memory to hold the object of datatype int and returns
a pointer to its starting point. The pointer variable a holds the address of memory space allocated.
£ynamic variables are never initialized by the compiler. Therefore, the programmer should make it a practice to
first assign them a value.
9 The programmer must take care not to free or delete a pointer variable that has already been deleted.
.
9 Overloading of new and delete operator is possible (to be discussed in detail in later section on overloading).
.
9 We know that sizeof operator is used for computing the size of the object. Using memory management
operator, the size of the object is automatically computed.
.
9 The programmer must take care not to free or delete pointer variables that have not been allocated using a
new operator.
.
9 Null pointer is returned by the new operator when there is insufficient memory available for allocation.
" to understand the concept of new and delete memory management operator in C++:
include <iostream.h>
void main()
//Allocates using new operator memory space in memory for storing a integer datatype
int *a= new a;
*a=100;
cout << " The Output is:a="<<a;
//ºemory Released using delete operator
delete a;
*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. The memory allocated by the
new operator for storing the integer variable pointed by a is released using the delete operator as:
delete a;
$
$
1. We need not have to use sizeof operator as it automatically calculates the size of the operator
2. It Automatically return the correct pointer type so we need not have to type cast it
3. Like any operator new and delete can be overloaded
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.