Inheritance -Virtual Base Class
Inheritance -Virtual Base Class
The mechanism of deriving a new class from an old one is called inheritance or
derivation.
The old class is referred to as the base class and the new one is called the derived
class or sub class.
The derived class inherits some or all of the characteristics from the base class.
A class can also inherit properties from more than one class or from more than
one level.
Reusability is an important feature of OOP
A derived class can be defined by specifying its relationship with the base
class in addition to its own details.
The colon indicates that the derived class name is derived from the base-class-name.
the visibility mode is optional and if present, may be either private or protected or
public. The default is private. Visibility mode specifies whether the features of the
base class are privately derived or publicly derived.
{
members of ABC;
};
//private derivation
{
members of ABC;
};
//public derivation
// protected derivation
//members of ABC;
};
class ABC:XYZ //private by default
{
members of ABC;
};
When a base class is privately inherited by a derived class, public members of
the base class can only be accessed by the member functions of the derived
class.private membes of base class are inaccessible to the objects of the derived class
When a base class is protected inherited by a derived class, public members of
the base class can only be accessed by the member functions of the derived class.
Private membes of base class are inaccessible to the objects of the derived class. If
private members of base class are to be inherited to derived class then declare them as
protected
When the base class is publicly inherited, public members of the base class is
publicly inherited, public members of the base class become public members of the
derived class and therefore they are accessible to the objects of the derived class. In
both the cases, the private members are not inherited and therefore, the private
members of a base class will never become the members of its derived class
In inheritance, some of the base class data elements and member functions are
„inherited‟ into the derived class. We can add our own data and member functions and
thus extend the functionality of the base class. Inheritance, when used to modify and
extend the capability of the existing classes, becomes a very powerful tool for
incremental program development
Types of Inheritance:
1.Single Inheritance
2.Multi level Inheritance
3.Mutiple Inheritance
4.Hybrid inheritance
5. Hierarchical Inheritance.
1.SINGLE INHERITANCE:
one derived class inherits from only one base class. It is the most
simplest form of Inheritance. When a class inherits from a single base class,
it is known as single inheritance.
A / /Base class
B
//Derived class
Syntax:
#include<iostream.h>
class A
{
public:
int a,b;
void get()
{
cout<<"Enter any two Integer values"<<endl; cin>>a>>b;
}
};
class B:public A
{
int c;
public:
void add()
{
c=a+b;
cout<<a<<"+"<<b<<"="<<c;
}
};
int main()
{
B b;
b.get();
b.add();
}
Output:
Enter any two Integer
values 1 2
1+2=3
When the inheritance is such that, the class A serves as a base class for a derived
class B which in
turn serves as a base class for the derived class C. This type of inheritance is called
‘MULTILEVEL
INHERITENCE’. The class B is known as the ‘INTERMEDIATE BASE CLASS’
since it provides a
link for the inheritance between A and C. The chain ABC is called
‘ITNHERITENCE*PATH’ for
#include<iostream.h>
class A
{
public:
int a,b;
void get()
{
cout<<"Enter any two Integer values"<<endl; cin>>a>>b;
}
};
class B:public A
{
public:
int c;
void add()
{
c=a+b;
}
};
class C:public B
{
public:
void show()
{
cout<<a<<"+"<<b<<"="<<c;
}
};
int main()
{
C c;
c.get();
c.add();
c.show();
}
Output:
Enter any two Integer values 12 14
12+14=26
3.Multiple Inheritance:
In this type of inheritance a single derived class may
inherit from two or more than two base classes.
A class can inherit the attributes of two or more classes.
This mechanism is known as ‘MULTIPLE INHERITENCE’.
Multiple inheritance allows us to combine the features
of several existing classes as a starring point for defining
new classes.
It is like the child inheriting the physical feature of one
parent and the intelligence of another. The syntax of the
derived class is
as follows:
A B
C
Syntax:
#include<iostream.h>
class A
{
public:
int a;
void getA()
{
cout<<"Enter an Integer value"<<endl;
cin>>a;
}
};
class B
{
public:
int b;
void getB()
{
cout<<"Enter an Integer value"<<endl;
cin>>b;
}
};
class C:public A,public B
{
public:
int c;
void add()
{
c=a+b;
cout<<a<<"+"<<b<<"="<<c<<endl;
}
};
int main()
{
C obj;
obj.getA();
obj.getB();
obj.add();
}
Output:
Enter an Integer
value 12
Enter an
Integer value 13
12+13=25
Features of pointers:
Pointers save the memory space.
Execution time with pointer is faster. Because data is Manipulated with
the address.
The memory is accessed efficiently with the pointers.
Pointers are used with data structures.
A pointer declared to a base class could access the objects of derived
class.
Pointer declaration:
Pointer variable can be declared as,
datatype *var_name;
example:
int *x; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch; // pointer to character
Here int *x; is the integer pointer variable, and it informs the compiler that
it holds the address of any integer variable.
The indirection operator(*) is also called the deference operator. When a
pointer is dereferenced, the value at that address stored by the pointer is
retrieved.
Normal variables provide direct access to their own values but pointer in
directly accesses the value of a variable which it points.
int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable
return 0;
}
When the above code is compiled and executed, it produces result something as
follows −
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
Pointer to class
A pointer is a variable that holds the address of another
data variable. The variable may be of any data type i.e.,
int, float or double.
A class pointer is a pointer variable that stores address of an object of a
class.
We can also define pointer to class. When defining
pointer to the class, the starting address of the member
variables can be accessed. Such pointers are called class
pointers.
Example:
class book
{
char name[25];
char author[25];
int pages;
};
book *ptr;
using pointer to member variable is as follows:
ptr->name
ptr->author
ptr->pages
These three statements estimates the starting address of each member.
Example program1:
#include <iostream.h>
class Rectangle
{
private:
int length;
int breadth;
public:
Rectangle(int l, int b)
{
length=l;
breadth=b;
}
int getArea()
{
return 2*length*breadth;
}
};
int main()
{
// creating an object of Rectangle
Rectangle var1(5,2); // parameterized constrcutor
Output
Area of rectangle is: 20
Example program2:
include <iostream.h>
class Box {
public:
double Volume()
{
length=10.5;
breadth=20.0;
height=30.1;
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void)
{
Box Box1; // Declare box1
Box Box2; // Declare box2
Box *ptrBox; // Declare pointer to a class.
return 0;
}
When the above code is compiled and executed, it produces the following result −
Volume of Box1: 6300.1234
Volume of Box2: 6300.1234
Pointer to object
Like variables and class pointers, objects can also have an address. A
pointer can point to specified object.
A variable that holds an address value is called a pointer variable or
simply pointer.
Pointer can point to objects as well as to simple data types and arrays.
sometimes we do not know, at the time that we write the program , how
many objects we want to create. when this is the case we can use new to
create objects while the program is running. new returns a pointer to an
unnamed objects.
Example:
class Bill
{
int qty;
float price;
};
--------
--------
Bill s; //object
Bill *ptr=s;
--------
---------
Example program:
#include <iostream.h>
#include <conio.h>
class Bill
{
int qty;
float price,amount;
public:
void getdata(int a, float b, float c)
{
qty=a;
price=b;
amount=c;
}
void show()
{
cout<<”Quantity :”<<qty<<”\n”;
cout<<”Price :”<< price<<”\n”;
cout<<”Amount :”<<amount<<”\n”;
}
};
void main()
{
clrscr();
Bill s; // object
Bill *ptr=&s; // pointer to object
ptr->getdata(45,10.25,45*10.25);
*ptr.show();
}
_________________________________________________
#include <iostream>
#include <string>
using namespace std;
class student
{
private:
int rollno;
string name;
public:
student():rollno(0),name("")
{
}
student(int r, string n): rollno(r),name (n)
{
}
void get()
{
cout<<"enter roll no";
cin>>rollno;
cout<<"enter name";
cin>>name;
}
void print()
{
cout<<"roll no is "<<rollno;
cout<<"name is "<<name;
}
};
void main ()
{
student *ps=new student;
(*ps).get();
(*ps).print();
delete ps;
}
This pointer
In C++ programming, this is a keyword that refers to the
current instance of the class.
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.
Therefore, inside a member function, this may be used to refer to the
invoking object.
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>
int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}
Output:
x = 20
2) To return reference to the calling object
#include<iostream>
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0)
{
this->x = x;
this->y = y;
}
Test &setX(int a)
{
x = a;
return *this;
}
Test &setY(int b)
{
y = b;
return *this;
}
void print()
{
cout << "x = " << x << " y = " << y << endl;
}
};
int main()
{
Test obj1(5, 5);
obj1.print();
return 0;
}
Output:
x = 10 y = 20
Arrays in c++
Declaring Arrays
To declare an array in C++, the programmer specifies the type of the elements and
the number of elements required by an array as follows −
type arrayName [ arraySize ];
This is called a single-dimension array. The arraySize must be an integer constant
greater than zero and type can be any valid C++ data type. For example, to declare
a 10-element array called balance of type double, use this statement −
double balance[10];
Initializing Arrays
You can initialize C++ array elements either one by one or using a single statement
as follows −
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } can not be larger than the number of
elements that we declare for the array between square brackets [ ]. Following is an
example to assign a single element of the array −
If you omit the size of the array, an array just big enough to hold the initialization is
created. Therefore, if you write −
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0. Array
with 4th index will be 5th, i.e., last element because all arrays have 0 as the index of
their first element which is also called base index. Following is the pictorial
representaion of the same array we discussed above −
Live Demo
#include <iostream.h>
#include <iomanip.h>
int main () {
return 0;
}
This program makes use of setw() function to format the output. When the above
code is compiled and executed, it produces the following result −
Element Value
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
Volvo
BMW
Ford
Mazda
Two-Dimensional Arrays
The simplest form of the multidimensional array is the two-dimensional array.
A two-dimensional array is, in essence, a list of one-dimensional arrays.
To declare a two-dimensional integer array of size x,y, you would write
something as follows −
type arrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName will be a valid C++
identifier.
A two-dimensional array can be think as a table, which will have x number of rows
and y number of columns. A 2-dimensional array a, which contains three rows and
four columns can be shown as below −
Thus, every element in array a is identified by an element name of the form a[ i ]
[ j ], where a is the name of the array, and i and j are the subscripts that uniquely
identify each element in a.
int main () {
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
class class-name
{
datatype var1;
datatype var2;
----------
datatype varN;
method1();
method2();
----------
methodN();
};
#include<iostream.h>
#include<conio.h>
class Employee
{
int Id;
char Name[25];
int Age;
long Salary;
public:
void GetData() //Statement 1 : Defining GetData()
{
cout<<"\n\tEnter Employee Id : ";
cin>>Id;
};
void main()
{
int i;
for(i=0;i<3;i++)
{
cout<<"\nEnter details of "<<i+1<<" Employee";
E[i].GetData();
}
cout<<"\nDetails of Employees";
for(i=0;i<3;i++)
E[i].PutData();
Output :
Details of Employees
101 Suresh 29 45000
102 Mukesh 31 51000
103 Ramesh 28 47000
WORKING With OPERATOR OVERLOADING
OPERATOR OVERLOADING:-
Operator overloading provides a flexible option for the creation of new
definations for most
of the C++ operators. We can overload all the C++ operators except the
following:
Class members access operator (. , .*)
Scope resolution operator (: :)
Size operator(sizeof)
Condition operator (? :)
Although the semantics of an operator can be extended, we can't change its
syntax, the
grammatical rules that govern its use such as the no of operands precedence
and associativety. For
example the multiplication operator will enjoy higher precedence than the
addition operator.
When an operator is overloaded, its original meaning is not lost. For example,
the operator +, which has been overloaded to add two vectors, can still be
used to add two integers.
DEFINING OPERATOR OVERLOADING:
To define an additional task to an operator, we must specify what it means in
relation to the class to which the operator is applied . This is done with the
help of a special function
called operator function, which describes the task.
Syntax:-
return-type class-name :: operator op( arg-list)
{
function body
}
Where return type is the type of value returned by the specified operation and
op is the operator being overloaded. The op is preceded by the keyword
operator, operator op is the
function name.
operator functions must be either member function, or friend
function. A basic defference between them is that a friend function will have
only one argument for
unary operators and two for binary operators, This is because the object used
to invoke the member
function is passed implicitly and therefore is available for the member
functions. Arguments may be
either by value or by reference.
operator functions are declared in. the class using prototypes as follows:-
vector operator + (vector); /./ vector addition
vector operator-( ); //unary minus
friend vector operator + (vuelor, vector); // vector add
friend vector operator -(vector); // unary minus
vector operator - ( vector &a); // substraction
int operator = =(vector); //comparision
friend int operator = =(vector ,vrctor); // comparision
vector is a data type of class and may represent both magnitude and direction
or a series
of points called elements.
The process of overloading involves the following steps:-
1. Create a class that defines the data type that is used in the overloading
operation.
2. Declare the operator function operator op() in the public part of the class
3. It may be either a member function or friend function.
4. Define the operator function to implement the required operations.
Overloaded operator functions can be invoked by expressions such as
op x or x op;
for unary operators and
x op y
for binary opearators.
operator op(x);
for unary operator using friend function
operator op(x,y);
for binary operator usinf friend function.
Unary – operator overloading(using member function):
class abc
{
int m,n;
public:
abc()
{
m=8;
n=9;
}
void show()
{
cout<<m<<n;
}
operator -- ()
{
--m;
--n;
}
};
void main()
{
abc x;
x.show();
--x;
x.show();
}
Unary – - operator overloading(using friend function):
class abc
{
int m,n;
public:
abc()
{
m=8;
n=9;
}
void show()
{
cout<<m<<n;
}
friend operator --(abc &p);
};
operator -- (abc &p)
{
--p.m;
--p.n;
}
};
void main()
{
abc x;
x.show();
operator--(x);
x.show();
}
C++ has the ability to provide the operators with as special meaning for a data type. The mechanism
of giving such special meanings to an operator is known as operator overloading
To define an additional task to an operator, specify what it means in relation to
the class to which
the operator is applied. This is done with the help of a special function, called
operator function.
The process of overloading involves following steps:
1. Create a class that defines the data type that is to be used in the overloading
operation.
2. Declare the operator function operator op() in the public part of the class. It
may be a member
function or a friend function.
3. Here op is the operator to be overloaded.
4. Define the operator function to implement the required operations.
General Form:-
return-type classname :: operator op(arglist)
{
Function body
}
Applying overloading to operators means,
same operator in responding different manner. For example operator + can be
used as concatenate
operator as well as additional operator.
That is 2+3 means 5 (addition), where as
"2"+"3" means 23 (concatenation).
Performing many actions with a single operator is operator overloading. We
can assign a user
defined function to an operator. We can change function of an operator, but it
is not recommedned to
change the actual functions of operator. We can't create new operators using
this operatorloading.
Operator overloading concept can be applied in following two major areas
(Benefits)
1. Extension of usage of operators
2. Data conversions
Rules to be followed for operator overloading:-
1.Only existing operators can be overloaded.
2.Overloaded operators must have at least one operand that is of user defined
operators
3.We cannot change basic meaning of an operator.
4.Overloaded operator must follow minimum characteristics that of original
operator
5.When using binary operator overloading through member function, the left
hand operand must be
an object of relevant class
The number of arguments in the overloaded operator‟ s arguments list
depends
1. Operator function must be either member function or friend function.
2. If operator function is a friend function then it will have one argument
for unary operator& two arguments for binary operator
3. . If operator function is a member function then it will have Zero
argument for unary
4. operator & one arguments for binary operator