Professional Documents
Culture Documents
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
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.
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.
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.
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.
Variable types
Variables are of three basic types which are as follows:
1. int
2. float
3. char
int myAge;
char myName;
float myHeight;
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
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.
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.
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".
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.
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.
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;
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.
while (x< 0)
cout<<x is positive integer;
end while;
x=0;
for(i=0;i<5;i++)
cout<<i;
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
}
What is Function?
A functions allows to group the series of steps under single name. Basic
form of the function definition is as follows:
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
}
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
}
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.
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 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:
class CRectangle
{
int width, height;
public:
CRectangle (int,int);
int area ()
{
return
(width*height);
}
};
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.
class CRectangle
{
int *width, *height;
public:
CRectangle (int,int);
~CRectangle ();
int area ()
{
return (*width * *height);
}
};
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;
class CRectangle
{
int width, height;
public:
void set_values (int, int);
int area (void)
{
return (width * height);
}
};
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;
}
};
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.
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”;
}
};
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.
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.
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.
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.
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.
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 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.