Access Modifier In C++
A pure
virtual function (or abstract function) in C++ is a virtual function for which we don’t have implementation,
we only declare it. A pure virtual function is declared by assigning 0 in
declaration.
Access
Modifiers or Access Specifiers in a class are used to set
the accessibility of the class members.
There
are 3 types of access modifiers available in C++:
1.
Public
2.
Private
3.
Protected
1.
Public:
All the class members declared under public will be available to everyone. The data members and member functions declared public can be accessed by other classes 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.
Syntax:
class base class
{
private:
-----------
public:
------------
protected:
-------------
};
class
derived class: public base class
{
private:
-----------
public:
------------
};
Program:
#include<iostream.h>
#include<conio.h>
class
bca
{
public:
void
output()
{
cout<<”base
class “;
}
};
class
mca: public bca
{
public:
void
output1()
{
cout<<”derived
class”;
}
};
void
main()
{
Mca
a1;
a1.output();
getch();
}
Output:
Base
class
2.Private:
The class members declared as private can
be accessed only by the 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 function are allowed to
access the private data members of a class.
Syntax:
class base class
{
private:
-----------
public:
------------
protected:
-------------
};
class
derived class: public base class
{
protected:
-----------
public:
------------
};
Program:
#include<iostream.h>
#include<conio.h>
class
bca
{
private:
void
output()
{
cout<<”base
class “;
}
};
class
mca: public bca
{
public:
void
output1()
{
cout<<”derived
class”;
}
};
void
main()
{
Mca
a1;
a1.output1();
getch();
}
Output:
Derived class
3.Protected:
Protected access modifier is similar
to that of private access modifiers, the difference is that the class member
declared as Protected are inaccessible outside the class but they can be
accessed by any subclass(derived class) of that class.
Syntax:
class base class
{
private:
-----------
public:
------------
protected:
-------------
};
class
derived class: public base class
{
protected:
-----------
public:
------------
};
Program:
#include<iostream.h>
#include<conio.h>
class
bca
{
protected:
void
output()
{
cout<<”base
class “;
}
};
class
mca: public bca
{
public:
void
output1()
{
cout<<”derived
class”;
}
};
void
main()
{
Mca
a1;
a1.output1();
getch();
}
Output:
Derived class
No comments:
Post a Comment