St.
PAUL’S DEGREE & PG COLLEGE
(Affiliated to Osmania University)
Street No. 8, Himayathnagar, Hyderabad. Ph.No: 27602533
UNIT-IV
1) Explain about Inheritance? Explain the types of Inheritance?
In C++, inheritance is a process in which one object acquires all the properties and behaviors
of its parent object automatically. In such way, you can reuse, extend or modify the attributes
and behaviors which are defined in other class.
In C++, the class which inherits the members of another class is called derived class and the
class whose members are inherited is called base class. The derived class is the specialized
class for the base class.
Advantage:
Code reusability: Now you can reuse the members of your parent class. So, there is no
need to define the member again. So less code is required in the class.
It increases the code reliability by definite body to the program.
Types of Inheritance:
C++ supports five types of inheritance:
o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
o Hybrid inheritance
Defining Derived Classes:
A derived class is specified by defining its relationship with the base class in addition
to its own details. The general syntax of defining a derived class is as follows:
class derived_classname : Access specifier baseclass name
{
__
__ // members of derived class
};
The colon indicates that the a-class name is derived from the base class name. The access
specifier or the visibility mode is optional and, if present, may be public, private or
protected. By default, it is private. Visibility mode describes the status of derived features.
Single Inheritance: Single inheritance is defined as the inheritance in which a derived
class is inherited from the only one base class.
Where 'A' is the base class, and 'B' is the derived class.
Syntax: class subclass_name : access_mode base_class {
//body of subclass
};
Example:
#include<iostream>
using namespace std;
class Vehicle //base class
{ public: Vehicle( )
{ cout << "This is a Vehicle" << endl; } };
class Car: public Vehicle{ }; // sub class derived from two base classes
int main( ) {
Car obj;
return 0; }
Visibility modes can be classified into three categories:
o Public: When the member is declared as public, it is accessible to all the functions of
the program.
o Private: When the member is declared as private, it is accessible within the class only.
o Protected: When the member is declared as protected, it is accessible within its own
class as well as the class immediately derived from it.
Multilevel inheritance : Multilevel inheritance is a process of deriving a class from
another derived class.
Example:
#include<iostream>
using namespace std;
class Vehicle {
public: Vehicle( )
{ cout << "This is a Vehicle" << endl; } };
class fourWheeler: public Vehicle
{ public: fourWheeler( )
{ cout<<"Objects with 4 wheels are vehicles"<<endl;
}};
class Car: public fourWheeler{
public: Car( )
{ cout<<"Car has 4 Wheels"<<endl;
}};
int main( ) {
Car obj;
return 0; }
Multiple Inheritance: Multiple inheritance is the process of deriving a new class that
inherits the attributes from two or more classes.
Syntax: class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
//body of subclass
};
Example:
#include<iostream>
using namespace std;
class Vehicle {
public: Vehicle( ) {
cout << "This is a Vehicle" << endl; } };
class FourWheeler {
public: FourWheeler( ) {
cout << "This is a 4 wheeler Vehicle" << endl; } };
class Car: public Vehicle, public FourWheeler {
};
int main( ) {
Car obj;
return 0; }
Hierarchical Inheritance: Hierarchical inheritance is defined as the process of deriving
more than one class from a base class.
Example:
#include <iostream>
using namespace std;
// Base class (Parent)
class Animal {
public:
void eat() {
cout << "This animal eats food." << endl;
}
};
// Derived class 1
class Dog : public Animal {
public:
void bark() {
cout << "Dog barks." << endl;
}
};
// Derived class 2
class Cat : public Animal {
public:
void meow() {
cout << "Cat meows." << endl;
}
};
int main() {
Dog d;
Cat c;
d.eat(); // Inherited from Animal
d.bark(); // Own function
c.eat(); // Inherited from Animal
c.meow(); // Own function
return 0;
}
Hybrid Inheritance: Hybrid inheritance is a combination of more than one type of
inheritance.
Example:
#include<iostream>
class A {
public: int x; };
class B : public A {
public: B( )
{
x = 10;
} };
class C {
public: int y;
C( )
{
y = 4;
}};
class D: public B,public C {
public: void sum( )
{
std::cout<<”Sum = “<<x+y; }};
int main( )
{
D obj1;
obj1.sum( );
return 0;
}
2) What is Operator Overloading? Explain the rules for Overloading operators?
An operator is used to perform some particular operation on operands. But if we want to
add two objects which are instance of the class then compiler will show an error.
Basically operators will work only on predefined datatypes.
With the help of operator overloading we can add two user defined datatypes. Here
operators are used instead of functions to perform a particular operation.
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.
Rules for operator overloading:
Only built-in operators like (+, -, *, /, etc)can be overloaded.
We cannot overload all of those operators that are not a part of C++ language like ‘$’.
In operator overloading we are passing object as an argument.
We can’t change the meaning of an operator. Operator overloading never overrides the
existing behaviour of an operator. We can’t change the basic behaviour of an operator.
In Operator overloading the left hand side operand should be a user defined data type at
least one user defined datatype should be used.
Some operators cannot be overloaded they are : Scope resolution(::)
Member accessing(. , *)
Ternanry/conditional operator( ?:)
Sizeof( ) operator
The operator / member function should be the member of the same class.
3) Explain the overloading unary operators, Overloading binary operators?
Unary operator: It means performing operations on a single operand.
Eg: a++, --a
To implement operator overloading then we have to define operator function. Operator
function may be either member function or friend function.
If unary function is overloaded using member function, then 0 arguments needed where
as if unary operator is overloaded using friend function then one argument is needed.
Example: #include <iostream>
using namespace std;
class Count {
private: int value;
public: Count()
{ value = 5; }
void operator ++ ( ) { ++value;}
void display() { cout << "Count: " << value << endl; }};
int main() {
Count count1;
++count1; // Call the "void operator ++ ()" function
count1.display();
}
Binary operator: It means performing operations on two operands. If binary operator is
overloaded using member function then 1 argument is needed where as if binary operator is
overloaded using friend function then 2 arguments are needed.
Example:
#include <iostream>
using namespace std;
class Test { int a;
public: void get() {
cout << "Enter a value: ";
cin >> a; }
// Member function to compare 'a' of current object with another object
void compare(Test t2) {
if (a == t2.a)
cout << "Objects are equal";
else
cout << "Objects are not equal"; }};
int main( )
{
Test t1, t2;
cout << "Enter a value for t1: ";
t1.get();
cout << "Enter a value for t2: ";
t2.get();
t1.compare(t2); // Compare t1 with t2
return 0;}
4)What are pointers? Explain about declaring and initializing pointers and arithmetic
operations on pointers?
Pointers: Pointers are useful in order to store address of a variable.
Pointers are symbolic representation of addresses. They enable programs to
simulate call-by-reference as well as to create and manipulate dynamic data structures.
Features of pointers:
Pointers save memory space.
Memory is accessed efficiently with the pointers.
Execution time with pointers is faster because data are manipulated with the address.
Pointers are used with data structures. They are useful for representing 2-D,3-D arrays.
Pointers are used to allocate memory dynamically.
Advantages of pointers:
Pointers reduces code and improves the performance.
We can return multiple values from function using pointer.
It is used to access any memory location in the computer’s memory.
Declaring and Initializing pointers:
Pointer variables are declared like normal variables except for the addition of the unary ∗
character.
The general form of a pointer declaration is as follows:
Data_type ∗var_name;
where "Data_type" can be any valid C++ data type, and "var_name" is the name of the
pointer variable. The following declarations declare pointers of different types:
int ∗iptr; // creates an integer pointer iptr
char ∗cptr; // creates a character pointer cptr
float ∗fptr; // creates a float pointer fptr
The process of assigning address of a variable to a pointer variable. By using & address
of a variable is determined.
int a = 10;
int *ptr; //declaration
Ptr = &a; //initilization
Arithmetic operators on pointers:
We can perform arithmetic operations on pointer values. But when we perform
arithmetic operations on pointer variable, the result depends on the amount of memory
required by the variable to which the pointer is pointing.
In c++ we can perform the following arithmetic operations on pointers.
Addition
Subtraction
Increment
Decrement
Comparison
Addition Operation on Pointer:
The addition operation on pointer variables is calculated using formula
AddressAtPointer + (NumberToBeAdd * BytesOfMemoryRequiredByDatatype)
Example:
#include <iostream>
using namespace std;
int main() {
int a,*intptr;
intptr = &a;
intptr = intptr+3;
cout<<"int ptr value:"<<intptr;
}
Subtraction Operation on pointer:
The subtraction operation on pointer variables is calculated using the following
formula. Suppose if p = p – 2, it moves the pointer backward by 2 elements.
AddressAtPointer - (NumberToBeAdd * BytesOfMemoryRequiredByDatatype)
Example:
#include <iostream>
using namespace std;
int main() {
int a,*intptr;
intptr = &a;
intptr = intptr-3;
cout<<"int ptr value:"<<intptr;
}
Increment and Decrement Operation on Pointer:
The increment and decrement operations on pointer variable is calculated.‘p++’
means, the pointer will move to the next location of the array. Here the address inside the
pointer is 200. Then it will move to the next location.
‘p–‘ means, the pointer will move backward. Now, ‘p’ is on ‘202’ and then ‘p–‘ will
come on ‘200’.
The increment operation on pointer variable is calculated as follows
AddressAtPointer + NumberOfBytesRequiredByDatatype
The decrement operation on pointer variable is calculated as follows
AddressAtPointer - NumberOfBytesRequiredByDatatype
Example:
#include <iostream>
using namespace std;
int main() {
int a,*intptr;
float b,*floatptr;
intptr = &a;
floatptr= &b;
intptr++;
cout<<"int ptr value:"<<intptr;
floatptr--;
cout<<"\n float ptr value:"<<floatptr;
}
Comparison on Pointers:
The pointers may be compared by using the relational operators such as ==,< and >.
Example:
#include <iostream>
using namespace std;
int main() {
int *p2;
int *p1;
p2 = (int *)300;
p1 = (int *)200;
if(p1 > p2) {
cout<<"P1 is greater than p2";}
else {cout<<"P2 is greater than p1"; }
return(0);
}
5)Discuss about pointers with arrays, arrays of pointers, pointers to objects and ‘this’
pointer?
Pointers with arrays:
In C++ the name of an array is considered as a pointer i.e, the name of an array
contains the address of an element. C++ considers the array name as the address of the first
element.
Eg: If we create an array marks which hold the 20 values of integer type, then marks will
contain the address of first element i.e, marks[0].Therefore, that array name marks is a
pointer which is holding the address of the first element of an array.
Example:
#include <iostream>
using namespace std;
int main() { int *ptr;
int marks[10];
cout<<"Enter the elements of an array:";
for(int i= 0;i<10;i++) { cin>>marks[i]; }
ptr = marks;
cout<<"The value of *ptr is:"<<*ptr;
cout<<"The value of *matrix is:"<<*marks;
}
Arrays of pointers:
An array of pointers is an array that consists of variables of pointer type, which means
that the variable is a pointer addressing to some other element. Suppose we create an array of
pointer holding 5 integer pointers, then its declaration would look like.
int *ptr[5]; //arrray of 5 integer pointer
In the above declaration, we declare an array of pointer named as ptr, and it allocated
5 integer pointers in memory.
The element of an array of a pointer can also be initialized by assigning the address of
some other element.
int a; //Variable declaration.
Ptr[2] = &a;
In above code we are assigning the address of ‘a’ variable to the third element
of an array ‘ptr’.
Example:
#include<iostream>
int main()
{
int ptr1[5];
int *ptr2[5];
std::cout<<"Enter five numbers:";
for(int i = 0;i<5;i++) {
std::cin>>ptr1[i]; }
for(int i = 0;i<5;i++) {
ptr2[i]=&ptr1[i]; }
std::cout<<"The values are:";
for(int i = 0;i<5;i++)
std::cout<<*ptr2[i];
}
Pointers to objects:
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. At the time
when we don’t know how many objects to create then we can use new to create objects while
the program is running. new returns a pointer to an unnamed object.
Example:
#include<iostream>
using namespace std;
class num{
int a;
public:void read(){
cout<<"Enter a:";
cin>>a;}
void display(){
cout<<"\n a="<<a;} };
int main() {
num obj;
num *ptr;
ptr = &obj;
obj.read();
obj.display(); }
‘this’ pointer: In C++ programming, this is a keyword that refers to the current instance
of the class. By using this pointer, we can access the members of the current class
directly.
There are 3 main usages of this keyword in C++
It can be used to pass current object as a parameter to another method.
It can be used to refer current class instance variable.
It can be used to declare indexers.
The main advantage is to distinguish data members and member function arguments are
declared with same name compiler will get confused to avoid this problem to identify the
data member this pointer is used.
Every non static member of C++ is having a local variable called this.
All static members never contain this.
By default, this pointer returns the addresses in Hexadecimal format.
Syntax: this -> member-identifier
Example:
#include<iostream>
using namespace std;
class test {
int a, b;
public: void show(int a, int b) {
this->a = a;
this->b = b;
}
void display() {
cout << a << endl << b;
}};
int main() {
test t;
t.show(5, 10);
t.display();
return 0; }