Professional Documents
Culture Documents
CPP Starting Notes
CPP Starting Notes
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
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
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.
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.
"!" << 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 types
Variables are of three basic types which are as follows:
1. int
2. float
3. char
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.
addition
int sum = 4 + 7
subtraction
multiplication
division
int quotient = 14 / 3
modulo ("mod")
int remainder = 10 % 6
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
result
is less than
<
true
is greater than
>
false
is equal to
==
false
<=
true
>=
false
is not equal to
!=
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
operator
name
boolean not
multiplication
division
mod
addition
subtraction
<
is less than
<=
>
is greater than
>=
==
is equal to
!=
is not equal to
&&
boolean and
||
boolean or
assignment
*=
/=
%=
+=
-=
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.
nesting.
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.
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
}
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
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
Player
Player
Player
blueHat;
redHat;
greenHat;
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.
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.
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.
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;
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++;
}
};
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.
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
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.
{
...
...
}
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.
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.
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
Inheritance Benefits
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.