MODULE 1
Introduction of C++
• C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill,
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.
• It is an extension to C programming .
➢ Applications:
• Object
• Class
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Overloading
• Dynamic Binding
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 objects is called class. It is a logical entity.An 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.
Poly refers to many. That is a single function or an operator functioning in many ways
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. Dynamic Binding
In dynamic binding, the code to be executed in response to the function call is decided
at runtime.
➢ Key features of OOP:-
• Emphasis on data than algorithm
• Data Hiding
• Message Passing
• Code Sharing
• Software Reuseability
• Bottom up Approach
➢ Application od C++
• Gaming
• GUI application
• Web Browser
• Compiler
• OS
➢ Sample Program In C++
#include <iostream>
usingnamespace std;
// Main() function: where the execution of
// program begins
intmain()
{
// Prints hello world
cout<< "Hello World";
return 0;
}
• The #include directive tells the compiler to include a 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.
• A namespace 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 line cout<< "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 to
the calling process.
➢ Data Types in C++
C++ supports the following data types:
1. Primary or Built-in or Fundamental data type
2. Derived data types
3. User-defined data types
❑ Primitive Data Types
• 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. A Boolean
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 character data 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() operator is used to find the number of bytes occupied by a
variable/data type in computer memory.
❑ Derived Data Types
➢ Function: A function is a block of code or program-segment that is defined to perform
a specific well-defined task.
▪ A function is generally defined to save the user time from writing the same lines of
code again and again for the same input.
▪ All the 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 data
structures.
Reference: When a variable is declared as reference, it becomes an alternative name
for an existing variable. A variable can be declared as reference by putting ‘&’ in the
declaration.
❑ User-Defined DataTypes:
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 instance of that class. A class is like
a blueprint for an object.
class className{};
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: Like Structures, 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:- Typedef type name;
➢ Operators in C++ :
An operator is a symbol that operates on a value to perform specific mathematical or logical
computations. They form the foundation of any programming language. In C++, we have
built-in operators to provide the required functionality.
Operators in C++ can be classified into 6 types:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Ternary or Conditional Operators
C++ Function Overloading
• 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.
• The advantage of 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:
• Parameters should have a different type
• int myFunction(int x)
• float myFunction(float x)
• double myFunction(double x)
#include <iostream>
using namespace std;
int sum(int a,int b){
return a + b;
}
float sum(float a, float b, float c)
{
return a + b + c;
}
int main(void) {
int add1= sum(10,20);
float add2= sum(5.6,2.3,2.5);
cout<<add1<<endl;
cout<<add2;
return 0;
}
➢ Inline Function in C++
▪ C++ provides inline functions to reduce the function call overhead. An inline function is a
function that is expanded in line when it is called. When the inline function is called whole
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.
Syntax for an inline function
inline return_type function_name(parameters)
{
// function code?
}
The compiler may not perform inlining in such circumstances as:
1. If a function contains a loop. (for, while and do-while)
2. If a function contains static variables.
3. If a function is recursive.
4. If a function return type is other than void, and the return statement doesn’t exist in a
function body.
5. If a function contains a switch or goto statement.
Let's understand the difference between the normal function and the inline
function.
▪ Inside the main() method, when the function fun1() is called, the control is transferred
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's understand through an example.
#include <iostream>
using namespace std;
inline int add(int a,int b)
{
return(a+b);
}
intmain(){
cout<<"Addition of 'a'and 'b'is:"<<add(2,3);
return 0;
}
➢ Class and Object
• A class in C++ is a user-defined data type that binds data and the functions that
operate on the data together in a single unit. Like other user-defined data types, it also
needs to be defined before using its objects in the program. A class definition specifies
a new data type that can be treated as a built-in data type.
• Defining Class and Declaring Objects
o A class is defined in C++ using the keyword class followed by the name of the
class. The body of the class is defined inside the curly brackets and terminated
by a semicolon at the end.
Example: A simple class definition
class book {
//private by default
char title [30] ; //variables declaration
float price;
public:
voidgetdata(char [],float); //function declaration
voidputdata ();
};
Declaring Objects
When a class is defined, only the specification for the object is defined; no memory or
storage 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 obj and you want to access the member function
with the name printName() then you will have to write obj.printName().
• Accessing Data Members
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
depends solely on the access control of that data member. This access control is given
by Access modifiers in C++. There are three access modifiers: public, private, and
protected.
// C++ program to demonstrate accessing of data members
#include <iostream>
using namespace std;
class A{
// Access specifier
public:
// Data Members
string Firstname;
// Member Functions()
void printname() { cout<< “name is:" <<Firstname; }
};
int main()
{
A obj1; // Declare an object of class geeks
obj1.Firstname = "Abhi"; // accessing data member
obj1.printname(); // accessing member function
return 0;
}
➢ Scope resolution operator
• The scope resolution operator is used to reference the global variable or member
function that is out of scope. Therefore, we use the scope resolution operator to access
the hidden variable or function of a program. The operator is represented as the
double 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 the scope resolution Operator
1. It is used to access the hidden variables or member functions of a program.
2. It defines the member function outside of the class using the scope resolution.
3. It is used to access the static variable and static function of a class.
4. The scope resolution operator is used to override function in the Inheritance.
Program to access the hidden value using the scope resolution (::) operator
#include <iostream>
using namespace std;
// declare global variable
int num = 50;
int main ()
{
int num = 100; // declare local variable
cout << " The value of the local variable num: " << num;
// print the value of the variables
cout << "\n The value of the global variable num: " << ::num;
// use scope resolution operator (::) to access the global variable
return 0;
}
➢ Passing objects as arguments
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.
class student
{
private:
int marks;
int total marks=0;
public:
void enter marks(){
cout<<"enter marks";
cin>>marks;}
void addmarks(student m1,student m2){
totalmarks=m1.marks+m2.marks;
}
void displaymarks(){
cout<<totalmarks;}
};
int main(){
students1,s2,s3;
s1.entermarks();
s2.entermarks();
s3.addmarks(s1,s2);
s3.displaymarks();
return 0;
}
➢ Return Object from a Function
A function 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>
using namespace std;
class student
{
private:
int marks;
int totalmarks=0;
public:
void entermarks()
{cout<<"enter marks";
cin>>marks;
}
student addmarks(student m1){
student m3;
m3.totalmarks=marks+m1.marks;
return m3;
}
void displaymarks();
};
void student::displaymarks()
{
cout<<totalmarks;}
int main(){
student s1,s2,s3;
s1.entermarks();
s2.entermarks();
s3=s1.addmarks(s2);
s3.displaymarks();
return 0;
}
➢ Object Assignment
• If both objects are of the same type (that is, both are objects of the same class), then
one 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.
• The following program demonstrates object assignment:
Example:
#include <iostream>
using namespace std;
class myclass{
int a, b;
public:
void setab(int i, int j)
{ a = i,
b = j;
}
void showab();
};
void myclass::showab()
{ cout<< "a is " << a << " \n ";
cout<< "b is " << b << " \n ";
}
int main(){
myclass ob1, ob2;
ob1.setab(10, 20);
ob2.setab(0, 0);
cout<< "ob1 before assignment:"<<"\n";
ob1.showab();
cout<< "ob2 before assignment:"<<"\n";
ob2.showab();
cout<< "\n";
ob2 = ob1; // assign ob1 to ob2
cout<< "ob1 after assignment: "<<"\n";
ob1.showab();
cout<< "ob2 after assignment:"<<"\n";
ob2.showab();
return 0;}