WINSEM2023-24 BCSE102L TH VL2023240501147 2024-02-23 Reference-Material-I

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 113

C++

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.

2. Data is shared among the objects through member functions


in OOP and global data is shared among functions in programs in
POP.

3. Access specifiers are used in OOP whereas no access specifiers


are used in POP.

4. OOP gives priority to objects and POP gives priority to


functions.

5. OOP deals with data whereas POP deals with algorithm.


6. In OOP modification is easy as objects are
independent whereas in POP modification is difficult as
it can affect the entire program.
7.It is possible to hide data in OOP whereas there is no
data hiding mechanism in POP.
8.OOP is highly secure whereas POP is less secure.
9. Operator overloading is possible in OOP whereas
operator overloading cannot take place in POP.
10. For memory allocation functions like new and
delete are used in OOP and in POP for memory
allocation functions like malloc and calloc are used.
11. For
input and output inbuilt functions like cin and cout are
used in OOP and in POP for input and output inbuilt
functions like printf and scanf are used.
12.Data encapsulation or abstraction, inheritance,
polymorphism, overloading are basic concepts of OOP
whereas it cannot take place in POP.
13. OOP follows bottom up approach whereas POP follows
top down approach.
15. Examples of OOP are C++, JAVA, PYTHON,etc.
16 Examples of POP are C, Pascal, FORTRAN, etc.
Object Oriented Programming in C++

• Object-oriented programming – As the name


suggests uses objects in programming.
• Object-oriented programming aims to
implement real-world entities like inheritance,
hiding, polymorphism, etc. in programming.
• The main aim of OOP is to bind together the
data and the functions that operate on them
so that no other part of the code can access
this data except that function.
There are some basic concepts that act as the building
blocks of OOPs i.e.
Class
Objects
Encapsulation
Abstraction
Polymorphism
Inheritance
Dynamic Binding
Message Passing
Characteristics of an Object-Oriented
Programming Language
Class
• The building block of C++ that leads to Object-Oriented
programming is a 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.
• For Example: Consider the Class of Cars. There may be many
cars with different names and brands but all of them will
share some common properties like all of them will have 4
wheels, Speed Limit, Mileage range, etc. So here, the Car is
the class, and wheels, speed limits, and mileage are their
properties. Class in C++ is a blueprint representing a group of
objects which shares some common properties and
behaviors.
Object

• An Object is an identifiable entity with some


characteristics and behavior.
• 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.
#include <iostream>
using namespace std;

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:

private members of a class are accessible only from within other


members of the same class (or from their "friends").
protected members are accessible from other members of the same
class (or from their "friends"), but also from members of their derived
classes.
Finally, public members are accessible from anywhere where the
object is visible.
Encapsulation
In normal terms,
Encapsulation is defined as
wrapping up data and
information under a single
unit.
In Object-Oriented
Programming, Encapsulation is
defined as binding together
the data and the functions
that manipulate them.
• Encapsulation also leads to data abstraction or
data hiding. Using encapsulation also hides
the data.
Abstraction
• Data abstraction is one of the most essential
and important features of object-oriented
programming in C++.
• Abstraction means displaying only essential
information and hiding the details.
• Data abstraction refers to providing only
essential information about the data to the
outside world, hiding the background details
or implementation.
Polymorphism

• The word polymorphism means having many


forms.
• A person at the same time can have different
characteristics. A man at the same time is a
father, a husband, and an employee. So the
same person possesses different behavior in
different situations. This is called
polymorphism.
• The behavior depends upon the types of data used
in the operation. C++ supports operator overloading
and function overloading.
• Operator Overloading: The process of making an
operator exhibit different behaviors in different
instances is known as operator overloading.
• Function Overloading: Function overloading is using
a single function name to perform different types of
tasks. Polymorphism is extensively used in
implementing inheritance.
Inheritance

• The capability of a class to derive properties and characteristics


from another class is called Inheritance. Inheritance is one of
the most important features of Object-Oriented Programming.
• Sub Class: The class that inherits properties from another class
is called Sub class or Derived Class.
• Super Class: The class whose properties are inherited by a sub-
class is called Base Class or Superclass.
• Reusability: Inheritance supports the concept of “reusability”,
i.e. when we want to create a new class and there is already a
class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we
are reusing the fields and methods of the existing class.
Dynamic Binding

• In dynamic binding, the code to be executed in


response to the function call is decided at
runtime. C++ has virtual functions to support
this. Because dynamic binding is flexible, it
avoids the drawbacks of static binding, which
connected the function call and definition at
build time.
Message Passing
• Objects communicate with one another by
sending and receiving information. A message
for an object is a request for the execution of a
procedure and therefore will invoke a function
in the receiving object that generates the
desired results. Message passing involves
specifying the name of the object, the name
of the function, and the information to be
sent.
Defining Class and Declaring Objects

• Classes are defined using either keyword class or


keyword struct, with the following syntax:

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();

The only members of rect that cannot be accessed from outside


the class are width and height, since they have private access
and they can only be referred to from within other members of
that same class.
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().
Member Functions in Classes

• There are 2 ways to define a member


function:
• Inside class definition
• Outside class definition
To define a member function outside the class
definition we have to use the scope resolution::
operator along with the class name and function
name.
#include <iostream.h>
class sample int main() {
{
public: sample obj1;
char name[50] cin>>obj1.name ;
int id; obj1.id=15;
void printname();
void printid()
// call printname()
{
obj1.printname();
cout <<" id is: "<<id;
cout << endl;
}
};
// call printid()
void sample ::printname()
obj1.printid();
{
return 0;
cout <<"name is: "<<name;
}
}
Inline Functions 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.
#include <iostream>
using namespace std;
inline int cube(int s) { return s * s * s; }
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
}
Inline function and classes

• It is also possible to define the inline function


inside the class. In fact, all the functions
defined inside the class are implicitly inline.
Thus, all the restrictions of inline functions are
also applied here. If you need to explicitly
declare an inline function in the class then just
declare the function inside the class and
define it outside the class using the inline
keyword.
class S
{
public:
int square(int s); // declare the function
};

inline int S::square(int s) // use inline prefix


{
}
#include <iostream>

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);

// public member function


public: return 0;
void compute_area(double r) }
{ // member function can access private
// data member radius
radius = r;

double area = 3.14*radius*radius;

cout << "Radius is: " << radius << endl;


cout << "Area is: " << area;
}
3. Protected:
• The protected access modifier is similar to the
private access modifier in the sense that it
can’t be accessed outside of its class unless
with the help of a friend class. The difference
is that the class members declared as
Protected can be accessed by any subclass
(derived class) of that class as well.
// base class
class Parent
{ // main function
protected: int main() {
int id_protected;
Child obj1;
};
obj1.setId(81);
class Child : public Parent obj1.displayId();
{ return 0;
public: }
void setId(int id)
{

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;}
};

void Rectangle::set_values (int x, int y) {


width = x;
height = y;
}

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.

• The constructor has the same name as the


class.
• The constructor does not have a return type,
and
• Constructor is public
class Wall {
public:
Wall()
{ // code }
};
Here, the function Wall() is a constructor of the class Wall.
Notice that the constructor
• has the same name as the class,
• does not have a return type, and
• is public
Types of Constructors
• Default constructor
• Parameterized constructor
• Copy constructor
Default constructor

• A constructor with no parameters is known as


a default constructor. For example,
Default constructor
• A constructor to which no arguments are passed is called the Default constructor. It is also
called a constructor with no parameters.
• Constructors are class functions that are called when new instances of the class’s objects are
produced. The constructors share the same name as the class, but they don’t even have void
as a return type. They are most helpful for giving class variables their initial values. Default
constructors and parameterized constructors are the two primary types of constructors.
• There are no parameters accepted by default constructors. The compiler will give an implicit
default constructor if the programmer does not explicitly provide one. In that scenario, the
variables’ default values are 0.

• 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;

//default constructor Output Line size is 30 cm


Line()
{
size=30;
}
};

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

• In C++, a constructor with parameters is known


as a parameterized constructor. This is the
preferred method to initialize member data.
Unlike default constructors which do not take any
parameters, it is however possible to pass one or
more arguments to a constructor.

Constructors that can take arguments are known


as parameterized constructors.
The syntax for declaring parameterized constructor inside the
set:

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++

• When a variable is declared as a reference, it


becomes an alternative name for an existing variable.
• A variable can be declared as a reference by putting
‘&’ in the declaration.
• Also, we can define a reference variable as a type of
variable that can act as a reference to another
variable. ‘&’ is used for signifying the address of a
variable or any memory.
• Variables associated with reference variables can be
accessed either by its name or by the reference
variable associated with it.
• Syntax:
• data_type &ref = variable;

• A reference is a variable that is referred to as another


name for an already existing variable. The reference of a
variable is created by storing the address of another
variable.
• A reference variable can be considered as a constant
pointer with automatic indirection. Here, automatic
indirection means that the compiler automatically applies
the indirection operator (*).
#include <iostream>
using namespace std;

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;

public: // print areas of wall1 and wall2


cout << "Area of Wall 1: " << wall1.calculateArea()
Wall(double len, double hgt) { << endl;
length = len; cout << "Area of Wall 2: " << wall2.calculateArea()
height = hgt;
} return 0;
Wall(Wall &obj) { }
length = obj.length;
height = obj.height;
}

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();

student manjeet(s); // copy constructor called


manjeet.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.

2. Copy constructor takes a reference to an object of the same


class as an argument. If you pass the object by value in the copy
constructor, it would result in a recursive call to the copy
constructor itself. This happens because passing by value
involves making a copy, and making a copy involves calling the
copy constructor, leading to an infinite loop. Using a reference
avoids this recursion. So we use reference of Objects to avoid
infinite calls.
Sample(Sample &t)
{
id=t.id;
}
3. The process of initializing members of an object through a
copy constructor is known as copy initialization.

4. It is also called member-wise initialization because the copy


constructor initializes one object with the existing object, both
belonging to the same class on a member-by-member copy
basis.

5. The copy constructor can be defined explicitly by the


programmer. If the programmer does not define the copy
constructor, the compiler does it for us.
// 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
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 is a special class function which


destroys the object as soon as the scope of
object ends.
• The destructor is called automatically when
the object goes out of scope.
• The syntax for destructor is same as that for
the constructor, the class name is used for the
name of destructor, with a tilde ~ sign as
prefix to it.
class A
{
public:
// defining destructor for class
~A()
{
// statement
}
};
Example to see how Constructor and
Destructor are called
class A
int main()
{ {
public: A obj1; // Constructor Called
// constructor int x = 1;
A() if(x)
{ {
A obj2; // Constructor Called
cout << "Constructor called";
} // Destructor Called for obj2
} } // Destructor called for obj1

// destructor
~A()
{
cout << "Destructor called";
}
};

You might also like