You are on page 1of 31

Start programming in C++.

C++ is an extension of the C Programming Language. C Programming


language was been developed in the Bells Labs in the year 1969-
1973. UNIX Operating system was also been developed at the same
time.

In the year 1983 Bjarne Stroustrup created the C++ in the Bells
Labs.

Brief History
C++ is an extension of the C Programming Language. C Programming
language was been developed in the Bells Labs in the year 1969-1973.
UNIX Operating system was also been developed at the same time.
Bjarne Stroustrup created the C++ during the year 1983 in the Bells
Labs. It was designed for the UNIX environment. It also represents the C
programming enhancement and makes programmers to improve the
quality of code that has been produced, This makes the code which can
be reused easier to write

Why to Program in C++?


C++ is not a best language to use for every instances. It is of great
choice to use in most instances. But this is not the case always, Some
circumstances would need other languages that best suits them.
Here are the major advantages of using C++ programming:
 C++ allows expression of abstract ideas.

C++ is a 3rd Generation Language. The ideas of the programmer are


been expressed in a high level language compared to assembly level
programming language. A C++ is third generation language which allows
the programmer to express their ideas at high level as compared to the
assembly languages.

 C++ allows programmer to keep low-level control.

Though C++ is a 3rd Generation Language it do contains some feel of a


Assembly level Programming language. It makes it possible to get down
into a low-level programming language for the programmers and also
tunes as needed. There is a strict control over the memory management
for a C++ programmer.

 C++ have national standards (ANSI).

C++ is national standards language. A C++ code written which confirms


to national standards can be easily integrated with the existing code. This
will also allow the programmer to reuse common libraries. So these
common functions need not be written more than once. An dalso note
that these functions will behave uniquely wherever they are used.

 C++, a reusable and object-oriented language

Since C++ is an object oriented language, it will make coceptually


programming easier. If the object paradigm is learned once, it will allow
reuse of code, or part of it through inheritance.

 The C++ is widely been used and taught

Because of this, C++ is a very widely used programming language. there


are many tools which are available for the C++ programming, and there
is broad base of the programmers contributing to C++ "community".

Inheritance
Generally speaking, objects are been defined in terms of the classes. We
know lot about object by knowing about its class. Even if you do not know
what the penny-farthing is, if I tell you it was bicycle, you would
definately know that it has two wheels, handle bars and the pedals.
The Object-oriented systems will take this step further and will allow the
classes to be defined in terms of the other classes. For an example, a
mountain bikes, race bikes and the tandems are all a different kind of the
bicycles. In an object-oriented terminology, the mountain bikes, the race
bikes and the tandems are all subclasses of a bicycle class. Similarly,
bicycle class is a superclass of the mountain bikes, race bikes and the
tandems.

Inheritance Benefits
• Subclasses provides the specialized behaviours from a basis of the
common elements provided by a superclass. Through use of the
inheritance, programmers can reuse a code in superclass many
times.

• Programmers can implement the superclasses that will define the


"generic" behaviours (called the abstract classes). Essence of
superclass is defined and can be partially be implemented but much
of the class is been left undefined and also unimplemented. Other
programmers fill in details with the specialized subclasses.

Multiple inheritances
A subclass having more than one superclass is called Multiple
inheritances. This will enables a subclass to inherit the properties of more
than one super class and to combine all these properties.

Polymorphism
Different types of objects which respond distinctively to same message is
called Polymorphism, example, when we do send same message, ‘cost’ to
the spike-bicycle object, a mono-cycle object and the tandem bicycle
object, each of these object will respond appropriately. All these cycles of
a class bicycle have their own individual price.

Data abstraction
Public interface, formed by a collections of messages understood by the
object, will define how to use this object. The programs which wants to
manipulate the object, will only have to be concerned about messages
this object will understand, and need not worry about how the tasks are
achieved nor internal structure of an object. Hiding up of the internal
details makes the object abstract, and a technique is normally known as
the data abstraction.

Encapsulation
Packing up an object's variables within its methods is called
encapsulation. Encapsulating the related variables and methods into neat
software bundle seems simple but is a powerful idea that provides two
benefits to the software developer:
• Modular programming-- The source code for any of the object can
be written and maintained independently from those of the source
code written for other objects. Also, an object can be easily used
passing around in the system. For example you can give your
bicycle to someone else and it will still work for them too.

• Information hiding-- An object has a public interface by which other


objects can communicate with it. But on the other hand objects can
maintain private information and methods that cannot be
communicated to others.

Structure of C++ program


Before going deep into the C++ language details, let us get started with
full-fledged C++ program! Idea of this program is to introduce the overall
structure of C++ program and give you flavor of the C++.

//include this file for cout


#include <iostream.h>

int main()
{
//print out the text string, "Hello, World!"
cout << "Hello, World!" << endl;

return 0;
}

To prepare next section, create a new text file and save this code into the
file. If you are using unix machine, save a file with a filename hello.C (.C
is a file extension). If you using Windows machine, save file with a
filename hello.cpp.

Brief Explanation of the program "Hello, Dave"


Let us look at each line of the code which makes the hello.C.
//include this file for cout This is a comment line. "//" indicates that
everything that follows this symbol should be ignored by compiler. This
allows to add some explanatory note, which might otherwise be confusing
code. You have a freedom to comment the code as you like -- some
programmers will not use any comments; others do write multi line
comments for C++ code. It is up to you. But one should add comments.
It is good way of writing the code, because programmers often do not
understand the code they have written a week ago!
#include <iostream.h> The line is read as "pound include i-o-stream
dot h". Effect of this line is it will just "copy and paste" entire file
iostream.h into the file at this line. It is like the syntax as replacing a line
#include <iostream.h> by the contents of a file iostream.h. "#include" is
known as the preprocessor directive,
int main() { Every program in C++ should have what is known as the
main function. When you run a program, program will go through every
line of the code in main function and will execute it. If the main function
is empty, then the program will do nothing.
//print out text string, "Hello, World!" This is a comment line which
the compiler ignores anything following the "//" (till the end of a line), By
commenting we can say whatever we want on these lines.
cout << "Hello, World!" << endl; This is a line which will print the text
string, "Hello, World!". For now, do not worry about the working of the
cout just try to know how to use it. You can print out any series of the
text strings by separating them by <<. So, instead of saying it cout <<
"Hello, World!" << endl;, you could say cout << "Hello, " << "World" <<
"!" << endl;. The statement endl simply adds the carriage return (the
stands for the "end-line").
return 0; Since the return type of main is int This line of code is
necessary. Let us see about the functions and the return types later, for
now understand that the function's return type is an integer type, the
function should return an int. return 0; will simply returns 0.

What is Variable?
Variable is the place to store the piece of information. As one might store
the friend's phone number in own memory, we can store this information
in the computer's memory. These are the means of accessing the
computer's memory.
There are fairly strict rules on how the variables are named which C++
imposes:
• Variable names should start with the letter.
• The variable names are case-sensitive (i.e., variable "myNumber" is
different from "MYNUMBER" which inturn is different from
"mYnUmBeR").
• Variable names cannot have blank spaces in between.

• A variable names cannot have the special characters.

Variable types
Variables are of three basic types which are as follows:

1. int
2. float

3. char

Declaring the Variables


Variable type is nothing but a description of the kind of the information a
variable will store. Declaring the variable in C++ is simple. Let us say that
we want to declare the variable of type int called "myAge". That is to say,
Variable myAge will store the integer, Variable myName will store an
character, Variable myHeight will store float value. In C++, this is written
as shown below:

int myAge;

char myName;

float myHeight;

How to Type Cast the Variable?


In C++ Casting is easy. Let us say that we have used a float variable
storing the number like "26.3141885", and we want to have the int
storing an integer portion instead of the float. This is done as shown
below:
int GetAverage()
{

// assume that regularAvg and specialAvg store two floats


float totalAvg = regularAvg + specialAvg;

// cast totalAvg to an int


int truncatedAvg = (int) totalAvg;

// return the truncated value


return truncatedAvg;
}

The key part to notice here is the line of code which reads int
truncatedAvg = (int) totalAvg. What we are doing here is taking the float,
totalAverage, that stores some kind of the decimal number (say
82.41832), and getting rid of ".41832" part by casting it to the int. This
works since int is the only capable of storing the integers, so it simply
stores an integer portion of the totalAvg.

Boolean Operators
and: && operator

//suppose that San is tired


bool sanIsTired = true;

//but San doesn't have to wake up early


bool sanMustWakeUpEarly = false;

//will San go to sleep now?


bool bedTime = sanIsTired && sanMustWakeUpEarly;

What will this chunk of the code do? It initializes the variables, sanIsTired
to true and sanMustWakeUpEarly to false, The third line of code
(comments not included), we determine that San is going to sleep if and
only if "and" operation is true -- that is, if both the inputs to "and"
operation are true. In this case, first input is true and second input is
false. Since the "and" requires both inputs to be true in order for output
to be true, but one of an inputs is false, output will become false. So,
variable bedTime will store a false value.
not: !
"not" operator is used by placing symbol "!", before the boolean value.

//suppose that Julie stayed up late


bool julieStayedUpLate = true;

//will Julie be peppy tomorrow?


bool julieIsPeppy = !julieStayedUpLate;

This code illustrates the "not" operation. At the end of the code, variable
julieIsPeppy will take an opposite value of julieStayedUpLate. If
julieStayedUpLate were false, then the variable julianIsPeppy would be
true. In this case, opposite is true, so the julieIsPeppy gets the value
false.

The Arithmetic Operators


In addition to boolean operators, C++ has many arithmetic operators.
They are listed below:

name symbol sample usage


addition + int sum = 4 + 7

subtraction - float difference = 18.55 - 14.21

multiplication * float product = 5 * 3.5

division / int quotient = 14 / 3

modulo ("mod") % int remainder = 10 % 6

These operators probably look familiar with an exception of mod (%)


operator. Mod is simply a remainder produced by dividing the two
integers. In example shown in the table above, if we treat a 10 / 6 as the
integer divison, quotient is 1 (rather than being 1.666) and remainder is
4. Hence, a variable remainder will get a value 4.

Equality Operators
An equality operator is used to tests the condition like "is less than", "is
greater than", and "is equal to". it is useful to to compare two numbers
using the expressions like "x<y".

name symbol sample usage result


is less than < bool result = (4 < 7) true
is greater than > bool result = (3.1 > 3.1) false
is equal to == bool result = (11 == 8) false
is less than or equal to <= bool result = (41.1 <= 42) true
is greater than or equal to >= bool result = (41.1 >= 42) false
is not equal to != bool result = (12 != 12) false

Once using the equality operator is known,it is easy to use all the others.
They all will work in the same way: they take an expressions on the
either side of them, and will either returns true or false.

The Assignment Operators


In case of an assignment operators return value is simply the value which
is stored in a variable on the left-hand-side.

int x;
int y;
x = 5;
y = 9;
cout << "The value of 'x' is "<< x << endl;
cout << "The value of 'y' is " << y << endl;
int sum;
sum = x + y;
cout << "The sum of 'x' and 'y' is " << sum << endl;

This block of code shows why one might want to throw the return value of
the operator. Look at third line, x = 5. We are using an assignment
operator here to place a value 5 in a variable x. Since the expression x =
5 returns the value, and we are not been using it, then you can say we
are ignoring a return value.

What is an Operator Precedence?


An Operator precedence refers to a order in which the operators are
resolved. An operator with a high precedence will be used before the
operator with the lower precedence. Here is an example: operators have
same precedence as the other operators in their group, and have the
higher precedence than the operators in the lower groups.
operator name
! boolean not
* multiplication
/ division
% mod
+ addition
- subtraction
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
&& boolean and
|| boolean or
= assignment
*= multiply and assign
/= divide and assign
%= mod and assign
+= add and assign
-= subtract and assign

What is the Control Statement?


Control Statement are the ways for programmer to control which pieces
of the program to be executed at certain times. The syntax of the Control
statements are very similar to the regular english, and they are very
similar to the choices that we do make in our every day life. There exists
two basic types of the control statements: branching statements and
loops.

A branching statement
A branching statement is one which divides the code into certain number
of branches depending upon some coditions specified. Example for
branching statement is the If statement.

if (x > 0)
cout<<x is positive integer;
else
cout<<x is negitive integer;

Depending on the condition certain series of events will be executed.


Another example for branching statement is a switch statement. Let us
study switch statement later. Here in the code given above will checks the
condition if x is greater than "0" or not. if it is greater then prints x is a
positive number otherwise prints x is a negitive number.

Nested control statements


Here in the nested control statements, statements are nested by using
the keyword If and Else

if (x>0)
cout<<x is positive integer;
else
if (x<0)
cout<<x is negitive integer;
else
cout<<x is Zero;

In the example given above there is one control statement which is inside
another control statement. This method of writing program is known as
nesting.

The While Statement


In this statement while keyword is been used, It checks the conditions, if
it holds good then block of code is executed. Otherwise the next
sequential line of code is been executed.

while (x< 0)
cout<<x is positive integer;
end while;
x=0;

Here if x is greater than "0" then it prints x is positive integer otherwise it


simply assigns zero to x.

The for command.


This is the loop statement. A line of code or the block of code is been
executed for certain number of times as specified in the for statement.
There are three parameters in the for statement. First intialization,
second condition and finally increement statement.

for(i=0;i<5;i++)
cout<<i;

A for statement execute a code for specified number of times. In this


instance it executes 5 times. It executes until the condition "i<5" fails.

The switch statement


A switch statement allows the programmer to compound the group of if
statements, provided that a condition being tested is integer. A switch
statement is of the form shown below:

switch(integer_val)
{
case val_1:
// code to execute if integer_val is val_1
break;
...
case val_n:
// code to execute if integer_val is val_n
break;
default:
// code to execute if integer_val is none of the above
}

Default clause is kept optional, but is a good programming practice to


include it. A default clause is been executed if none of other clauses are
executed.

What is Function?
A functions allows to group the series of steps under single name. Basic
form of the function definition is as follows:

output function_name (input_1, input_2, input_3, input_...)


{
// code to execute inside function
}

It is called the function definition as we are defining function. We say that


This is a function called function_name, with the inputs input_1, input_2,
etc., and whose output is the output. When this function is called,
function will execute a block of code in between the curly braces "{" and
"}".
Here is the syntax for the function.

return_type function_name (parameter_1, parameter_2, parameter_3,


parameter_...)
{
// code to execute inside function
}
Notice in the place of output, function definition says the return_type.
That is because when we actually are writing the function definition, we
will put an return type there, immediately preceding name of a function.
Return type is nothing but a plain old variable type, such as the int, or
double, etc.
Similarly the parameters use the variable types too. If first input to the
function is the int, then first parameter will be something like int
myNumber.

When the function is written in C++?


A function will written when there is need to execute certain block of code
more than once, or may even just to separate certain block of code from
rest of the code. For example, to convert the degrees Celsius to the
degrees Fahrenheit we have the following function:

//Sample code for functions in C++


float CtoF(float val)
{
return val *= 1.8 += 32;
}
?
float FtoC(float val)
{
return (val -= 32) /= 1.8;
}
?
int main()
{
float temperature = float();
?
//temperature now is 0, temperature == 0

temperature = 37.5;
?
CtoF(temperature);
?
//temperature is still equal to 37.5
?
temperature = 0;
?
FtoC(temperature);
?
//temperature is still equal to 0
?
CtoF(temperature);
?
//temperature == 0
}

Declaring the Class


To write a code for Class, we need to do is simply declare all the member
data and the member functions, and then wrap them up inside an object
declaration. Here is an exaple of a class called player.

class Player
{
int health;
int strength;
int agility;

void move();
void attackMonster();
void getTreasure();
};

This is a valid, working class declaration for a Player object. All we did is
declared the member data (variables for the player object) and the
member functions (functions which our object can do use), and then
enclosed them inside the class declaration block. A class declaration block
do consists of a keyword class, followed by name of an object, in this case
the class name is Player, pair of braces, and the semi-colon.

A Member Data
A class player can have attributes like health,strength, ability etc. These
attributes of a class are called memeber data. These can be either
private, public or protected Private members are those which can only be
accessed by the member funtions where as the Public members can be
accessed by any functions in the program.

A Member Function
Player object can have the behavours like Move, AttackMonster and
GetTreasure. Till now we mentioned what a player can do and not how
the Player can execute these functions. We need to write the function
body for each of the function, so that a Player instance will come to know
how to attack the monster, Here is a syntax for writing the function
definition for the member function:

void Player::move()
{
//function body goes here
}

It is almost similar to writing the function definition for the plain-old,


stand-alone functions. Only difference here is that we do precede the
name of a function, with the object name here move(), with the Player
object, and a scope resolution operator :: which tells a compiler that this
function is the part of the Player class.

Instantiating an Object
Creating an object is similar to creating a simple variable. Let us say
assume that we want four players in the game, each of them trying to
find their way to end of the maze faster than the other player. This can be
done by creating four instances of Player object as shown below.

Player blueHat;
Player redHat;
Player greenHat;
Player yellowHat;

Though all these objects are Players, they are independent from one
another. They are created by a same template, but they do have some
different attributes. Take for example, "blueHat" may be a slow and
strong player, while a "greenHat" may be quick but weak, and an
"yellowHat" may be well balanced individual, etc. Things which will make
these objects similar is they all should have the values for a strength,
health, and the ability. but they all are different as each of them can each
have their own values for these attributes. So an object is intantiated or
created by prefixing a class name to the object name as shown above.

Using the Object's Mmember Functions


Once the object is been created it is time to know how to use the object.
Using the object means using up an member data and member funtions
of an object. Suppose we have an object greenHat. The behaviour
(method) attackMonster can be accessed as shown below. The memeber
funtion is accessed using the dot operator.

greenHat.attackMonster();

Objects
Object is a component of the program which knows how to carry out
some actions and interact with other pieces of a code. Functions which
previously have been described as the "black boxes" takes the input and
spit out the output. An objects can be thought as a "smart" black boxes.
which know how to do more than one specific action, and also they can
store own set of data. Designing the program with an object allows the
programmer to model a program after a real world.

Player Object:
data:
health
strength
ability
actions:
move
attack monster
get treasure
END;

Here is a "Player" object. This object have attributes healthh, strength


and ability. These attributes in terms of Programming language are called
as data members. The various actions that a player oject can perform are
move, attakMonster and getTreasure, These actions are called memeber
Functions.

Objects and the Instances


There is a distinction between object and the instance of an object. Object
is the definition or a template for its instances. And instance is the actual
thing which can be manipulated. For example we have one instance of the
player object with certain values:

Player Instance #1:


data:
health = 16
strength = 12
ability = 14
END;

Here is one instace of the object "Player" with the values for health,
strength and ability as 16, 12 and 14 respectively.

Constructors
Objects need to initialize the variables or assign the dynamic memory to
them during their creation to become operative and to avoid the returning
unexpected values during execution.
To avoid this, a class can include special function "constructor", which is
been automatically called when the new object of the class is created. The
constructor function should have same name as that of the class, and
cannot have the return type not even the void.
Here we have implemented the CRectangle class including the
constructor:

// example: class constructor


#include <iostream>
using namespace std;

class CRectangle
{
int width, height;
public:
CRectangle (int,int);
int area ()
{
return
(width*height);
}
};

CRectangle::CRectangle (int a, int b)


{
width = a;
height = b;
}
int main ()
{
CRectangle rect (3,4);
CRectangle rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}

Here the constructor initializes the values of x and y with parameters


which are passed to it.

The Arguments to Constructor


Look at the way in which arguments are passed to constructor, they are
passed at the moment the objects of the class are created:

CRectangle rect (3,4);


CRectangle rectb (5,6);

As regular member functions, Constructors cannot be called explicitly


They are executed only when the new object of the class is been created.
There is neither prototype nor constructor declaration been done and
neither includes return value; nor void.

Destructors
A destructor fulfills opposite functionality. This is automatically been
called when the object is been destroyed, because the scope of existence
has finished off or due the reason that it is object which is dynamically
assigned and it is released using delete operator.
A destructor should have same name as that of class, but prefixed with
tilde sign (~) and it should not return any value. Use of the destructors is
suitable especially when the object assigns the dynamic memory during
lifetime and at the moment the object is destroyed we want to free the
memory which was allocated to the object.

// example on constructors and destructors


#include <iostream>
using namespace std;

class CRectangle
{
int *width, *height;
public:
CRectangle (int,int);
~CRectangle ();
int area ()
{
return (*width * *height);
}
};

CRectangle::CRectangle (int a, int b)


{
width = new int;
height = new int;
*width = a;
*height = b;
}

CRectangle::~CRectangle ()
{
delete width;
delete height;
}

int main ()
{
CRectangle rect (3,4), rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}

Class Pointers
Perfectly it is valid to create the pointers which point to the classes.
Simply we have to consider, after declaration, a class will become valid
type, so we can make use of the class name as a type for pointer. Take
for example:
CRectangle * prect;

This is the pointer to object of the class CRectangle. As with data


structures, in order to refer to member of an object pointed by the
pointer directly, we can use an arrow operator (->) of the indirection.
Consider the following example.

// pointer to classes example


#include <iostream>
using namespace std;

class CRectangle
{
int width, height;
public:
void set_values (int, int);
int area (void)
{
return (width * height);
}
};

void CRectangle::set_values (int a, int b)


{
width = a;
height = b;
}

int main ()
{
CRectangle a, *b, *c;
CRectangle * d = new CRectangle[2];
b= new CRectangle;
c= &a;
a.set_values (1,2);
b->set_values (3,4);
d->set_values (5,6);
d[1].set_values (7,8);
cout << "a area: " << a.area() << endl;
cout << "*b area: " << b->area() << endl;
cout << "*c area: " << c->area() << endl;
cout << "d[0] area: " << d[0].area()<< endl;
cout << "d[1] area: " << d[1].area() << endl;
return 0;
}
Overloading
Overloading in C++ advocates simplicity in usage and the readability.
Therefore all forms of the operators are overloaded to give a natural and
the domain oriented meanings. An increment operator "++" can be called
in two different forms as the post fix and the pre fix operator.
Programmers do have some difficulty in overloading or using it, as they
dont know how to differentiate between them. That is why the postfix
operators are been created with the dummy parameter of a integer type.
Prefix operator "++" can be overloaded like the postfix operator without
making any change. Look at the following function definition.

Class Test
{
int i;
public:
void operator ++()
{
++i;
}
};

The post fix ++ operator will be overloaded with a dummy integer


parameter as follows.
Class Test
{
int i;
public:
void operator ++(int)
{
i++;
}
};

Overloading a "+" operator


Except "?" all operators can be overloaded like ":" , "sizeof", "::", "*" .
Now let us see the example of using "+" operator.

//C++ overloading sample

class MyString
{
public:
char member1[100];
void operator +(MyString val)
{
strcat(member1, val.member1);
}
};

Friend Function
The data taht is declared as private inside the class cannot be accessed
from outside a class. The function which is not the member function or
the class which is external can never access these private data. But there
may also be some of the cases, where the programmer needs access to
private data, either from the non-member functions and the external
classes. C++ will offer some of the exceptions in these cases.
• Once the non-member function is been declared as friend, it can
get access to the private data of a class.

• similarly when the class is been declared as friend, friend class can
have the access to private data of a class which made this as a
friend

#include <iostream.h>
//Declaration of the function to be made as friend for the C++ Tutorial
sample
int AddToFriend(int x);

class CPP_Tutorial
{
int private_data;
friend int AddToFriend(int x);
public:
CPP_Tutorial()
{
private_data = 5;
}
};
int AddToFriend(int x)
{
CPP_Tutorial var1;
return var1.private_data + x;
}
int main()
{
cout << "Added Result for this C++ tutorial: "<<
AddToFriend(4)<<endl; }

A Friend Class:
Declaring a friend class is also same, The only different thing is class
definition is bit different.

#include < iostream.h >

class CPP_Tutorial
{
int private_data;
friend class friendclass;
public:
CPP_Tutorial()
{
private_data = 5;
}
};

class friendclass
{
public:
int subtractfrom(int x)
{
CPP_Tutorial var2;
return var2.private_data - x;
}
};

int main()
{
friendclass var3;
cout << "Added Result for this C++ tutorial: "<<
var3.subtractfrom(2)
}

Virtual Function
Virtual function is a function which is a member of a class, the
functionality of which can be over-ridden in the derived classes. It is
declared as a virtual in the base class using the keyword virtual. Virtual
nature is been inherited in the subsequent derived classes and there is no
need to re-state virtual keyword. Whole function body can be replaced by
the new set of implementation in a derived class. The code given below
shows how virtual function in C++ can be used to achieve the dynamic or
the runtime polymorphism.

#include <iostream.h>

class base
{
public:
virtual void display()
{
cout<<”\nBase”;
}
};

class derived : public base


{
public:
void display()
{
cout<<”\nDerived”;
}
};

void main()
{
base *ptr = new derived();
ptr->display();
}

In the example above, pointer is of the type base but it points to derived
class object. A display() method is virtual in the nature. Therefore to
resolve a virtual method call, context of a pointer is been considered,
Which means that a display method of derived class is been called and
not the base class. If a method was non virtual in nature, a display()
method of base class might have been called up.

Concept of Handling Exception


The concept of exception handling is very simple. The basic idea is simply
to raise an error flag when something goes wrong. Next, there is a
system which always lookout for these error flag. finally, previous system
calls an error handling code if a error flag is spotted.
Program Flow Raising an imaginary error flag is called throwing up an
error. When the error is been thrown overall system will respond by
catching an error. Surrounding the block of the error-sensitive code with
an exception handling is called trying to execute the block of code.
The most powerful features of the exception handling is, an error can be
thrown over the function boundaries. Means that if one of a deepest
functions on a stack has error, this can be propagate to a upper function
if there is the trying-block of a code there. This will allow the
programmers to put an error handling code in a place, like the main-
function of the program.

C++ exception handling


Designers of the C++ programming language, extended the language
with the exception handling structures. Commands which are used relate
closely to the terms used in the exception handling (as described above).
Block of code which you want to try out starts by specifying a "try"
command and surrounding a block with the curly braces. Inside this
block, you are allowed to throw the occurring errors with a "throw"
command. You should specify the error and this must be a class. After a
try-block is been closed, a catch-block will start. This is illustrated in the
code below.
try
{
...
...
throw Exception()
...
...
}
catch( Exception e )
{
...
...
}

Here the exception is the defined class with the constructor with no
parameters been passed. It will be useful to have the info on what type of
error has occurred. This can be done by two methods. Either can define
the different exception-classes and then throw them according to the
error been occurred. Or can give a class parameter containing error
message and allow a class to display the message.

Exception Handling System


A class which we are about to design should have to store the information
about an error which occurred and a class should be able to display the
error message. Following code shows this functionality.

class CException
{
public:
char* message;
CException( char* m ) {
message = m
};
Report();
}

Template functions
The C++ Function templates are the functions that can handle a different
data types without any separate code for all of the datatypes. For the
similar operation on the several kinds of the data types, the programmer
may need not write the different versions by function overloading. C++
template based function is enough, it will take care of all data types.
Let us cosider a small example for the Add function. If requirement is to
use the Add function to both types that is an integer and float type, then
the two functions needs to be created for each data type.

int Add(int a,int b)


{
return a+b;
}
// function Without C++ template
float Add(float a, float b)
{
return a+b;
}
// function Without C++ template

If the data types are more than two then it is difficult to be handled,
Because those many number of functions are to be added.
If we make use of the c++ function template, whole process will be
reduced to the single c++ function template. Here is the code fragment
for the Add function.

template <class T>


T Add(T a, T b)
//C++ function template sample
{
return a+b;
}

The Class Templates


A C++ Class Templates are been used where we have the multiple copies
of the code for the different data types having the same logic. If the set
of functions or the classes have a same functionality for the different data
types, they will become the good candidates being written as the
Templates.
A C++ class template declaration must starts with the keyword
"template". The parameter must be included inside the angular brackets.
Parameter inside a angular brackets, can either be the keyword class or
the typename. This is then followed by a class body declaration with a
member data and the member functions. Following code is the declaration
for the sample Queue class.

//Sample code snippet for C++ Class Template


template <typename T>
class MyQueue
{
std::vector data;
public:
void Add(T const &d);
void Remove();
void Print();
};

What is C++?
C++ is an extension of the C Programming Language. C Programming
language was been developed in the Bells Labs in the year 1969-1973.
UNIX Operating system was also been developed at the same time.
Bjarne Stroustrup created the C++ during the year 1983 in the Bells
Labs. It was designed for the UNIX environment. It also represents the C
programming enhancement and makes programmers to improve the
quality of code that has been produced, This makes the code which can
be reused easier to write

What is Inheritance?
Generally speaking, objects are been defined in terms of the classes. We
know lot about object by knowing about its class. Even if you do not know
what the penny-farthing is, if I tell you it was bicycle, you would
definately know that it has two wheels, handle bars and the pedals.
The Object-oriented systems will take this step further and will allow the
classes to be defined in terms of the other classes. For an example, a
mountain bikes, race bikes and the tandems are all a different kind of the
bicycles. In an object-oriented terminology, the mountain bikes, the race
bikes and the tandems are all subclasses of a bicycle class. Similarly,
bicycle class is a superclass of the mountain bikes, race bikes and the
tandems.
Inheritance Benefits
• Subclasses provides the specialized behaviours from a basis of the
common elements provided by a superclass. Through use of the
inheritance, programmers can reuse a code in superclass many
times.

• Programmers can implement the superclasses that will define the


"generic" behaviours (called the abstract classes). Essence of
superclass is defined and can be partially be implemented but much
of the class is been left undefined and also unimplemented. Other
programmers fill in details with the specialized subclasses.

What is Multiple Inheritances?


A subclass having more than one superclass is called Multiple
inheritances. This will enables a subclass to inherit the properties of more
than one super class and to combine all these properties.

What is Polymorphism?
Different types of objects which respond distinctively to same message is
called Polymorphism, example, when we do send same message, ‘cost’ to
the spike-bicycle object, a mono-cycle object and the tandem bicycle
object, each of these object will respond appropriately. All these cycles of
a class bicycle have their own individual price.

What is Data Abstraction?


Public interface, formed by a collections of messages understood by the
object, will define how to use this object. The programs which wants to
manipulate the object, will only have to be concerned about messages
this object will understand, and need not worry about how the tasks are
achieved nor internal structure of an object. Hiding up of the internal
details makes the object abstract, and a technique is normally known as
the data abstraction.

What is Encapsulation?
Packing up an object's variables within its methods is called
encapsulation. Encapsulating the related variables and methods into neat
software bundle seems simple but is a powerful idea that provides two
benefits to the software developer.

You might also like