UNIT : 2
Syllabus
Classes and Objects, Constructors and
Destructors, Copy constructor,
Constructor Overloading, Operator
overloading and Type Conversions,
Inheritance, Extending classes
C++ Classes/Objects
• C++ is an object-oriented programming language.
• Everything in C++ is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car has
attributes, such as weight and color, and methods, such as drive and brake.
• Attributes and methods are basically variables and functions that belongs to
the class. These are often referred to as "class members".
• A class is a user-defined data type that we can use in our program, and it works
as an object constructor, or a "blueprint" for creating objects.
2
3
4
C++ Classes/Objects
• A Class is a user defined data type and an Object is a variable of this Class.
• For example suppose we want to store details of Book. There is no data type
available for storing the details of book. We can define a C structure for this
but a C structure defines only the attributes of an entity and not the behavior.
• So the functions which operate on this Book entity has to be defined
separately.
• Object Oriented approach allows us to create more powerful data type- Class,
which gives more control over the data type. 5
C++ Classes/Objects
• A class is an extension to C structure.
• The difference is that structure in C contains only attributes but a Class
can contains attribute along with the behavior of the entity.
• The class defines the blueprint of a real world entity.
• An Object is an instance of a class.
• If we need a real world entity then we need to instantiate object of a class.
6
Feature Array Structure Union Class
Data Types Homogeneous (same type) Heterogeneous (different Heterogeneous (different Heterogeneous (supports both
types) types, but only one active at a data and functions)
time)
Memory Usage Fixed and contiguous Sum of the sizes of members Size of the largest member Depends on data members,
methods, and inheritance
Access Indexed by integer Accessed by member name Accessed by member name Accessed by object (dot or
(dot operator) (dot operator) arrow operator)
Data Sharing No NO Yes (members share the same No (each object has its own
memory location) memory)
Methods No No No Yes (functions/methods
defined inside)
Use Case When you need to store a When you need to store When you need to store When you need
fixed number of elements of different data types together different types but only one at encapsulation, inheritance,
the same type a time and polymorphism
7
Defining Class in C++
8
Defining Class in C++
9
10
11
12
13
Access Modifiers
• In C++ classes, we can control the access to the members of the class using Access Specifiers.
• Also known as access modifier, they are the keywords that are specified in the class and all the
members of the class under that access specifier will have particular access level.
• In C++, there are 3 access specifiers that are as follows:
1. Public: Members declared as public can be accessed from outside the class.
2. Private: Members declared as private can only be accessed within the class itself.
3. Protected: Members declared as protected can be accessed within the class and by derived
classes.
If we do not specify the access specifier, the private specifier is applied to every member by
default. 14
Friend class
● A friend class can access private and protected members of other classes in which it is declared
as a friend.
● It is sometimes useful to allow a particular class to access private and protected members of
other classes.
● For example, a LinkedList class may be allowed to access private members of Node.
● We can declare a friend class in C++ by using the friend keyword.
15
Friend class
16
Friend Function
• Like a friend class, a friend function can be granted special access to
private and protected members of a class in C++.
• They are not the member functions of the class but can access and
manipulate the private and protected members of that class for they are
declared as friends.
• A friend function can be:
1. A global function
2. A member function of another class 17
Friend Function
18
Features of Friend Functions
● A friend function is a special function in C++ that in spite of not being a member function of a
class has the privilege to access the private and protected data of a class.
● A friend function is a non-member function or ordinary function of a class, which is declared as
a friend using the keyword “friend” inside the class. By declaring a function as a friend, all the
access permissions are given to the function.
● The keyword “friend” is placed only in the function declaration of the friend function and not in
the function definition or call.
● A friend function is called like an ordinary function. It cannot be called using the object name
and dot operator. However, it may accept the object as an argument whose value it wants to
access.
● A friend function can be declared in any section of the class i.e. public or private or protected.
19
Advantages of Friend Functions
● A friend function is able to access members without the need of inheriting the class.
● The friend function acts as a bridge between two classes by accessing their private
data.
● It can be used to increase the versatility of overloaded operators.
● It can be declared either in the public or private or protected part of the class.
Disadvantages of Friend Functions
● Friend functions have access to private members of a class from outside the class
which violates the law of data hiding.
● Friend functions cannot do any run-time polymorphism in their members. 20
21
Constructor in C++
● A constructor is a special member function of a class and shares the same
name as of class, which means the constructor and class have the same name.
● Constructor is called by the compiler whenever the object of the class is
created, it allocates the memory to the object and initializes class data
members by default values or values passed by the user while creating an
object.
● Constructors don’t have any return type because their work is to just create
and initialize an object. 22
In the syntax, we can see the class
has the name class_name and the
constructor have also the same name.
A constructor can have any number
of parameters as per requirements.
Also, there is no return type or return
value of the constructor.
Note: In the above syntax we have
declared the constructor as a public
member but we can declare it private
also
23
Important Points about Constructors
Access specifiers
● Constructors can be defined as public, protected, or private as per the requirements. By default or default
constructors, which are created by the compiler are declared as the public.
● If the constructor is created as private, then we are not able to create its object.
● When there is no requirement of the object of a class (in a situation when all class members are static) we can
define its constructor as private.
● Usually, constructors are defined as public because constructors are used to create an object and initialize the
class data members for the object.
● An object is always created from outside of class, which justifies making constructors public.
24
Important Points about Constructors
Inheritance
● As a derived class can access all the public properties of the base class, it can call its constructor also if it is
not declared as private. Also, the constructor's address cannot be referenced.
Virtual
● Constructor in C++ cannot be declared as virtual because when we declare any function of a class as a virtual
function, at compile time compiler creates a virtual table to store the address of each function that is declared
as virtual.
● Also, it creates a data member of the class virtual pointer to points towards the virtual table. But as we have
discussed we cannot refer to the address of the constructor, which means we are not able to declare the
constructor as virtual.
25
Types of constructors in c++
1. Default constructor
2. Parameterized constructor
3. Copy Constructor
4. Dynamic Constructor
26
1. Default Constructor
● Default constructor is also known as a zero-
argument constructor, as it doesn’t take any
parameter.
● It can be defined by the user if not then the
compiler creates it on his own.
● Default constructor always initializes data
members of the class with the same value they
were defined.
27
2. Parameterized Constructor
● Parameterized constructor is used to initialize data
members with the values provided by the user.
● This constructor is basically the upgraded version of
the default constructor.
● We can define more than one parameterized
constructor according to the need of the user, but we
have to follow the rules of the function overloading,
like a different set of arguments must be there for
each constructor.
28
3. Copy Constructor
● If we have an object of a class and we want to create
its copy in a new declared object of the same class,
then a copy constructor is used.
● The compiler provides each class a default copy
constructor and users can define it also.
● It takes a single argument which is an object of the
same class.
29
4. Dynamic Constructor
● When memory is allocated dynamically to
the data members at the runtime using a new
operator, the constructor is known as the
dynamic constructor.
● This constructor is similar to the default or
parameterized constructor; the only
difference is it uses a new operator to allocate
the memory.
30
Destructor in C++
● Destructor is just the opposite function of the constructor.
● A destructor is called by the compiler when the object is destroyed and its main function is
to deallocate the memory of the object.
● The object may be destroyed when the program ends, or local objects of the function get out
of scope when the function ends or in any other case.
● Destructor has the same as of the class with prefix tilde(~) operator and it cannot be
overloaded as the constructor.
● Destructors take no argument and have no return type and return value.
31
● In the syntax, we can see the class has
the name class_name and the destructor
also has the same name, in addition
there is a tilde(~).
● Also, there is no return type and return
value of the destructor.
● Note: In the syntax we have declared
the destructor as a public member but
we can declare it private also.
32
Important Points about the Destructor
● Destructor are the last member function called for an object and they are called by the compiler itself.
● If the destructor is not created by the user then compile creates or declares it by itself.
● A Destructor can be declared in any section of the class, as it is called by the compiler so nothing to worry
about.
● As Destructor is the last function to be called, it should be better to declare it at the end of the class to increase
the readability of the code.
● Destructor is just the opposite of the constructor as the constructor is called at the time of the creation of the
object and allocates the memory to the object, on the other side the destructor is called at the time of the
destruction of the object and deallocates the memory.
33
Constructor and and Destructor
● Constructor and Destructor are the special member functions of the class which are created by the C++
compiler or can be defined by the user.
● Constructor is called by the compiler whenever the object of the class is created, it allocates the memory to the
object and initializes class data members.
● A destructor is called by the compiler when the object is destroyed and its main function is to deallocate the
memory of the object.
● Constructors have the same as of class while destructors have the same name of the class with the prefix a
tilde (~) operator.
● Both Constructor and destructor can be defined as public, private, or protected. But it is better to declare the
constructor as public.
● The constructor can have parameters but the destructor doesn’t receive any parameters.
34
35
C++ Overloading
● If we create two or more members having the same name but different in number or type of
parameter, it is known as C++ overloading. In C++, we can overload:
1. methods
2. constructors
3. indexed properties
36
37
38
39
40
41
42
43
44
45
46
Function Overloading and Ambiguity
● When the compiler is unable to decide which
function is to be invoked among the overloaded
function, this situation is known as function
overloading.
● When the compiler shows the ambiguity error, the
compiler does not run the program.
● Causes of Function Overloading:
a. 1. Type Conversion
b. 2. Function with default arguments
c. 3. Function with pass by reference.
47
● The example shows an error
"call of overloaded
fun(double)' is ambiguous".
● The fun(10) will call the first
function.
● The fun(1.2) calls the second
function according to our
prediction.
● But, this does not refer to any
function as in C++, all the
floating point constants are
treated as double not as a float.
If we replace float to double,
the program works. Therefore,
this is a type conversion from
float to double.
48
● The example shows an error "call of
overloaded 'fun(int)' is ambiguous".
● The fun(int a, int b=9) can be called
in two ways: first is by calling the
function with one argument, i.e.,
fun(12) and another way is calling
the function with two arguments,
i.e., fun(4,5).
● The fun(int i) function is invoked
with one argument.
● Therefore, the compiler could not be
able to select among fun(int i) and
fun(int a,int b=9).
49
● The example shows an error "call of
overloaded 'fun(int&)' is
ambiguous".
● The first function takes one integer
argument and the second function
takes a reference parameter as an
argument.
● In this case, the compiler does not
know which function is needed by
the us
50
Why is C++ Using Function Overloading?
• Over traditional structured programming languages, the OOPS ideas offer a number of
benefits.
• Overloading functions is regarded as compile-time polymorphism.
• With the help of this OOPS idea, a programmer can create a function with the same name
but a distinct execution pattern, enabling the code to be more understandable and reusable.
51
Rules of function overloading in C++?
When overloading a function in C++, there are some guidelines that must be observed. Let's take a closer look
at a few of them:
1) The parameters for each function must be in a distinct order.
2) The functions have to be named the same.
3) The parameters for the functions must be distinct.
4) The parameters for the functions must be of various sorts.
52
Types of function overloading in C++
In C++, there are two types of function overloading. Those are
1) Overloading at compile time occurs when alternative signatures are used to overload the functions. The
function's return type, number, and type of parameters are all regarded as the function's signature.
2) Overloading that occurs during runtime refers to the overloading of the functions. Time overloading occurs
when a different number of parameters are added to the function during execution.
53
Advantages of function overloading in C++
Here are a few benefits of function overloading in C++.
1) The programmer can create functions with distinct purposes but the same name by using function overloading.
2) It speeds up the program's execution.
3) The code is clearer and simpler to comprehend.
4) It reduces memory utilization and makes programs reusable.
Disadvantages of function overloading in C++
The following are some drawbacks of C++ function overloading.
1) The primary drawback of function overloading is that it prevents the overloading of functions with various return types.
2) The identical parameters cannot be overloaded in the case of a static function.
54
C++ Operators Overloading
• Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the
special meaning to the user-defined data type.
• Operator overloading is used to overload or redefines most of the operators available in C++.
• It is used to perform the operation on the user-defined data type.
• For example, C++ provides the ability to add the variables of the user-defined data type that is applied to the
built-in data types.
• Where the return type is the type of value
returned by the function.
• class_name is the name of the class.
• operator op is an operator function where op is the operator being overloaded, and the operator is the
keyword. 55
Operator that cannot be overloaded are as follows:
• Scope operator (::)
• Sizeof
• member selector(.)
• member pointer selector(*)
• ternary operator(?:)
56
Rules for Operator Overloading
• Existing operators can only be overloaded, but the new operators cannot be overloaded.
• The overloaded operator contains at least one operand of the user-defined data type.
• We cannot use friend function to overload certain operators. However, the member function
can be used to overload those operators.
• When unary operators are overloaded through a member function take no explicit
arguments, but, if they are overloaded by a friend function, takes one argument.
• When binary operators are overloaded through a member function takes one explicit
argument, and if they are overloaded through a friend function takes two explicit arguments.
57
C++ Operators Overloading Example
• Let's see the simple example of operator
overloading in C++.
• In this example, void operator ++ () operator
function is defined (inside Test class).
• // program to overload the unary operator +
+.
58
59
60