What Is Access Control in Inheritance.: Base Class
What Is Access Control in Inheritance.: Base Class
Inheritance is the mechanism by which one class can inherit the properties of
another. When one class is inherited by another, the class that is inherited is
called the base class. The inheriting class is called the derived class. In general,
the process of inheritance begins with the definition of a base class. The base
class defines all qualities that will be common to any derived class, represent the
most general description of a set of traits. The derived class inherits those
general traits and adds properties that are specific to that class. When one class
inherits another, it uses this general form:
Base Class
Derived Class
Here access specifier is the way of inheriting base class properties by the derived
class. The access specifier /type of inheritance are : public, private, or protected.
This determines how elements of the base class are inherited by the derived
class. If access specifier is not mentioned , it takes private inheritance by default.
Outside yes no no
classes
Visibility mode/ Access control in Inheritance
The scope of inheritance of the data members and member functions from the
base class to the derived class is called visibility mode
.A derived class can access all the non-private members of its base class. Thus
base-class members that should not be accessible to the member functions of
derived classes should be declared private in the base class.
When deriving a class from a base class, the base class may be inherited
through public, protected or private inheritance. The type of inheritance is
specified by the access-specifier as explained above.
We hardly use protected or private inheritance, but public inheritance is
commonly used. While using different type of inheritance, following rules are
applied −
• Public Inheritance − When deriving a class from a public base
class, public members of the base class become public members of the
derived class and protected members of the base class
become protected members of the derived class. A base
class's private members are never accessible directly from a derived class,
but can be accessed through calls to the public and protected members of
the base class.
• Protected Inheritance − When deriving from a protected base
class, public and protected members of the base class
become protected members of the derived class.
• Private Inheritance − When deriving from a private base
class, public and protected members of the base class
become private members of the derived class.
We can summarize the different access types according to – the access
specifier
#include <iostream>
using namespace std;
// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
int main(void) {
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;}
o/p : 35
Types of Inheritance
class base_class
{
};
class derived_ class : visibility-mode base_ class
{
}
Multiple Inheritance:
The process in which a derived class inherits traits from several base classes, is
called multiple inheritance. In Multiple inheritance, there is only one derived
class and several base classes. We declare the base classes and derived class as
given below:
class base_class1
{
};
class base_class2
{
}
Class derived_ class : visibility-mode base_ class1, visibility-mode base_ class2
{
};
Hierarchical Inheritance:
The process in which traits of one class can be inherited by more than one class
is known as Hierarchical inheritance. The base class will include all the features
that are common to the derived classes. A derived classcan serve as a base class
for lower level classes and so on.
class base
{
};
class derived1 : visibility-mode base
{
}
Class derived2 : visibility-mode base
{
};
.
Multilevel Inheritance: he process in which a derived class inherits traits from
another derived class, is called Multilevel Inheritance. A derived class with
multilevel inheritance is declared as :
class base_class
{
};
class derived_ class1 : visibility-mode base_ class
{
};
class derived_ class 2: visibility-mode derived_ class1
{
};
Here, derived_ class 2 inherits traits from derived_ class 1 which itself inherits
from base_class..
Define Pointer.
type *var-name;
Here, type is the pointer’s base type. The base type determines what type of data
the pointer will be pointing to.
int a[]={10,20,30};
int *p;
p=a;
// Pointer moves to the next int position (as if it was an array)
Cout<<p++; //output is 10,display and increments the address
// Pointer moves to the next int position (as if it was an array)
Cout<<++p; //output is 30, increments the address and display
/* All the following three cases are same they increment the value
* of variable that the pointer p points.
*/
Cout<<++*p; //output is 31
Cout<<++(*p); //output is 32
Cout<<++*(p); //output is 33
Void Pointers
This is a special type of pointer available in C++ which represents absence of
type. void pointers are pointers that point to a value that has no type (and thus
also an undetermined length and undetermined dereferencing properties).
This means that void pointers have great flexibility as it can point to any data
type.
Example : void *ptr;
NULL Pointers
Null pointer is a pointer which point nowhere and not just an invalid address.
Following are 2 methods to assign a pointer as NULL;
int *ptr1 = 0;
Pointers to pointers
C++ allows the use of pointers that point to pointers, that these, in its turn, point
to data (or even to other pointers). The syntax simply requires an asterisk (*) for
each level of indirection in the declaration of the pointer:
char a;
char * b;
a = 'z';
char ** c;
b = &a;
c = &b;
This, assuming the randomly chosen memory locations for each variable of 7230,
8092, and 10502, could be represented as:
new operator
The new operator requests for the memory allocation in heap. If the sufficient
memory is available, it initializes the memory to the pointer variable and returns
its address.
Here is the syntax of new operator in C++ language,
pointer_variable = new datatype;
int *ptr1 = NULL;
ptr1 = new int;
Delete Operator
The delete operator is used to deallocate the memory. User has privilege to
deallocate the created pointer variable by this delete operator.
Here is the syntax of delete operator in C++ language,
delete pointer_variable;
delete ptr1
this pointer
Every object in C++ has access to its own address through an important pointer
called this pointer. The this pointer is an implicit parameter to all member
functions. this pointer holds the address of current object, this pointer points to
the current object of the class. Friend functions do not have a this pointer,
because friends are not members of a class. Only member functions have
a this pointer.
include <iostream>
class Box {
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume() {
return length * breadth * height;
}
int compare(Box box) {
return this->Volume() > box.Volume();
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
if(Box1.compare(Box2)) {
cout << "Box2 is smaller than Box1" <<endl;
} else {
cout << "Box2 is equal to or larger than Box1" <<endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Constructor called.
Constructor called.
Box2 is equal to or larger than Box1
POLYMORPHISM
Polymorphism in C++ is basically the ability for data to be processed or
represented in more than one form. Typically, polymorphism occurs when there is
a hierarchy of classes and they are related by inheritance.
Polymorphism allows the data in the form of a message or a group of statements
when executed to behave differently in different scenarios.
Function Overriding
To call the overridden function by using the object of child class. You can do that
by creating the child class object in such a way that the reference of parent class
points to it.
Eg.
include <iostream>
using namespace std;
class BaseClass {
public:
void disp(){
cout<<"Function of Parent Class";
}
};
class DerivedClass: public BaseClass{
public:
void disp() {
cout<<"Function of Child Class";
}
};
int main() {
/* Reference of base class pointing to
* the object of child class.
*/
BaseClass obj = DerivedClass();
obj.disp();
return 0;
}
#include<iostream>
using namespace std;
//Parent class or super class or base class
class Animal{
public:
virtual void animalSound(){
cout<<"This is a generic Function";
}
};
//child class or sub class or derived class
class Dog : public Animal{
public:
void animalSound(){
cout<<"Woof";
}
};
int main(){
Animal *obj;
obj = new Dog();
obj->animalSound();
return 0;
}
Pure Virtual Functions:
It's possible that you'd want to include a virtual function in a base class so that
it may be redefined in a derived class to suit the objects of that class, but that
there is no meaningful definition you could give for the function in the base
class. The pure virtual function is a function that has the notation "= 0" in
the declaration of that function.
#include<iostream>
using namespace std;
//Parent class or super class or base class
class Animal{
public:
virtual void animalSound()=0
};
//child class or sub class or derived class
class Dog : public Animal{
public:
void animalSound(){
cout<<"Woof";
}
};
int main(){
Animal *obj;
obj = new Dog();
obj->animalSound();
return 0;
}
Abstract class
When a class contains atleast one pure virtual function, it is referred to as an
abstract class. Since, an abstract class contains atleast one function for which
nobody exists, it is, technically, an incomplete type, and no objects of that class
can be created. Thus, abstract classes exist only to be inherited. We can still
create a pointer to an abstract class,
Unit – V
Stream.
It refers to a sequence of bytes. The C++ I/O system operates through streams. A
stream is logical device that either produces or consumes information. A stream
is linked to a physical device by the C++ I/O system.
Two types of streams:
Output stream: a stream that takes data from the program and sends (writes) it
to destination.
Input stream: a stream that extracts(reads) data from the source and sends it to
the program.
Types of files
Text file. It is a file that stores information in ASCII characters. In text files,
each line of text is terminated with a special character known as EOL (End of
Line) character or delimiter character. When this EOL character is read or
written, certain internal translations take place. It has extension as “.txt”
Binary file. It is a file that contains information in the same format as it is
held in memory. In binary files, no delimiters are used for a line and no
translations occur here. This has extension as “.dat”.
Opening a file
A file must be opened before you can read from it or write to it. Either ofstream or fstream object may
be used to open a file for writing. And ifstream object is used to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream, ifstream, and
ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the second
argument of the open() member function defines the mode in which the file should be opened.
Two methods of opening a file.
OPENING FILE USING CONSTRUCTOR
ofstream fout(“results”); //output only
ifstream fin(“data”); //input only
Closing File
When we are finished with our input and output operations on a file we shall close it. Then call the stream's
member function close. This member function takes flushes the associated buffers and closes the file:
fout.close();
fin.close();
File Modes:
File modes specify that, how file data will be read and write operation perform.
Mode
1. ios::in Open file for read only mode.
2. ios::out Open file for writing mode.
3. ios::app Append data to the end of file.
4. ios::ate Write data on the end of file and provide the
facility of modifying existing contents.
5. ios::binary Create the binary file.
6. ios::nocreate Open fail if file does not exist.
7. ios::noreplace Open fail if file already exist.
8. ios::trunc Delete all the contents of the file if it exists. It
will not create new file.
INPUT AND OUTPUT OPERATION
put() and get() function
the function put() writes a single character to the associated stream. Similarly,
the function get() reads a single character form the associated stream.
example :
file.get(ch);
file.put(ch);
int main()
{
ofstream fout;
fout.open("out.txt");
fout.close();
return 0;
}
int main()
{
ifstream fin;
fin.open("out.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
cout << ch;
}
fin.close();
return 0;
}
int main()
{
ifstream fin;
fin.open("out.txt");
ofstream fout;
fout.open("sample.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
fout << ch;
}
fin.close();
fout.close();
return 0;
}