WINSEM2023-24 BCSE102L TH VL2023240501147 2024-02-23 Reference-Material-I
WINSEM2023-24 BCSE102L TH VL2023240501147 2024-02-23 Reference-Material-I
WINSEM2023-24 BCSE102L TH VL2023240501147 2024-02-23 Reference-Material-I
C++ history
• History of C++ language
• C++ programming language was developed in 1980 by
Bjarne Stroustrup at bell laboratories of AT&T (American
Telephone & Telegraph), located in U.S.A.
• Bjarne Stroustrup is known as the founder of C++
language.
• It was developed for adding a feature of OOP (Object
Oriented Programming) in C without significantly changing
the C component.
• C++ is a general-purpose object-oriented programming
(OOP) language, developed by Bjarne Stroustrup, and is an
extension of the C language.
• Initially, In 1979, the language was called "C with classes" as
it had all the properties of the C language with an additional
concept of "classes."
• In 1983, 'C with classes' was renamed to 'C++', adding new
features like virtural functions, operator overloading,
references, memory allocation/de-allocation/ with
new/delete keywords.
• In 1985, the first version of C++ was released
• In 1989, C++ 2.0 was released includes features like multiple
inheritance, abstract classes, static member functions.
• Later feature additions included templates, exceptions,
namespace, boolean type.
Define C++
• Relation Between C and C++
• C++ is an object-oriented programming language. It
was developed by Bjarne Stroustrup at AT & T Bell
Laboratory in Murray Hill, New Jersey, USA in 1979. C+
+ is a superset of C. C++ has solved many other
problems faced by C programmers. C++ is a versatile
language for handling very large programs. C++ is a
case sensitive programming language. Most of the C
concept applies to C++ also. The most important
facilities that C++ adds is the concept of OOP's (Object
Oriented Programming).
Difference between C and C++
No. C C++
1) C follows the procedural C++ is multi-paradigm. It supports
style programming. both procedural and object oriented.
2) Data is less secured in C. In C++, you can use modifiers for class members
to make it inaccessible for outside users.
3) C follows the top-down C++ follows the bottom-up approach.
approach.
4) C does not support function C++ supports function overloading.
overloading.
5) In C, you can't use functions In C++, you can use functions in structure.
in structure.
6) C does not support C++ supports reference variables.
reference variables.
7) In C, scanf() and C++ mainly uses stream cin and
printf() are mainly used cout to perform input and output
for input/output. operations.
8) Operator overloading is Operator overloading is possible
not possible in C. in C++.
9) C programs are divided C++ programs are divided
into procedures and into functions and classes.
modules
10) C does not provide the C++ supports the feature of
feature of namespace. namespace.
11) Exception handling is not C++ provides exception handling
easy in C. It has to using Try and Catch block.
perform using other
functions.
12) C does not support the C++ supports inheritance.
inheritance.
Object Oriented Programming
1. OOP is object oriented and POP is structure oriented.
class person {
char name[20];
int id;
public:
void getdetails() {}
};
int main()
{
person p1; // p1 is a object
return 0;
}
Class
• Class in C++ is the building block that leads to
Object-Oriented programming.
• 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 C++ class is like a blueprint for an object.
• A Class is a user-defined data type that has
data members and member functions.
• Data members are the data variables and
member functions are the functions used to
manipulate these variables together, these
data members and member functions define
the properties and behavior of the objects in a
Class.
Object
An Object is an instance of a Class.
When a class is defined, no memory is allocated
but when it is instantiated (i.e. an object is
created) memory is allocated.
An object is an instantiation of a class.
In terms of variables, a class would be the type,
and an object would be the variable.
• Objects take up space in memory and have an associated
address like a record in pascal or structure or union.
• When a program is executed the objects interact by
sending messages to one another.
• Each object contains data and code to manipulate the
data.
• Objects can interact without having to know details of
each other’s data or code, it is sufficient to know the
type of message accepted and the type of response
returned by the objects.
Where class_name is a valid identifier for the class, object_names is
an optional list of names for objects of this class.
The body of the declaration can contain members, which can either be
data or function declarations, and optionally access specifiers.
Classes have the same format as plain data structures, except that
they can also include functions and have these new things
called access specifiers. An access specifier is one of the following
three keywords: private, public or protected. These specifiers modify
the access rights for the members that follow them:
class class_name {
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
By default, all members of a class declared with the class
keyword have private access for all its members.
Therefore, any member that is declared before any other access
specifier has private access automatically. For example:
class Rectangle {
int width, height;
public:
void set_values (int,int);
int area (void);
} rect;
Declares a class (i.e., a type) called Rectangle and an object (i.e.,
a variable) of this class, called rect. This class contains four
members: two data members of type int (member width and
member height) with private access (because private is the
default access level) and two member functions with public
access: the functions set_values and area, of which for now we
have only included their declaration, but not their definition.
Notice the difference between the class name and the object
name: In the previous example, Rectangle was the class name
(i.e., the type), whereas rect was an object of type Rectangle. It
is the same relationship int and a have in the following
declaration:
int a;
where int is the type name (the class) and a is the variable name
(the object).
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
• ClassName ObjectName;
class product
{
int code, quantity;
float price;
public:
void assignData();
void Print();
};
product p1, p2;
After the declarations of Rectangle and rect, any of the public
members of object rect can be accessed as if they were normal
functions or normal variables, by simply inserting a dot (.)
between object name and member name. This follows the same
syntax as accessing the members of plain data structures. For
example:
rect.set_values (3,4);
myarea = rect.area();
class operation {
int a, b, add, sub, mul;
float div;
public:
void get();
void sum();
void difference();
void product();
void division();
};
inline void operation ::get()
{
cout << "Enter first value:";
cin >> a;
cout << "Enter second value:";
cin >> b;
}
inline void operation ::sum()
{
add = a + b;
cout << "Addition of two numbers: " << a + b << "\n";
}
inline void operation ::difference()
{
sub = a - b;
cout << "Difference of two numbers: " << a - b << "\n";
}
inline void operation ::product()
{
mul = a * b;
cout << "Product of two numbers: " << a * b << "\n";
}
inline void operation ::division()
{
div = a / b;
cout << "Division of two numbers: " << a / b << "\n";
}
int main()
{
cout << "Program using inline function\n";
operation s;
s.get();
s.sum();
s.difference();
s.product();
s.division();
return 0;
}
Access Modifiers in C++
• Access modifiers are used to implement an important
aspect of Object-Oriented Programming known as Data
Hiding.
• Access Modifiers or Access Specifiers in a class are used to
assign the accessibility to the class members, i.e., they set
some restrictions on the class members so that they can’t
be directly accessed by the outside functions.
There are 3 types of access modifiers available in C++:
• Public
• Private
• Protected
• Note: If we do not specify any access modifiers for the
members inside the class, then by default the access
modifier for the members will be Private.
• Let us now look at each one of these access modifiers in
detail:
1. Public: All the class members declared under the public
specifier will be available to everyone. The data members
and member functions declared as public can be accessed
by other classes and functions too. The public members of a
class can be accessed from anywhere in the program using
the direct member access operator (.) with the object of
that class.
#include<iostream> // main function
int main()
using namespace std; {
Circle obj;
// class definition
// accessing public datamember outside cla
class Circle obj.radius = 5.5;
{
cout << "Radius is: " << obj.radius << "\n";
public: cout << "Area is: " << obj.compute_area();
double radius; return 0;
}
double compute_area()
{
return 3.14*radius*radius;
}
};
2. Private:
• The class members declared as private can be
accessed only by the member functions inside
the class. They are not allowed to be accessed
directly by any object or function outside the
class. Only the member functions or the
friend functions are allowed to access the
private data members of the class.
// main function
#include<iostream> int main()
{
using namespace std; // creating object of the class
Circle obj;
class Circle
{ // trying to access private data mem
// private data member // directly outside the class
obj.radius = 1.5; //error
private:
double radius; cout << "Area is:" <<
obj.compute_area();
// public member function return 0;
public: }
double compute_area()
{ // member function can access private
// data member radius
return 3.14*radius*radius;
}
// C++ program to demonstrate private
// access modifier
// main function
#include<iostream> int main()
using namespace std; {
// creating object of the class
class Circle Circle obj;
{
// private data member // trying to access private data member
private: // directly outside the class
double radius; obj.compute_area(1.5);
id_protected = id;
void displayId()
{
cout << "id_protected is: " << id_protected << endl;
}
};
Example
// classes example
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
void set_values (int,int);
int area() {return width*height;}
};
int main () {
Rectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
return 0;
}
C++ Constructors
• A constructor is a special type of member
function that is called automatically when an
object is created.
• In C++, a constructor has the same name as that
of the class, and it does not have a return type.
• A constructor in C++ is a special ‘MEMBER FUNCTION’
having the same name as that of its class which is used to
initialize some valid values to the data members of an
object.
• It is executed automatically whenever an object of a class
is created.
• The only restriction that applies to the constructor is that
it must not have a return type or void.
• It is because the constructor is automatically called by the
compiler and it is normally used to INITIALIZE VALUES.
• The compiler distinguishes the constructor from other
member functions of a class by its name which is the same
as that of its class.
Constructor in C++ Syntax
The syntax for defining constructor inside the class body is as follows:
class CLASSNAME
{
………
public :
CLASSNAME([parameter_list]) // constructor definition
{
......
}
........
};
• You can also define a constructor with its declaration inside the class body and
see what follows.
class CLASSNAME
{
........
public:
CLASSNAME ([parameter_list]);//Constructor declaration
.........
};
CLASSNAME: :CLASSNAME([parameter_list])//Constructor Definition
{
...........
}
• The above syntax shows the declaration and definition
of a constructor. It is defined outside the class in the
same way as we define a member function outside the
class using the scope resolution operator.
• One should note that the name of the constructor is the
same as that of its class. The constructor parameter list
enclosed in the square brackets is optional and may
contain zero or more parameters.
• We should declare the constructor in the public section
of the class as they are invoked automatically when the
objects are created.
Take note that the Constructor.
• Using the default constructor, data members can be initialized to some realistic values in its
definition even though no arguments are specified explicitly. Each time an object is created,
a constructor is invoked. If we define objects and classes without defining any constructor
for a class. So in such a situation, the compiler automatically generates a constructor of its
own without any parameters i.e. Default Constructor.
• . However, if you define a default constructor explicitly, the compiler no longer generates a
default constructor for you.
#include <iostream>
using namespace std;
// declare a class
class Wall {
private:
double length;
public:
// default constructor to initialize variable
Wall() {
length = 5.5;
cout << "Creating a wall." << endl;
cout << "Length = " << length << endl;
}
};
int main() {
Wall wall1;
return 0;
}
class Line
{
public:
int size;
int main()
{
//default constructor called when object is created
Line l;
cout<<"Line size is"<<" "<<l.size<<" "<<"cm";
return 0;
}
#include <iostream>
using namespace std;
class TestDefault {
private:
int num1, num2 ;
public:
TestDefault() {
num1 = 10;
num2 = 20;
}
void display() {
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
};
int main() {
TestDefault obj;
obj.display();
return 0;
}
C++ Parameterized Constructor
class class_name
{
public:
class_name(variables) //Parameterized constructor declared.
{
}
};
The syntax for declaring parameterized construct outside the class:
class class_name
{
};
class_name :: class_name() //Parameterized constructor
declared.
{
}
// C++ program to calculate the area of a wall
int main() {
#include <iostream> // create object and initialize data members
using namespace std; Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);
// declare a class
class Wall { cout << "Area of Wall 1: " << wall1.calculateArea
private: << endl;
double length; cout << "Area of Wall 2: " << wall2.calculateArea
double height;
return 0;
public: }
// parameterized constructor to initialize variables
Wall(double len, double hgt) {
length = len;
height = hgt;
}
double calculateArea() {
return length * height;
}
};
Constructor Overloading
• In some programs, a class had only one constructor
which was either zeroes, one, or more parameters.
• The constructor is key for object initialization.
• The mechanism of the constructor is made
considerably more powerful by uniting with the
feature of overloading.
• It is made possible by providing more than one
constructor in a class called Constructor
overloading.
#include <iostream>
using namespace std; OUTPUT:
class ABC X = 10 and y = 0
X = 10 and y = 10
{ x = 10 and y = 2
private:
int x,y;
public:
ABC () //constructor 1 with no arguments
{
x = y = 0;
}
ABC(int a) //constructor 2 with one argument
{
x = y = a;
}
ABC(int a,int b) //constructor 3 with two argument
{
x = a;
y = b;
}
void display()
{
cout << "x = " << x << " and " << "y = " << y << endl;
}
};
int main()
{
ABC cc1; //constructor 1
ABC cc2(10); //constructor 2
ABC cc3(10,20); //constructor 3
cc1.display();
cc2.display();
cc3.display();
return 0;
} //end of program
#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo",
890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
References in C++
int main()
{
int x = 10;
// ref is a reference to x.
int& ref = x;
// Value of x is now changed to 20
ref = 20;
cout << "x = " << x << '\n';
// Value of x is now changed to 30
x = 30;
cout << "ref = " << ref << '\n';
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int i=8; // variable initialization
int &a=i; // creating a reference variable
cout<<"The value of 'i' variable is :"<<a;
return 0;
}
We cannot reassign the reference variable.
#include <iostream>
using namespace std;
int main()
{
int i; // variable declaration
int k; // variable declaration
int &a=i;
int &a=k; // error
return 0;
}
C++ Copy Constructor
• The copy constructor in C++ is used to copy data from one object to
another.
• A copy constructor is a member function that initializes an object
using another object of the same class. In simple terms, a constructor
which creates an object by initializing it with an object of the same
class, which has been created previously is known as a copy
constructor.
• Copy constructor is used to initialize the members of a newly created
object by copying the members of an already existing object.
• Copy constructor takes a reference to an object of the same class as
an argument.
Sample(Sample &t)
{
id=t.id;
}
#include <iostream>
using namespace std;
int main() {
// declare a class // create an object of Wall class
class Wall { Wall wall1(10.5, 8.6);
private:
double length; // copy contents of wall1 to wall2
double height; Wall wall2 = wall1;
double calculateArea() {
return length * height;
}
};
#include <iostream>
#include <string.h>
using namespace std;
class student {
int rno;
char name[50];
double fee;
public:
student(int, char[], double);
student(student& t) // copy constructor
{
rno = t.rno;
strcpy(name, t.name);
fee = t.fee;
void display();
};
student::student(int no, char n[], double f)
{
rno = no;
strcpy(name, n);
fee = f;
}
void student::display()
{
cout << endl << rno << "\t" << name << "\t" << fee;
}
int main()
{
student s(1001, "Manjeet", 10000);
s.display();
return 0;
}
Characteristics of Copy Constructor
1. The copy constructor is used to initialize the members of a
newly created object by copying the members of an already
existing object.
class Point {
Output
private: p1.x = 10, p1.y = 15
int x, y; p2.x = 10, p2.y = 15
public:
Point(int x1, int y1)
{
x = x1;
y = y1;
}
// Copy constructor
Point(const Point& p1)
{
x = p1.x;
y = p1.y;
}
int getX() { return x; }
int getY() { return y; }
};
int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here
// Let us access values assigned by constructors
cout << "p1.x = " << p1.getX()
<< ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX()
<< ", p2.y = " << p2.getY();
return 0;
// C++ program to demonstrate the working
// of a COPY CONSTRUCTOR
#include <iostream>
using namespace std;
class Point {
Output
private: p1.x = 10, p1.y = 15
int x, y; p2.x = 10, p2.y = 15
public:
Point(int x1, int y1)
{
x = x1;
y = y1;
}
// Copy constructor
int getX() { return x; }
int getY() { return y; }
};
int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here
// Let us access values assigned by constructors
cout << "p1.x = " << p1.getX()
<< ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX()
<< ", p2.y = " << p2.getY();
return 0;
}
Problem to solve
Problem to solve
Destructors in C++
// destructor
~A()
{
cout << "Destructor called";
}
};