Unit 2
Unit 2
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
#include<iostream>
using namespace std;
// class definition
class Circle
{
public:
double radius;
double compute_area()
{
return 3.14*radius*radius;
}
};
#include<iostream>
using namespace std;
class Circle
{
// private data member
private:
double radius;
};
// main function
#include<iostream>
using namespace std;
class Circle
{
// private data member
private:
double radius;
};
return 0;
}
// base class
class Parent
{
// protected data members
protected:
int id_protected;
};
Child obj1;
obj1.setId(81);
obj1.displayId();
return 0;
}
// create class A
class A
{
public:
void show()
{
cout << " It is the member function of class A " << endl;
}
};
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.
class A {
public:
void show()
{
cout << "Hello form A \n";
}
};
class B : public A {
};
int main()
{
D object;
object.show();
}
Syntax 1:
class B : virtual public A
{
};
Syntax 2:
class C : public virtual A
{
};
int main()
{
D object; // object creation of class d
cout << "a = " << object.a << endl;
return 0;
}
class A {
public:
void show()
{
cout << "Hello from A \n";
}
};
int main()
{
D object;
object.show();
}
Hello from A
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
int main() {
Derived derived1;
derived1.print();
return 0;
}
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.
Had we called the print() function from an object of the Base class, the
function would not have been overridden.
class Engine {
// Class members and methods
};
class Car {
Engine engine;
// Class members and methods
};
};
class A2
{
public:
A2()
{
cout << "Constructor of the base class A2 \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