MODULE1
IntroductionofC++
C++wasdevelopedbyBjarneStroustrupstartingin1979atBellLabsinMurrayHill, New
Jersey, as an enhancement to the C language and originally named C with Classes but
later it was renamed C++ in 1983.
C++ is a general-purpose, compiled, case-sensitive, object-oriented programming
language.
Itisanextensionto Cprogramming.
Applications:
Object
Class
Abstraction
Encapsulation
Inheritance
Polymorphism
Overloading
DynamicBinding
1. Object
Any entity that has state and behavior is known as an object. For example: chair, pen,
table, keyboard, bike etc. It can be physical and logical.
2. Class
Collection of objectsis called class. It is a logical [Link] object's class acts as its
blueprint.
Take the class of cars as an example. Even if different names and brands may be used
for different cars, all of them will have some characteristics in common, such as four
wheels, a speed limit, a range of miles, etc. In this case, the class of car is represented
by the wheels, the speed limitations, and the mileage.
3. Abstraction
Data abstraction refers to, providing only essential information to the outside world
and hiding their background details, i.e., to represent the needed information in
program without presenting the details.
For example, a database system hides certain details of how data is stored and created
and maintained. Similar way, C++ classes provides different methods to the outside
world without giving internal detail about those methods and data.
4. Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
5. Inheritance
When one object acquires all the properties and behaviours of parent object i.e.
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Sub class - Subclass or Derived Class refers to a class that receives properties from
another class.
Super class - The term "Base Class" or "Super Class" refers to the class from which a
subclass inherits its properties.
Reusability - As a result, when we wish to create a new class, but an existing class
already contains some of the code we need, we can generate our new class from the
old class thanks to inheritance. This allows us to utilize the fields and methods of the
pre-existing class.
6. Polymorphism
The ability to use an operator or function in different ways in other words giving
different meaning or functions to the operators or functions is called polymorphism.
[Link] isasinglefunctionoran operatorfunctioninginmanyways
different upon the usage is called polymorphism.
7. Overloading
The concept of overloading is also a branch of polymorphism. When the exiting
operator or function is made to operate on new data type, it is said to be overloaded.
8. DynamicBinding
Indynamicbinding,thecodetobeexecutedinresponse tothefunctioncallisdecided at
runtime.
Keyfeaturesof OOP:-
Emphasisondatathan algorithm
Data Hiding
MessagePassing
CodeSharing
SoftwareReuseability
Bottom upApproach
Application od C++
Gaming
GUIapplication
WebBrowser
Compiler
OS
SampleProgramInC++
#include
<iostream>usingnamesp
ace std;
//Main()function:where theexecutionof
//programbegins
intmain()
{
// Prints hello world
cout<<"HelloWorld";
return0;
}
The#includedirectivetellsthecompilerto includea file and#include<iostream>. It tells the
compiler to include the standard iostream file which contains declarations of all the
standard input/output library functions.
Anamespace in C++ is used to provide a scope or a region where we define identifiers. It
is used to avoid name conflicts between two identifiers as only unique names can be used
as identifiers.
Main Function:-Functions are basic building blocks of a C++ program that contains the
instructions for performing some specific task. Apart from the instructions present in its
body, a function definition also contains information about its return type and parameters.
The next linecout<<"Hello World";causes the message "Hello World" to be displayed on
the screen.
The next line return 0;terminates main( )function and causes it to return the value 0 tothe
calling process.
DataTypesinC++
▶C++supportsthefollowingdatatypes:
1. PrimaryorBuilt-inorFundamentaldatatype
2. Deriveddata types
3. User-defineddatatypes
PrimitiveDataTypes
• Integer: The keyword used for integer data types is int. Integers typically require 4
bytes of memory space and range from -2147483648 to 2147483647.
• Character: Character data type is used for storing characters. Characters typically
require 1 byte of memory space and range from -128 to 127 or 0 to 255.
• Boolean: Boolean data type is used for storing Boolean or logical values. ABoolean
variable can store either true or false.
• Floating Point: Floating Point data type is used for storing single-precision floating-
point values or decimal values. Float variables typically require 4 bytes of memory
space.
• Double Floating Point: Double Floating Point data type is used for storing double-
precision floating-point values or decimal values. Double variables typically require 8
bytes of memory space.
• void: Void means without any value. void data type represents a valueless entity. A
void data type is used for those function which does not return a value.
• Wide Character:Wide characterdata type is also a character data type but this data
type has a size greater than the normal 8-bit data type. Represented by wchar_t. It is
generally 2 or 4 bytes long.
• sizeof() operator:sizeof() operatoris used to find the number of bytes occupied by a
variable/data type in computer memory.
DerivedData Types
Function:Afunction is a block of code or program-segment that is defined to perform
a specific well-defined task.
Afunction is generally defined to save the user time from writing the same lines of
code again and again for the same input.
Allthe lines of code are put together inside a single function and this can be called
anywhere required. main() is a default function that is defined in every program of C+
+.
Syntax:
Function_typefunction_Name(arguments)
Array:An array is a collection of items stored at continuous memory locations. The
idea of array is to represent many instances in one variable.
Syntax:
DataTypeArray_name[size];
▶Pointers:Pointers are symbolic representation of addresses. They enable programs to
simulate call-by-reference as well as to create and manipulate dynamic datastructures.
▶Reference:When a variable is declared as reference, it becomes an alternative name for
an existing [Link] can be declared as reference by putting ‘&’in the
declaration.
User-DefinedDataTypes:
Class: It is a user-defined data type, which holds its own data members and member
functions, which can be accessed and used by creating an instanceofthat [Link] is like a
blueprint for an object.
classclassName{};
Structure: A structure is a user defined data type in C/C++. A structure creates a data type
that can be used to group items of possibly different types into a single type.
Union: LikeStructures, union is a user defined data type. In union, all members share the
same memory location.
Enumeration: Enumeration (or enum) is a user defined data type in C. It is mainly used to
assign names to integral constants, the names make a program easy to read and maintain.
Typedef: C++ allows you to define explicitly new data type names by using the keyword
typedef. Using typedef does not actually create a new data class, rather it defines a name for
an existing type. This can increase the portability(the ability of a program to be used across
different types of machines; i.e., mini, mainframe, micro, etc; without much changes into the
code)of a program as only the typedef statements would have to be changed.
Syntax:-Typedeftypename;
OperatorsinC++:
Anoperatoris asymbolthatoperatesonavalueto performspecificmathematicalorlogical
computations. They form the foundation of any programming language. In C++, we have
built-in operators to provide the required functionality.
▶OperatorsinC++canbe classifiedinto6types:
1. Arithmetic Operators
2. RelationalOperators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Ternary or Conditional Operators
C++FunctionOverloading
Function Overloading is defined as the process of having two or more function with
the same name, but different in parameters is known as function overloading in C++.
In function overloading, the function is redefined by using either different types of
arguments or a different number of arguments. It is only through these differences
compiler can differentiate between the functions.
Theadvantageof Function overloading is that it increases the readability of the
program because you don't need to use different names for the same action.
The parameters should follow any one or more than one of the following conditions
for Function overloading:
Parametersshouldhaveadifferenttype
intmyFunction(intx)
floatmyFunction(floatx)
doublemyFunction(doublex)
#include <iostream>
usingnamespacestd;
int sum(int a,int b)
{ return a + b;
}
floatsum(floata,floatb,floatc)
{
returna+b +c;
}
intmain(void){
intadd1=sum(10,20);
floatadd2=sum(5.6,2.3,2.5);
cout<<add1<<endl;
cout<<add2;
return 0;
}
InlineFunctionin C++
C++ provides inline functions to reduce the function call [Link] inline function is a
[Link] code of
the inline function gets inserted or substituted at the point of the inline function call.
This substitution is performed by the C++ compiler at compile time. An inline function
may increase efficiency if it is small.
Syntaxforan inlinefunction
inlinereturn_type function_name(parameters)
{
//functioncode?
}
Thecompilermaynotperforminlininginsuchcircumstancesas:
1. Ifafunctioncontainsaloop.(for,whileanddo-while)
2. Ifafunctioncontains staticvariables.
3. Ifafunction is recursive.
4. If a function return type is other than void, and the return statement doesn’t exist in a
function body.
5. Ifafunction contains aswitch orgotostatement.
▶Let'sunderstandthedifferencebetweenthenormalfunctionandtheinlinefunction.
Insidethemain()method,whenthefunctionfun1()iscalled,thecontrolistransferred to the
definition of the called function. The addresses from where the function is called and
the definition of the function are different. This control transfer takes a lot of time and
increases the overhead.
When the inline function is encountered, then the definition of the function is copied
to it. In this case, there is no control transfer which saves a lot of time and also
decreases the overhead.
Let'sunderstandthroughanexample. #include
<iostream>
usingnamespacestd;
inlineintadd(inta,int b)
{
return(a+b);
}
intmain(){
cout<<"Additionof'a'and 'b'is:"<<add(2,3);
return0;
}
ClassandObject
AclassinC++isa user-defineddatatypethatbindsdataandthefunctionsthat operate on the
data together in a single unit. Like other user-defined data types, it also
[Link] a new
data typethat can be treated as a built-in data type.
DefiningClassandDeclaringObjects
o Aclass isdefined inC++ usingthekeyword class followedbythenameof the
[Link] body of the class is defined inside the curly brackets and terminated
by a semicolon at the end.
Example:Asimpleclassdefinition
classbook {
//privatebydefault
chartitle[30]; //variables declaration
floatprice;
public:
voidgetdata(char[],float);//functiondeclaration
voidputdata ();
};
▶DeclaringObjects
When a class is defined, only the specification for the object is defined; no memory orstorage
is allocated. To use the data and access functions defined in the class, you need to create
objects.
Syntax:
ClassnameobjectName
Accessing data members and member functions: The data members and member
functions of the class can be accessed using the dot(‘.’) operator with the object. For
example, if the name of the object is objand you want to access the member function
with the name printName() then you will have to write [Link]().
AccessingDataMembers
The public data members are also accessed in the same way given however the private data
members are not allowed to be accessed directly by the object. Accessing a data member
[Link] byAccess
modifiers in C++. There are three access modifiers: public, private, and protected.
//C++programtodemonstrateaccessingofdatamembers #include
<iostream>
usingnamespacestd;
classA{
//Accessspecifier
public:
//DataMembers
string Firstname;
//Member Functions()
voidprintname(){cout<<“nameis:"<<Firstname;}
};
int main()
{
Aobj1; //Declareanobjectofclassgeeks
[Link] = "Abhi"; // accessing data member
[Link](); //accessingmemberfunction
return 0;
}
Scoperesolutionoperator
The scope resolution operator is used to reference the global variable or member
function that is out [Link], weusethescoperesolution operatorto access the
hidden variable or function of a program. The operator is represented as thedouble
colon (::) symbol.
For example, when the global and local variable or function has the same name in a
program, and when we call the variable, by default it only accesses the inner or local
variable without calling the global variable. In this way, it hides the global variable or
function. To overcome this situation, we use the scope resolution operator to fetch a
program's hidden variable or function.
Uses of thescoperesolution Operator
1. Itisusedtoaccessthehidden variablesormemberfunctionsofa program.
2. Itdefines themember functionoutside oftheclass usingthe scoperesolution.
3. Itisusedtoaccess thestaticvariable and staticfunctionofaclass.
4. ThescoperesolutionoperatorisusedtooverridefunctionintheInheritance.
Program to access the hidden value using the scope resolution (::) operator#include
<iostream>
usingnamespacestd;
//declareglobalvariable
intnum = 50;
intmain()
{
intnum = 100; //declarelocal variable
cout<<"Thevalueofthelocal variablenum:"<<num;
//print thevalueofthevariables
cout<<"\nThevalueoftheglobalvariablenum:"<<::num;
//usescoperesolution operator(::)toaccess theglobalvariable
return0;
}
Passingobjectsasarguments
To pass an object as an argument we write the object name as the argument while calling the
function the same way we do it for other variables.
classstudent
{
private:
int marks;
inttotalmarks=0; public:
void enter marks()
{ cout<<"entermarks
"; cin>>marks;}
voidaddmarks(studentm1,studentm2){
totalmarks=[Link]+[Link];
}
voiddisplaymarks(){
cout<<totalmarks;}
};
int main(){
students1,s2,s3;
[Link]();
[Link]();
[Link](s1,s2);
[Link]();
return 0;
}
ReturnObjectfromaFunction
Afunction can also return objects either by value or by reference. When an object is returned by
value from a function, a temporary object is created within the function, which holds the
return value. This value is further assigned to another object in the calling function.
Example:
#include<iostream>usin
gnamespacestd; class
student
{
private:
intmarks;
inttotalmarks=0; public:
void entermarks()
{cout<<"entermarks";
cin>>marks;
}
studentaddmarks(studentm1)
{ student m3;
[Link]=marks+[Link]; return
m3;
}
void displaymarks();
};
voidstudent::displaymarks()
{
cout<<totalmarks;} int
main(){
student s1,s2,s3;
[Link]();
[Link]();
s3=[Link](s2);
[Link]();
return 0;
}
ObjectAssignment
If both objects are of the same type (that is, both are objects of the same class),
thenone object may be assigned to another.
By default, when one object is assigned to another, a bitwise copy of the first object's
data is copied to the second.
Thefollowingprogramdemonstratesobjectassignment:
Example:
#include <iostream>
usingnamespacestd;
class myclass{
inta,b;
public:
voidsetab(inti,int j)
{a=i, b = j;
}
void showab();
};
void myclass::showab()
{cout<<"ais"<<a<<"\n"; cout<<"b
is "<< b <<" \n ";
}
int main()
{ myclassob1,ob2;
[Link](10,20);
[Link](0,0);
cout<<"ob1beforeassignment:"<<"\n";
[Link]();
cout<<"ob2beforeassignment:"<<"\n";
[Link]();
cout<<"\n";
ob2 = ob1; //assignob1toob2
cout<<"ob1 after assignment: "<<"\n";
[Link]();
cout<<"ob2afterassignment:"<<"\n"; [Link]();
return0;}