0% found this document useful (0 votes)
11 views76 pages

Unit 2

Uploaded by

yuvrajahuja2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views76 pages

Unit 2

Uploaded by

yuvrajahuja2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

UNIT 2

VISHAKHA SEHDEV VERMA


Access modifiers
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

VISHAKHA SEHDEV VERMA


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.

VISHAKHA SEHDEV VERMA


// C++ program to demonstrate public
// access modifier

#include<iostream>
using namespace std;

// class definition
class Circle
{
public:
double radius;

double compute_area()
{
return 3.14*radius*radius;
}

};

VISHAKHA SEHDEV VERMA


// main function
int main()
{
Circle obj;

// accessing public datamember outside class


obj.radius = 5.5;

cout << "Radius is: " << obj.radius << "\n";


cout << "Area is: " << obj.compute_area();
return 0;
}

VISHAKHA SEHDEV VERMA


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.

VISHAKHA SEHDEV VERMA


// C++ program to demonstrate private
// access modifier

#include<iostream>
using namespace std;

class Circle
{
// private data member
private:
double radius;

// public member function

VISHAKHA SEHDEV VERMA


public:
double compute_area()
{ // member function can access private
// data member radius
return 3.14*radius*radius;
}

};

// main function

VISHAKHA SEHDEV VERMA


int main()
{
// creating object of the class
Circle obj;

// trying to access private data member


// directly outside the class
obj.radius = 1.5;

cout << "Area is:" << obj.compute_area();


return 0;
}

VISHAKHA SEHDEV VERMA


Output
In function 'int main()':
11:16: error: 'double Circle::radius' is private
double radius;
^
31:9: error: within this context
obj.radius = 1.5;
^
The output of the above program is a compile time error because we are not
allowed to access the private data members of a class directly from outside the
class. Yet an access to obj.radius is attempted, but radius being a private data
member, we obtained the above compilation error.
However, we can access the private data members of a class indirectly using the
public member functions of the class.
VISHAKHA SEHDEV VERMA
// C++ program to demonstrate private
// access modifier

#include<iostream>
using namespace std;

class Circle
{
// private data member
private:
double radius;

// public member function

VISHAKHA SEHDEV VERMA


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

};

VISHAKHA SEHDEV VERMA


// main function
int main()
{
// creating object of the class
Circle obj;

// trying to access private data member


// directly outside the class
obj.compute_area(1.5);

return 0;
}

VISHAKHA SEHDEV VERMA


Output:

Radius is: 1.5


Area is: 7.065

VISHAKHA SEHDEV VERMA


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.

VISHAKHA SEHDEV VERMA


// C++ program to demonstrate
// protected access modifier
#include <bits/stdc++.h>
using namespace std;

// base class
class Parent
{
// protected data members
protected:
int id_protected;

};

// sub class or derived class from public base class

VISHAKHA SEHDEV VERMA


class Child : public Parent
{
public:
void setId(int id)
{
// Child class is able to access the inherited
// protected data members of base class
id_protected = id;
}
void displayId()
{
cout << "id_protected is: " << id_protected << endl;
}
};

VISHAKHA SEHDEV VERMA


// main function
int main() {

Child obj1;

// member function of the derived class can


// access the protected data members of the base class

obj1.setId(81);
obj1.displayId();
return 0;
}

VISHAKHA SEHDEV VERMA


Output
id_protected is: 81

VISHAKHA SEHDEV VERMA


Ambiguity Problem in Multiple Inheritance
In Multiple Inheritance, when a single class is derived from two or more base or
parent classes.
So, it might be possible that both the parent class have the same-named
member functions, and it shows ambiguity when the child class object invokes
one of the same-named member functions.
Hence, we can say, the C++ compiler is confused in selecting the member
function of a class for the execution of a program.

VISHAKHA SEHDEV VERMA


#include <iostream>
#include <conio.h>

using namespace std;

// create class A
class A
{
public:
void show()
{
cout << " It is the member function of class A " << endl;
}
};

VISHAKHA SEHDEV VERMA


class B
{
public:
void show()
{
cout << " It is the member function of class B " << endl;
}
};

VISHAKHA SEHDEV VERMA


class child: public A, public B
{
public:
void disp()
{
cout << " It is the member function of the child class " << endl;
}
};
int main ()
{
// create an object of the child class to access the member function
child ch;
ch.show(); // It causes ambiguity
ch.disp();
return 0;
}
VISHAKHA SEHDEV VERMA
 When the above program is compiled, it throws the show() member function
is ambiguous.
 Because of both the base class A and B, defining the same member function
show(), and when the derived class's object call the shows() function, it
shows ambiguity in multiple inheritances.
 Therefore, we need to resolve the ambiguous problem in multiple
Inheritance. The ambiguity problem can be resolved by defining the class
name and scope resolution (::) operator to specify the class from which the
member function is invoked in the child class.

VISHAKHA SEHDEV VERMA


Syntax of the Ambiguity Resolution
Derived_obj_name.parent_class_name : : same_named_memberFunction (
[parameter] );

ch.A:: show(); // class_name and scope resolution operator with member


function
ch.B::show();

It is the member function of the child class


It is the member function of class A
It is the member function of class B

VISHAKHA SEHDEV VERMA


Virtual base class
 Virtual base classes are used in virtual inheritance in a way of preventing
multiple “instances” of a given class appearing in an inheritance hierarchy
when using multiple inheritances.

 Need for Virtual Base Classes: Consider the situation where we have one class
A . This class A is inherited by two other classes B and C. Both these class are
inherited into another in a new class D as shown in figure below.

VISHAKHA SEHDEV VERMA


VISHAKHA SEHDEV VERMA
 As we can see from the figure that data members/function of class A are
inherited twice to class D. One through class B and second through class C.
 When any data / function member of class A is accessed by an object of class
D, ambiguity arises as to which data/function member would be called? One
inherited through B or the other inherited through C.
 This confuses compiler and it displays error.

VISHAKHA SEHDEV VERMA


#include <iostream>
using namespace std;

class A {
public:
void show()
{
cout << "Hello form A \n";
}
};

class B : public A {
};

VISHAKHA SEHDEV VERMA


class C : public A {
};

class D : public B, public C {


};

int main()
{
D object;
object.show();
}

VISHAKHA SEHDEV VERMA


Compile Errors:

prog.cpp: In function 'int main()':


prog.cpp:29:9: error: request for member 'show' is ambiguous
object.show();
^
prog.cpp:8:8: note: candidates are: void A::show()
void show()
^
prog.cpp:8:8: note: void A::show()

VISHAKHA SEHDEV VERMA


To resolve this ambiguity when class A is inherited in both class B and class C, it is
declared as virtual base class by placing a keyword virtual as :

Syntax for Virtual Base Classes:

Syntax 1:
class B : virtual public A
{
};
Syntax 2:
class C : public virtual A
{
};

VISHAKHA SEHDEV VERMA


 virtual can be written before or after the public. Now only one copy of
data/function member will be copied to class C and class B and class A
becomes the virtual base class.
 Virtual base classes offer a way to save space and avoid ambiguities in class
hierarchies that use multiple inheritances.
 When a base class is specified as a virtual base, it can act as an indirect base
more than once without duplication of its data members. A single copy of its
data members is shared by all the base classes that use virtual base.

VISHAKHA SEHDEV VERMA


#include <iostream>
using namespace std;
class A {
public:
int a;
A() // constructor
{
a = 10;
}
};
class B : public virtual A {
};
class C : public virtual A {
};

VISHAKHA SEHDEV VERMA


class D : public B, public C {
};

int main()
{
D object; // object creation of class d
cout << "a = " << object.a << endl;

return 0;
}

VISHAKHA SEHDEV VERMA


Output
a = 10
Explanation :
The class A has just one data member a which is public. This class is virtually
inherited in class B and class C. Now class B and class C use the virtual base
class A and no duplication of data member a is done; Classes B and C share a
single copy of the members in the virtual base class A.

VISHAKHA SEHDEV VERMA


#include <iostream>
using namespace std;

class A {
public:
void show()
{
cout << "Hello from A \n";
}
};

class B : public virtual A {


};

VISHAKHA SEHDEV VERMA


class C : public virtual A {
};

class D : public B, public C {


};

int main()
{
D object;
object.show();
}

VISHAKHA SEHDEV VERMA


Output

Hello from A

VISHAKHA SEHDEV VERMA


Function Overriding
A function is a block of statements that together performs a specific task by
taking some input and producing a particular output.
Function overriding in C++ is termed as the redefinition of base class function in
its derived class with the same signature i.e. return type and parameters. It falls
under the category of Runtime Polymorphism.

VISHAKHA SEHDEV VERMA


Real-life example could be the relationship between RBI(The Reserve Bank of
India) and Other state banks like SBI, PNB, ICICI, etc. Where the RBI passes the
same regulatory function and others follow it as it is.

VISHAKHA SEHDEV VERMA


VISHAKHA SEHDEV VERMA
Syntax
class Parent{
access_modifier:
// overridden function
return_type name_of_the_function(){}
};
}
class child : public Parent {
access_modifier:
// overriding function
return_type name_of_the_function(){}
};
}
VISHAKHA SEHDEV VERMA
Advantages of Using Function Override in C++
 Polymorphism: Overriding allows a program to execute the appropriate
version of a function based on the object’s type during runtime, enhancing
flexibility and adaptability, thereby making it a backbone of polymorphism.
 Code reusability: Developers can reuse existing code by inheriting functions
from a base class and overriding them in derived classes. This promotes a
more efficient and organized code structure.
 Customization: Overriding enables the customization of inherited
functionality in derived classes. This is particularly useful when a specific
class requires a modified or enhanced version of a function inherited from its
parent class.

VISHAKHA SEHDEV VERMA


 Enhances code readability: The override function in C++ helps create class
hierarchies, promoting a structured and organized codebase. This hierarchical
arrangement simplifies code maintenance and readability.
 Keeping codes clean: With method overriding in C++, you can use the same
function name for different tasks, making the code cleaner. This reduces
confusion in naming and simplifies the code, making it easier to understand.
 Saves memory: Overriding enhances memory efficiency by avoiding
unnecessary duplication, ensuring a consistent and streamlined code
structure. This not only promotes clarity but also facilitates ease of
maintenance.

VISHAKHA SEHDEV VERMA


// C++ program to demonstrate function overriding

#include <iostream>
using namespace std;

class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};

VISHAKHA SEHDEV VERMA


class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
}
};

int main() {
Derived derived1;
derived1.print();
return 0;
}

VISHAKHA SEHDEV VERMA


Output
Derived Function

Explanation: Here, the same function print() is defined in both Base and Derived
classes.
So, when we call print() from the Derived object derived1, the print() from
Derived is executed by overriding the function in Base.

VISHAKHA SEHDEV VERMA


Working

VISHAKHA SEHDEV VERMA


As we can see, the function was overridden because we called the function
from an object of the Derived class.

Had we called the print() function from an object of the Base class, the
function would not have been overridden.

// Call function of Base class


Base base1;
base1.print(); // Output: Base Function

VISHAKHA SEHDEV VERMA


Composition vs classification
 An object is a basic unit of Object-Oriented Programming and represents real-
life entities. Complex objects are objects that are built from smaller or a
collection of objects.
 For example, a mobile phone is made up of various objects like a camera,
battery, screen, sensors, etc. This process of building complex objects from
simpler ones is called object composition.
 In object-oriented programming languages, object composition is used for
objects that have a “has-a” relationship with each other. Therefore, the
complex object is called the whole or a parent object whereas a simpler
object is often referred to as a child object.

VISHAKHA SEHDEV VERMA


Types of Object Compositions
Composition: The composition relationships are part-whole relationships where
a part can only be a part of one object at a time. This means that the part is
created when the object is created and destroyed when the object is destroyed.
To qualify as a composition, the object and a part must have the following
relationship-

 The part (member) is part of the object (class).


 The part (member) can only belong to one object (class).
 The part (member) has its existence managed by the object (class).
 The part (member) does not know about the existence of the object (class).

VISHAKHA SEHDEV VERMA


There are some variations on the rule of creating and destroying parts:
 A composition may avoid creating some parts until they are needed.
 A composition may opt to use a part that has been given to it as input
rather than creates the part itself.
 A composition may delegate the destruction of its parts to some other
object.

A composition relationship is represented in C++ as an object of one class being


contained within another class. The contained object is said to be a part of the
containing object, and it cannot exist independently of the containing object.
If the containing object is destroyed, the contained object is automatically
destroyed along with it.

VISHAKHA SEHDEV VERMA


For example, consider a class Car and a class Engine. If a car "has an" engine,
we can say that there is a composition relationship between the two classes.

class Engine {
// Class members and methods
};

class Car {
Engine engine;
// Class members and methods
};

VISHAKHA SEHDEV VERMA


Aggregation: The aggregation is also a part-whole relationship but here in
aggregation, the parts can belong to more than one object at a time, and the
whole object is not responsible for the existence of the parts. To qualify as
aggregation, a whole object and its part must have the following relationships:

 The part (member) is part of the object (class).


 The part (member) can belong to more than one object (class) at a time.
 The part (member) does not have its existence managed by the object (class).
 The part (member) does not know about the existence of the object (class).

VISHAKHA SEHDEV VERMA


Benefits of Object Composition:
 Reuse existing codes: Object composition allows to reuse of the existing code
without a need to model an is-a relationship as usually done in inheritance.
 Clean design APIs: Using object composition can help to design clean and
composed APIs. This is because when the class is composed it is easier to
decide if the referenced class will become part of the API or will be hidden.
 Change in implementation of the class used in the composition without
requiring external clients: Composition also allows to make code easier to
change and adapt if necessary. The internal classes can be changed without
any side effects and changes can be handled internally.

VISHAKHA SEHDEV VERMA


C++ Aggregation
 In C++, aggregation is a process in which one class defines another class as
any entity reference. It is another way to reuse the class. It is a form of
association that represents HAS-A relationship.
 In C++, Aggregation is used to represent the ‘HAS-A’ relationship between two
objects. It is a type of association. If in a process, one class defines another
class as any entity reference then it is known as Aggregation. With the help of
aggregation, you can also reuse the class.
 In an aggregation relationship, one class is a container for objects of another
class, but it is not responsible for the creation or destruction of those objects.
This relationship is often referred to as a “has-a” relationship, because one
class has objects of another class as members.
 An aggregation relationship is represented in C++ as an object of one class
containing pointers to objects of another class. The contained objects are
said to be part of the containing object, but they can exist independently of
the containing object. If the containing object is destroyed, the contained
objects are not automatically destroyed along with it.

VISHAKHA SEHDEV VERMA


An object should define the following relationships to qualify as an aggregation:-

 Must be a part of the class.


 The member can belong to one or more classes at a time.
 Member is unknown about the existence of the object.
 The relationship is unidirectional.

VISHAKHA SEHDEV VERMA


Implementing Aggregations in C++
 Compositional Nature:– Aggregation resembles composition. With a small
difference in semantics, both are implemented identically.
 Member Constraints:– You can also add parts as member variables in
aggregation. It also takes constructor parameters.
 Existence:– The parts will exist consequently. Class destruction can lead you
to member variable destruction.

VISHAKHA SEHDEV VERMA


Advantages of Aggregations in C++
 Aggregation represents unidirectional relation between the objects of 2
classes. It is a one-direction relation.
 Aggregation also helps in improving readability and reusability of the program
code.
 It helps in initiating the relation between objects of 2 classes where one class
is the Whole class and other is the part of the class. It is useful in
representing the HAS-A relation.
 Aggregation helps in making your program code more readable and
understandable to represent the relation.

VISHAKHA SEHDEV VERMA


#include <iostream>
using namespace std;
class Address {
public:
string addressLine, city, state;
Address(string addressLine, string city, string state)
{
this->addressLine = addressLine;
this->city = city;
this->state = state;
}
};

VISHAKHA SEHDEV VERMA


class Employee
{
private:
Address* address; //Employee HAS-A Address
public:
int id;
string name;
Employee(int id, string name, Address* address)
{
this->id = id;
this->name = name;
this->address = address;
}

VISHAKHA SEHDEV VERMA


void display()
{
cout<<id <<" "<<name<< " "<<
address->addressLine<< " "<< address->city<< " "<<address-
>state<<endl;
}
};
int main(void) {
Address a1= Address("C-146, Sec-15","Noida","UP");
Employee e1 = Employee(101,"Nakul",&a1);
e1.display();
return 0;
}

VISHAKHA SEHDEV VERMA


Output:

101 Nakul C-146, Sec-15 Noida UP

VISHAKHA SEHDEV VERMA


Constructor in derived class in C++
We can use constructors in derived classes in C++
 If the base class constructor does not have any arguments, there is no need
for any constructor in the derived class
 But if there are one or more arguments in the base class constructor, derived
class need to pass argument to the base class constructor
 If both base and derived classes have constructors, base class constructor is
executed first

VISHAKHA SEHDEV VERMA


Constructors in Multiple Inheritances
 In multiple inheritances, base classes are constructed in the order in which
they appear in the class deceleration.
 For example if there are three classes “A”, “B”, and “C”, and the class “C” is
inheriting classes “A” and “B”. If the class “A” is written before class “B”
then the constructor of class “A” will be executed first. But if the class “B” is
written before class “A” then the constructor of class “B” will be executed
first.
 In multilevel inheritance, the constructors are executed in the order of
inheritance.
 For example if there are three classes “A”, “B”, and “C”, and the class “B” is
inheriting classes “A” and the class “C” is inheriting classes “B”. Then the
constructor will run according to the order of inheritance such as the
constructor of class “A” will be called first then the constructor of class “B”
will be called and at the end constructor of class “C” will be called.

VISHAKHA SEHDEV VERMA


Special Syntax
 C++ supports a special syntax for passing arguments to multiple base classes
 The constructor of the derived class receives all the arguments at once and
then will pass the call to the respective base classes
 The body is called after the constructors is finished executing

VISHAKHA SEHDEV VERMA


// C++ program to implement
// constructor in multiple
// inheritance
#include<iostream>
using namespace std;
class A1
{

VISHAKHA SEHDEV VERMA


public:
A1()
{
cout << "Constructor of the base class A1 \n";
}

};

class A2
{
public:
A2()
{
cout << "Constructor of the base class A2 \n";
}

};

VISHAKHA SEHDEV VERMA


class S: public A1, virtual A2
{
public:
S(): A1(), A2()
{
cout << "Constructor of the derived class S \n";
}
};

// Driver code
int main()
{
S obj;
return 0;
}
VISHAKHA SEHDEV VERMA
Output
Constructor of the base class A2
Constructor of the base class A1
Constructor of the derived class S

VISHAKHA SEHDEV VERMA


Nesting of Classes
A nested class is a class that is declared in another class. The nested class is also
a member variable of the enclosing class and has the same access rights as the
other members. However, the member functions of the enclosing class have no
special access to the members of a nested class.

VISHAKHA SEHDEV VERMA


#include<iostream>
using namespace std;
class A {
public:
class B {
private:
int num;
public:
void getdata(int n) {
num = n;
}

VISHAKHA SEHDEV VERMA


void putdata() {
cout<<"The number is "<<num;
}
};
};
int main() {
cout<<"Nested classes in C++"<< endl;
A :: B obj;
obj.getdata(9);
obj.putdata();
return 0;
}

VISHAKHA SEHDEV VERMA


Output
Nested classes in C++
The number is 9

VISHAKHA SEHDEV VERMA


VISHAKHA SEHDEV VERMA

You might also like