Class
- A class
is a model that defines the variables and the methods that common to all
objects of a certain kind. A class is an abstract type. A class
defines the abstract characteristics of an object, including its attributes,
fields or properties and also its behaviors or methods or features. For
example, the class Dog would consist of quality shared by all dogs,
for example breed, fur colour etc.
Object
- An object means an instance. An object is a software
bundle of variables related methods. An object is a particular
instance of a class. The set of values of the attributes of a particular
object is called its state.
Object Oriented
programming follows the following principle also known as OOPs Principle.
Inheritance
– Inheritance is where in some cases, a class will have "subclasses,"
more specialized versions of a class. Subclasses inherit attributes and
behaviors from their parent classes, and can introduce their own.
Encapsulation
- Conceals the exact details of how a particular class works from objects
that use its code or send messages to it. Encapsulation is achieved
by specifying which classes may use the members of an object. The result is
that each object exposes to any class a certain interface — those members
accessible to that class.
Polymorphism
- Polymorphism is an object-oriented programming term. The ability to
have methods with the same name, but different content, for related classes.
The procedure to use is determined at run time by the class of the object.
Function overloading, constructor overload is one of the example.
Abstraction
- Identifying the distinguishing characteristics of a
class or object without having to process all the information about the
class or object.. Represent essential features of a system without getting
involvement with the complexity of the entire system.
Modularity - The source code for an object can be written and
maintained independently of the source code for other object and an object
can be used easily by someone else in the system.
Information hiding
– An object has a public interface that other objects can communicate with
it. The object can maintain private information and methods that can changed
at any time without affecting the other objects that depend on it.
Instance
- It’s an object-oriented programming term. An object created from a class
definition. Unlike a class, which is just a definition, an instance actually
exists as an object that can be used to perform tasks.
Method
-
A method is an object's abilities. Methods or functions are
the modules from which program is built. Method can be declared with
- access-specifier, modifier, type, method-name(parameter list), where
access specifier is optional. Methods also known as functions.
access-specifier – private/ public/protected.
protected
keyword is a modifier that can be used in the declaration of methods or
variables. A protected variable or method is only visible within its class,
within its subclasses, or within the class package.
private
keyword is a modifier that can be used in the declaration of methods or
variables. Using the private modifier in the declaration for either of these
types hides the methods and variables so they cannot be directly referenced
outside of the class they're declared in. One exception to this rule is that
private methods or variables declared within a class can also be used by
inner classes.
public
keyword is a modifier that can be used in the declaration of classes and
interfaces. The public keyword can also be used as a modifier in the
declaration of methods and variables. Classes or interfaces declared as
public are visible everywhere. Methods and variables declared as public are
visible everywhere their corresponding classes are visible.
(Note that the protected,
public, private keyword cannot be used in the declaration of local
variables.)
type
– Type is compulsory for a method declaration. Type declaration indicates
that what types of values going to be returned. void (no return) or int /
float / double / Boolean / char –(if a function return a value it not
compulsory to accept a parameter form caller method).
parameter list
– are variables or objects that receive the value of argument.
static
- The static keyword is used as a modifier for methods and variables. When
the static keyword appears in a method or variable declaration, it means
that there will be only one copy of the method or variable that each class
object may reference, regardless of the number of instances of the
containing class that are created.
Data Type
: A variable
is a symbolic name for a computer memory location, while declaring a
variable the program must keep track of the type of data or information to
be stored in the variable. This definition done by the data type.
Primitive data types are
those are not composed, it also known as fundamental data types.
int -
It is a 16-bit signed two's
complement integer data type. It ranges from 32,768 to 32,767. This data
type is used for integer values. However for wider range of values use
long.
byte -
The byte data type is an
8-bit integer. It ranges from -128 to127 , byte can be used instead of int.
short int -The
short data type is a 16-bit signed two's complement integer. It ranges from
-32,768 to 32,767. short is used to save memory in array declaration.
long int -
The long data type is a
32-bit integer. It ranges from -2,147,483,648 to 2,147,483,647. Use this
data type with larger range of values.
float -
The float data type is a
single-precision 32-bit floating point. It ranges from 3.4 * (10-38)
to 3.4 * (1038). Use a float (instead of double) to save memory
in large arrays.
double -
This data type is a
double-precision 64-bit floating point. It ranges from 3.4 * (10-308)
to 3.4 * (10308) . This data type is generally the default choice
for decimal values.
char -
The char data type is a
single 16-bit, unsigned Unicode character. It ranges from 0 to 65,535.
Composite Data
Types
- In addition to the elementary data types its possible to assemble items of
different types to create composite data types such as structures, arrays,
and classes. You can build composite data types from elementary types and
from other composite types. For example, you can define an array of
structure elements, or a structure with array members.
Constant or
Literals
– A data item does not change during execution of a program is called a
constant or literals. Constant or literals can be numeric – Integer (int)
type or fractional (float or double), character or string.
e. g. 200, “hello”, 45.0F,
444.4545, TRUE, FALSE
Identifiers or
variables
– Symbolic names used for various data items in programs known as
identifiers. Identifiers also can be defined as user defined name given to
memory boxed to store data or information.
Rules for naming
identifiers. 1. Must start with an alphabet. A numeric digit allowed. No
space or symbols are allowed except an underscore. No keyword can be use as
identifiers.
Instance variable
-
Instance variables are any
variables that are defined in a constructor function and that are copied
into each object instance of that constructor. All object instances have
their own copies of instance variables.
The significance of an instance variable is
that every object instantiated from that class contains its own copy of all
instance variables.
global variable
- A variable whose value can be accessed and modified by any statement in an
application, and not merely within a single routine in which it is defined.
Variables declared just in side the class known as global variable.
class testing{
int a, b; //global
variable }
local variable
- A variable that is accessible only within a function or procedure. Other
procedures or functions cannot access this variable's data. Use global
variables to share data across many procedures and functions, or private
variables to share data with the functions you call.
Keyword
– Reserved words that convey meaning to the computer. Used to write
programming syntax. A programming syntax or statement should have at least
one keyword.
e. g. class, int, if,
for.
Operators
–
An operator is a symbol
or letter, which makes the computer perform specific operation in a
programming statement.
arithmetic operator
- Operators
that perform numeric calculations known as arithmetic operators are: +
(addition), – (subtraction), * (multiplication), / (division) and %
(modulus).
Relational operator
- An operator that manipulates numeric and other values to produce a logical
result. The relational operators are <, >,= =, <=, >=, and !=.
unary operator
- The unary
assignment operators, use two operand instead of one, for the increment (++)
and decrement (– –) operators. Its also call increment/decrement
operator. a++, a--, a+=10.
Ternary Operator
– Can be used
to replace certain of if – else-if statement. Its require three operands to
work on. It represent by the ? and : symbols.
Expression1?Expression2:Expression3
e.g. tax =
salary>10000?salary*0.05 : 0; (if variable salary stored more than 10000
then tax variable will calculated 5% of salary otherwise tax will be).
logical operator
- An operator
that produces a logical result (true or false); sometimes called a Boolean
operator. The logical operators are used for expression grouping, NOT or !
(negation), AND (Creates a Boolean behavior that represents the logical AND
of the given behaviors. The behavior's value is true when both b1 and
b2 are true; otherwise, it is false. OR (Creates a Boolean behavior
that represents the logical OR of the given behaviors. The behavior's value
is true when either b1 or b2 are true; otherwise it is false).
Binary Operator
– This operator do the binary operations between two or more variables. Also
known as bits operator. The bitwise operators
perform bitwise-AND (&), bitwise-exclusive-OR (^), and
bitwise-inclusive-OR (|) operations. E.g. 101 & 100 = 100
(Multiplication). 101 ! 100 = 101 (Addition). 101 ^ 100 = 001(If one bit is
0 and the other bit is 1, the corresponding result bit is set to 1.
Otherwise, the corresponding result bit is set to 0). Right shift >>
Left shift << (The value of a right-shift expression e1
>> e2 is e1 / 2e2, and the value of a
left-shift expression e1 << e2 is e1 * 2e2).
Function Call by
value
– When a simple type passed to a method, as a copy of the argument is being
made and passed to the function is known as call by value, any
changes made to the parameter inside the function do not affect the
original. A functions parameter list also known as signature.
void
test() {
int
a=10,b=20;
int s=sum(a, b); }
Function call by
reference
– When an object is passed as an argument to a method it is passed by
reference. A reference to an argument is passed as parameter, the value
of the argument is not passed. This method is called call by reference.
class testing
{
int a;
void input()
{
cout<<”\nEnter a No “;
cin>>a ;
}
void sum(testing test)
{
cout<<”\nSum
“<<a+test.a;
}
};
void main()
{
testing t,t1;
t.input();
t1.input();
t.sum(t1);
}
Pure function
– Pure function or accessor methods return information to the caller about a
state of an object without changing the state.
Impure function
– Pure function or mutator methods return information to the caller about a
state of an object by changing the state.
Function
overloading
– It is possible to define two or more methods or functions within the same
class can have same name, however their parameter declarations have to
differ form one another its known as Functions overloading. Functions
overloading is one of the ways where polymorphism principle implemented.
Function overloading is also known as compile time polymorphism.
Example :
#include<iostream.h>
#include<conio.h>
#include<math.h>
class test
{
public:
void
area(int);
void
area(int,int);
void area(float);
};
void test::area(int S)
{
int ans=S*S;
cout<<"\nThe
Area od Square
"<<ans;
}
void test::area(int L, int B)
{
int ans=L*B;
cout<<"\nThe
Area of Rectangle "<<ans;
}
void test:: area(float radius)
{
float
ans=3.14*pow(radius,2);
cout<<"\nThe
area of Circle is = "<<ans;
}
void main()
{
clrscr();
int a,b;
float r;
test t;
cout<<"Enter side : ";
cin>>a;
cout<<"Enter
Length & Breadth : ";
cin>>a>>b;
cout<<"enter
the radius "<<endl;
cin>>r;
t.area(a);
t.area(a,b);
t.area(r);
getch();
}
actual parameter—the
actual value that is passed into the method by a caller. Actual arguments
(those supplied by the caller) are evaluated. Caller – sum(a, b)
formal parameter—the
identifier used in a method to stand for the value that is passed into the
method by a caller. Receiver – int sum(int x, int y)
Message passing
- "The process by which an object sends data to another object or asks the
other object to invoke a method. Also known to some programming languages as
interfacing
Comment
- A comment is a remark from programmer to explain some aspect of the code
to who is reading the source code. Comments can be anything including or
excluding programming syntax as compiler ignore it. a) Single line comments
- Comments followed the // symbols
b) Multiline Comments –
The are used for comments spread over many line. They begin with /* and end
with */.
Constructors
-
The
central player in object initialization is the constructor.
Constructors are similar to methods, but they are not methods. Like a
method, a constructor has a set of parameters and a body of code. Unlike
methods, however, constructors have no return type. Like methods, you can
give access specifiers to constructors, but unlike methods, constructors
with public, protected, or package access are not inherited by subclasses.
There are two types of constructors, Default constructors can be called with
no arguments. Where parameter constructors can
- They have the same name as the class.
- If you don't define the any constructors, a no-argument constructor will be generated by machine.
- An access specifier can be use but Constructor can not be typed (int, float etc.).
Example:
class A
{
int i;
public:
A() //Default Constructor of the class A
{
i=5;
}
};
Constructor Overloading: Parameterize Constructor
: A constructor can also be overloaded with more than one function that have
the same name but different types or number of parameters. For overloaded
functions the compiler will call the one whose parameters match the
arguments used in the function call. In the case of constructors, which are
automatically called when an object is created, the one executed is the one
that matches the arguments passed on the object declaration.
Example:
class A
{
int i,j;
public:
A() //Constructor of the class A
{
i=2;
j=5;
}
A(int x) //Parameterise Constructor of
the class A
{
i=x;
j=5;
}
A(int x, int y) //Parameterise Constructor of
the class A
{
i=x;
j=y;
}
};
int main()
{
A ob_1; // value of i is 2 & value j is
5
A ob_2(4); // value of i is 4 & value j
is 5
A ob_3(4,8); // value of i is 4 & value
j is 8
return 0;
}
Copy
Constructor
: A
copy constructor is a special constructor in the C++ programming language
creating a new object as a copy of an existing object. The first argument of
such a constructor is a reference to an object of the same type as is being
constructed (const or non-const), which might be followed by parameters of
any type (all having default values).
Normally the
compiler automatically creates a copy constructor for each class (known as a
default copy constructor) but for special cases the programmer creates the
copy constructor, known as a user-defined copy constructor. In such cases,
the compiler does not create one.
Example:
#include
<iostream.h>
using
namespace std;
class Student
{
public:
int age;
explicit
Student (int x): age (x)
{}
};
int main()
{
Student
p_1(10);
Student p_2
(15);
Student ob =
p_1; //call the Default Copy Constructor
cout <<
p_1.age << " " <<p_2.age <<
" " << ob.age << endl;
p_1.age =
23;
cout <<
p_1.age << " " << p_2.age <<
" " << ob.age << endl;
return 0;
}
OUTPUT:
10 15 10
23 15 10
Explanation:
As expected, p_1
has been copied to the new object, ob. While p_1's age was changed, ob's age
remained the same. This is because they are totally different objects.
The compiler has
generated a copy constructor for us, and it could be written like this:
Student (const
Student& copy): age (copy. age)
{
}
Destructor
: Destructor functions are the inverse of constructor functions. Destructors
are called when objects are need to be destroyed. A destructor declared by
preceding the class name with a tilde (~). For example, the
destructor for class MyClass is declared:
~MyClass()
.
The destructor is
commonly used to “clean up” when an object is no longer necessary.
Type Casting
- A type cast provides a method for explicit conversion of the type of an
object in a specific situation. The compiler treats cast-expression
as type type-name after a type cast has been made. Casts can be used
to convert objects of any scalar type to or from any other scalar type.
Explicit type casts are constrained by the same rules that determine the
effects of implicit conversions.
float x = 3.1;
int
i;
i = (int)x; // the
value of i is now 3
Implicit conversion
: Implicit conversions do
not require any operator. They are automatically performed when a value is
copied to a compatible type. For example:
short
a=2000;
int b;
b=a;
Explicit conversion
: Many conversions,
specially those that imply a different interpretation of the value, require
an explicit conversion. We have already seen two notations for explicit type
conversion: functional and c-like casting:
double
a=2000.566;
int b;
b = (int) a; // c-like cast
notation
If – else if – else
- The if keyword is used to execute a statement or block of statements when
its associated expression evaluates to true. An if statement may also
have an alternative else if or else clause. If the expression defined by
the if statement evaluates to false, then control transfers to the
statement (or block of statements) following the else if or else keyword.
If the expression defined by the if statement evaluates to true,
then control transfers to the first statement following the if keyword.
Multiple conditional expression can be written in if or else if
statement separated by logical operator but there is no expression written
in else.
if ( num < 1000 ) //when num is below 1000t=0;
else if ( num <5000) // When num is equal or over 1000 but below 5000
t=100;
else t=200; // When num is equal or over 5000
switch
- The switch keyword is used along with the keyword case, and
sometimes the keyword default, to create a conditional statement. In a
switch statement, the switch keyword is followed by an expression
within parentheses. Once the expression has been evaluated, its value is
compared against the label following each case statement within the
switch statement body. When a label has the same value, the lines
following that case statement are executed. An optional default label
is included within the body of a switch statement when there is no guarantee
that the labels provided by each case statement are the only values
the switch expression may evaluate to.
switch ( someExpression ){ case 1 : cout<<“Switch-case”; break;
default : cout<<“Not a Value”;
}
The break keyword
is also, at times, used within the body of a switch statement. Once the
lines following a case statement have executed, the break statement
is included to jump over the remaining body of the switch condition.
Without a break statement, subsequent case statements would continue being
evaluated, and eventually the default statement, if one were
included, would execute.
Difference between
if-else-if-else and switch
switch-case
switch can only check of equality
switch only looks for match between the values of the
expression with one of its case constant values. No two
case constant can have identical values. Use of switch is
more convenient than multiple nested if.
When the case
constant match with criteria given computer start from that point
continue performing each case even its not satisfied the condition,
so its required jump statement like break to jump from the
table. Thus its run faster than if construct.
In switch-case
no floating point constant allowed.
|
if-else-if-else
if
can evaluate any type
if-else statement uses series of expression involving
unrelated variables.
No jump statement
can be given for if statement. It check each condition even
after it’s found its match, so it’s slower than switch-case.
In
if-else-if-else floating point constant can be used as a
condition.
|
for
- The for keyword is used to create a loop construct. An
initialization section, an expression section, and an update section
immediately follow the keyword. A semicolon separates each section, and all
appear together within at least one set of parentheses. The initialization
section allows the programmer to declare one or more local loop variables
with initial values. The expression or final value section contains an
expression that is evaluated to determine whether the loop should continue
or how long it should continue. A true result allows the loop to
continue; a false result allows control to transfer to the statement
following the loop body. The update section allows to increment loop
counters or perform other updates. Typically, the update section is used to
increment or decrement whatever loop counters the programmer defines.
for ( int i = 0; i < 10; i++ )
while
- The while keyword is used to create a loop
construct. In a while loop, the expression in parentheses immediately
following the keyword is evaluated, and if the result is true, the
statements appearing within the loop body are executed. If multiple
statements make up the body of the loop, they must be enclosed with curly
braces. Once the loop body has executed, control transfers back to the top
of the loop where the test is performed again, and the execution of the loop
body is repeated until the value of the expression evaluates to false.
While is a entry centered loop as it check the condition and then
perform the body.
while( i < 10 ) {cout<<"Printing in loop";
do-while
- The do keyword is used as part of a do/while loop. Unlike
the other, more commonly used loop constructs, a do/while loop expression is
evaluated only after the block of code within its body has been executed.
Thus, you are ensured that the code within the loop body is executed at
least once, even if the expression tested causes the loop to end. .
Do-while is an exit centered loop as it does not check any condition but
perform the body once and then check the condition. A semicolon is required
after the condition (while) in a do/while loop.
do {
cout<<"Printing at least once";
} while ( i <= 10 );
while – do-while
Difference
while
while is entry centered loop.
while check its condition and if satisfied then it
performed the body else it comes out of the loop statement and
proceeds further.
|
do-while
do-while is a exit centered loop.
do-while, start with do and does not check any condition
when computer performed the loop body first time, but check the
condition at the below, which given in while, so even condition is
not satisfied.
|
Jump Statement
– Jump statement used to transfer control to another part of the program.
break, continue worked as jump statement.
break - statement used to terminate a sequence in switch
statement. Also exit a loop depend on programmer wish.
while(a<10)
{ if(a==5) break; }//
Ü
continue
– can be used only in loop to terminate that particular process and transfer
control to the loop conditional expression.
while(a<10)
{ if(a==5) continue;} //
Û
break and continue
Difference
break can be used a jump statement in any type of loops
and switch-case.
break jump directly out of the body of the loop or
switch-case statement and follow the next statement onwards.
|
continue can be used in loop but not in switch-case
continue transfer
control to conditional expression not quite the loop.
|
statements
consist of
tokens, expressions, and other statements. A statement that forms a
component of another statement is called the “body” of the enclosing
statement. Each statement type given by the following syntax is discussed in
this chapter.
Compound Statements
(Blocks) -
A compound statement consists of zero or more statements enclosed in curly
braces ({ }). A compound statement can be used anywhere a statement is
expected. Compound statements are commonly called “blocks.”
Multithreading
- The ability of an operating system to execute different parts of a
program, called threads, simultaneously. The programmer must carefully
design the program in such a way that all the threads can run at the same
time without interfering with each other.
Array
- An array is a group of same typed variables that are referenced by a
common name. Arrays can be any typed and one or more dimensions. A
particular element can be addressed by array name and index of the array
enclosed in third bracket ([]). Array can be declared with its initial
values or can be defined with the size and can input the values latter. An
array index start from 0 by default. int a[]={1,2,3,4};
int a[10];
new
- The new operator attempts to dynamically allocate
(at run time) one or more objects of type-name. The new operator cannot be
used to allocate a function; however, it can be used to allocate a pointer
to a function.
Preprocessor Directives
- Preprocessor directives, such as #define is typically used to make
source programs easy to change and easy to compile in different execution
environments. Directives in the source file tell the preprocessor to perform
specific actions. E.g. #define MAX 50;
Header Files
- File containing predefined compile-time constants or functions. This can
be inserted at any part of the program.
#include
- Directive tells the
preprocessor to treat the contents of a specified file as if those contents
had appeared in the source program at the point where the directive appears.
You can organize constant and macro definitions into include files and then
use #include directives to add these definitions to any source file.
Pointer
- A pointer is a data type whose value refers directly to (or “points to”)
another value stored elsewhere in the computer memory using its address. A
pointer is a simple implementation of the general reference data type.
Pointers are so commonly
used as references that sometimes people use the word “pointer” to refer to
references in general; however, more properly it only applies to data
structures whose interface explicitly allows it to be manipulated as a
memory address. E. G. – int *p, p1=10; p=&p1;
String Functions
– String functions are part of string.h
strlen(string)
– to find the length of a string value.
strcpy(string1,string2)
– Copy all contents of string2 to String1.
strcmp(string1,string2)
– Compare between two string( relevant to the ASCII values of each
character), if both equal it return 0, if String1 is smaller than String2
then it will return -1 and if String1 is bigger than String2 then it will
return 1.
strcmpi(string1,string2)-
Same as above only ignore case while checking.
strcat(string1,string2)
– Join String2 to the right of String1.
strlwr(string)/
strlupr(string)
- Converts this String to lowercase / Converts this String to
upper case.
strrev(string)
– Reverse the string.
Math.h
- Math function are from
abs(num)
- Returns the absolute value of a double value.
sqrt(num)
- Returns the square root of a double value.
pow(num,num)
- Returns of value of the first argument raised to the power of the second
argument.
sin(num)
/ cos(num) / tan(num) - Returns the
trigonometric sine, cosine and tangent of an angle.
ceil(num)
- Returns the smallest (closest to negative infinity) double value
that is not less than the argument and is equal to a mathematical integer.
Math. ceil(12.5) = 13, ceil(-12.5) = -12
floor(num)
- Returns the largest (closest to positive infinity) double value
that is not greater than the argument and is equal to a mathematical
integer. Math.floor(12.5) = 12, floor(-12.5) = -13.
conio.h
– Console input output header file having predefined function like –
clrscr()
– To clear output screen. getch() – gets a character from the
console but does not echo to the screen. getche() – gets a
character from the console and echoes to the screen.
stdio.h
– Standard input output header file having following function –
gets()
– Gets a string from stdin. puts() – print the output to the
stdout.
struct
– Groups the variables in a single record. E.g. Struct personal { char
name[20], int age;}per, per1;
personal
is struct type name and per / per1 are
structure variables, name and age are the structure elements.
Structure type and variables both are optional, but one of the two must
appear. Structure type used to create multiple copies and can not be used
directly where structure variable can be used directly like per.name.
union – A union is like a
structure, except it allows you to define variables that share storage
space.
getchar()
– Get a character from stdin. putchar() – display a character
to the stdout.
fflush()
– Flushes the input and output stream.
fopen()
– Opens a file and associate stream with it and return a pointer that
identifies the stream for the operation. fclose() – Close an
open file stream.
fwrite()–
Write specified numbers of equal sized data to a file stream. fread()
- Reads specified numbers of equal sized data from a file stream.
printf()
- Print formatted output to the standard output stream.
iostream.h –
This header file is a must used for
C++ program for some IO stream.
cout
– Output to the standard output stream like screen.
cin
- input from the standard input stream like keyboard.
fstream
- The fstream class is an iostream derivative
specialized for combined disk file input and output. Its constructors
automatically create and attach a filebuf buffer object like
f.open(), f.write(), f.close(), f.read().
this
- The keyword
this
may be used only in the body of an instance method or constructor, or in the
initializes of an instance variable of a class. If it appears anywhere else,
an error will occur.
class
test{
int a;
test(int
a) {
a=this->a;}}
Operator overloading – It is a case of polymorphism. Operator overloading
is the ability to tell the compiler how to perform a certain operation when its
corresponding operator is used on one or more variables.
We can
redefine or overload the function of most built-in operators in C++. These
operators can be overloaded globally or on a class-by-class basis. Overloaded
operators are implemented as functions and can be member functions or global
functions. An overloaded operator is called an operator function. we declare an
operator function with the keyword operator preceding the operator which we want
to overload. Overloaded operators are distinct from overloaded functions, but
like overloaded functions, they are distinguished by the number and types of
operands used with the operator.
Operator overloading is the ability to
tell the compiler how to perform a certain operation when its corresponding
operator is used on one or more variables. For example, the compiler acts
differently with regards to the subtraction operator “-“ depending on how the
operator is being used. When it is placed on the left of a numeric value such as
-48, the compiler considers the number a negative value. When used between two
integral values, such as 80-712, the compiler applies the subtraction operation.
When used between an integer and a double-precision number, such as 558-9.27,
the compiler subtracts the left number from the right number; the operation
produces a double-precision number. When the - symbol is doubled and placed on
one side of a variable, such as --Variable or Variable--, the value of the
variable needs to be decremented; in other words, the value 1 shall be
subtracted from it. All of these operations work because the subtraction
operator “-” has been reconfigured in various classes to act appropriately.
Necessary to overload an operator
We can use the operator to
perform a user define task and it can be possible by using operator overloading.
So, using the operator overloading we can execute different operation instead of
natural behaviors of that operator.
The operators that overloaded : +, -, *, /, ++, --,
=, ==, !=, >, <. >=, <=, <<, >>, [],
The name of the operators that can not be overloaded
Scope resolution operator (::)
Member selection operator (.)
Pointer to class member operator (.*)
Conditional operator (:?)
Size of operator (size of)
A program in C++ to concatenate two strings of two
different objects using operator overloading with constructor.
#include<iostream.h>
#include<string.h>
using namespace std;
class
A
{
char
p[20];
public:
A()
{
}
A(char
*x)
{
strcpy(p,x);
}
void
display()
{
cout<<p<<endl;
}
void
operator +(A &o)
{
char
a[20];
int i,j;
for(i=0;i<strlen(p);i++)
{
a[i]=*(p+i);
}
*(a+i)='
';
for(j=0,i++;j<strlen(o.p);i++,j++)
{
a[i]=*(o.p+j);
}
*(a+i)='\0';
strcpy(p,a);
}
};
int
main()
{
A
ob_1("How are you"),ob_2("I am fine");
ob_1.display();
ob_2.display();
ob_1+ob_2;
// + Operator is overloaded to concatenation two string of different object
ob_1.display();
return
0;
}
Template
: Templates are a
feature of the C++ programming language that allow functions and classes to
operate with generic types. This allows a function or class to work on many
different data types without being rewritten for each one. Templates are of
great utility to programmers in C++, especially when combined with multiple
inheritance and operator overloading. The C++ Standard Library provides many
useful functions within a framework of connected templates.
Function template and Class template
Function template
:
Function
templates are special functions that can operate with generic types. This allows
us to create a function template whose functionality can be adapted to more than
one type or class without repeating the entire code for each type. In C++ this
can be achieved using template parameters. A template parameter is a special
kind of parameter that can be used to pass a type as argument: just like regular
function parameters can be used to pass values to a function, template
parameters allow to pass also types to a function. These function templates can
use these parameters as if they were any other regular type.
The format for declaring function
templates with type parameters is:
template <class identifier>
function_declaration; template <typename identifier > function_declaration;
The only difference between both
prototypes is the use of either the keyword class or the keyword type name. Its
use is indistinct, since both expressions have exactly the same meaning and
behave exactly the same way.
Example :
template<class
t1,class t2>
void fun(t1
a,t2 b)
{
cout<<a<<”\t”<<b;
}
int main()
{
int
x=4;
float
y=5.9;
char
z='S';
fun(x,y);
fun(y,z);
fun(z,x);
return
0;
}
OUTPUT
4 5.9
5.9 S
S 4
Class template
:
A class
template definition looks like a regular class definition, except it is prefixed
by the keyword template. Using the class templates, we can implemented a class
can have members of the type template parameters.
The relationship between a class template
and an individual class is like the relationship between a classes and an
individual object. An individual class defines how a group of objects can be
constructed, while a class template defines how a group of classes can be
generated.
Example:
template<class t1>
class A
{
t1 a;
public:
A(t1 x)
{
a=x;
}
void
display()
{
cout<<a<<endl;
}
};
int main()
{
A
<int>o1(4);
A
<float>o2(8.7);
A <char>o3('F');
o1.display();
o2.display();
o3.display();
return
0;
}
OUTPUT
4
8.7
F
NOTE:
Class template
is a
template used to generate template classes. You cannot declare an object of a
class template. Template class is an instance of a class template.
Explicit function specialization in template
: With a function template, we can define
special behavior for a specific type by providing an explicit specialization
(override) of the function template for that type.
For example: template<> void
fun(double a, double b); When we instantiate a template with a given set of
template arguments the compiler generates a new definition based on those
template arguments. We can override this behavior of definition generation.
We can instead specify the definition the
compiler uses for a given set of template arguments. This is called explicit
specialization. We can explicitly specialize any of the following:
- Function or class template
- Member function of a class template
- Static data member of a class template
- Member class of a class template
- Member function template of a class template
- Member class template of a class template
Example
#include<iostream.h>
#include<string.h>
using namespace std;
template<class t1>
void fun(t1 a,t1 b)
{
cout<<endl<<"Template
Function : "<<a<<" "<<b;
}
template< >
void fun(int a,int b)
{
cout<<"Explicit
Specilization Function : "<<a<" "<<b;
}
int main()
{
int x=9,y=5;
float
p=5.6,q=8.1;
fun(x,y);
//Explicit specialization
fun(p,q); //Template
Function Called
return
0;
}
OUTPUT
Explicit Specilization Function : 9 5
Template Function : 5.6 8.1
Templates increase the code reusability
: A template provides generalize form of a
program so we need not to use separate code for the same operation with respect
to the different data type.
In the above example
template function fun can be used for display the value of two variable of the
different data type. No need to define separate function for each data type of
those variables for displaying their value. In this way using the template we
can minimize the line of code (LOC) and increases the code reusability.
Friend function:
A friend function is a
function that is not a member of a class but has access to the all class members
(public, private, protected member). Friend functions are not considered class
members; they are normal external functions that are given special access
privileges. Friend functions are called using the function name only. Friends
are not in the class's scope, and they are not called using the member-selection
operators (. and –>) unless they are members of another class. A friend
function is declared by the class that is granting access. The friend
declaration can be placed anywhere in the class declaration. It is not affected
by the access control keywords.
Friend function contradicts the concept of data hiding
: Basically uses
of friend functions are limited because friend functions have access to protect
and private members of the class for which it is a friend and so that it
violates the concept of data hiding.
Example:
#include<iostream> /*INCLUDING HEADER FILE*/
using namespace std;
class list /*CLASS
DEFINITION*/
{
int
x;
friend
void ins(list &); /*PROTOTYPE
OF FRIEND FUNCTION*/
friend
void disp(list&);
};
void ins(list &ob) /*FRIEND FUNCTION */
{
cout<<"Enter number
::";
cin>>ob.x;
}
void disp(list &ob) /* FRIEND FUNCTION */
{
cout<<"
-> "<<ob.x ;
}
int main(); /* MAIN()*/
{
list
l[5];
int
i,n,max;
cout<<"Enter
5 numbers::"<<endl<<endl;
for(i=0;i<5;i++)
{
ins(l[i]);
}
cout<<endl<<"List
::";
for(i=0;i<5;i++)
{
disp(l[i]);
}
return
0;
}
Friend Classes:
When classes functions will
have direct access to protected and private members of the class when it is
decalrte with friend keyword. While giving access to a class, one must specify
that the access is granted for a class using the class keyword:
friend
class aClass;
Example:
#include <iostream.h>
#include <conio.h>
class aclass
{
friend class bclass;
private :
int x,y;
public:
void getdata();
};
class bclass
{
public:
void disp(class aclass temp);
};
void aclass:: getdata()
{
cout<<"Enter
two nos ";
cin>>x>>y;
}
void bclass::disp(class aclass t)
{
cout<<" Sum of
"<<t.x<<" and "<<t.y<<" =
"<<t.x+t.y;
}
void main()
{
clrscr();
aclass ac;
bclass bc;
ac.getdata();
bc.disp(ac);
getch();
}
Virtual Base Class :
Virtual base classes offer a way to save space and avoid ambiguities in class
hierarchies that use multiple inheritance. Each nonvirtual object contains a
copy of the data members defined in the base class. This duplication wastes
space and requires you to specify which copy of the base class members you want
whenever you access them. When a base class is specified as a virtual base, it
can act as an indirect base more than once without duplication of its data
members. A single copy of its data members is shared by all the base classes
that use it as a virtual base. The virtual keyword appears in the base lists of
the derived classes, not the base class. When two or more objects are derived
from a common base class, we can prevent multiple copies of the base class being
present in an object derived from those objects by declaring the base class as
virtual when it is being inherited. Such a base class is known as virtual base
class. This can be achieved by preceding the base class’ name with the word
virtual.
Virtual functions:
“Virtual functions” are functions that ensure that the correct function is
called for an object, regardless of the expression used to make the function
call. A virtual function is a member function that is declared within a base
class and redefined by a derived class. To create virtual function, precede the
function’s declaration in the base class with the keyword virtual. When a class
containing virtual function is inherited, the derived class redefines the
virtual function to suit its own needs.
#include<iostream.h>
class Add
{
protected:
int a,b;
public:
Add()
{
a=1;
b=2;
}
virtual void show()
{
cout <<a<<" "<<b;
}
};
class Sum: public Add
{
int c;
public:
Sum()
{
c = 0;
}
virtual void show()
{
cout <<a+b;
}
};
int main()
{
Add *ptrAdd;
Sum objSum;
ptrAdd = &objSum;
ptrAdd->show();
return 0;
}
No comments:
Post a Comment