C++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory.

Similar documents
The mechanism that allows us to extend the definition of a class without making any physical changes to the existing class is called inheritance.

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Inheritance, and Polymorphism.

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

Interview Questions of C++

More C++ : Vectors, Classes, Inheritance, Templates

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

Introduction Of Classes ( OOPS )

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

What is Class? Remember

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

Tokens, Expressions and Control Structures

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

Chapter 1: Object-Oriented Programming Using C++

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

Fast Introduction to Object Oriented Programming and C++

Polymorphism Part 1 1


SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

CS304 Object Oriented Programming Final Term

ECE 3574: Dynamic Polymorphism using Inheritance

AN OVERVIEW OF C++ 1

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Recharge (int, int, int); //constructor declared void disply();

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Friend Functions, Inheritance

C++ Classes, Constructor & Object Oriented Programming

C++ Quick Guide. Advertisements

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Object-Oriented Design (OOD) and C++

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Object Oriented Programming(OOP).

Lecture 5: Inheritance

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

Constructor - example

Pointers! Arizona State University 1

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

CS 162, Lecture 25: Exam II Review. 30 May 2018

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

OBJ. ORI.& MULT. PROG., M.C.Q. BANK, FOR UNIT -2, SECOND YEAR COMP. ENGG. SEM-4, 2012 PATTERN, U.O.P. UNIT-2

C++ Programming: Polymorphism

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

A A B U n i v e r s i t y

Classes and Objects. Class scope: - private members are only accessible by the class methods.

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FACULTY INFORMATION TECHNOLOGY AND COMMUNICATION (FTMK) BITE 1513 GAME PROGRAMMING I.

Data Structures using OOP C++ Lecture 3

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

PROGRAMMING IN C++ COURSE CONTENT

CS3157: Advanced Programming. Outline

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Module 10 Inheritance, Virtual Functions, and Polymorphism

C++ Important Questions with Answers

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

What is an algorithm?

CS304 Object Oriented Programming

COEN244: Class & function templates

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING CS6456 OBJECT ORIENTED PROGRAMMING

CS201- Introduction to Programming Current Quizzes


PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

Increases Program Structure which results in greater reliability. Polymorphism

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. 1

CLASSES AND OBJECTS IN JAVA

Instantiation of Template class

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

Module Operator Overloading and Type Conversion. Table of Contents

Sri Vidya College of Engineering & Technology

KLiC C++ Programming. (KLiC Certificate in C++ Programming)

Object Oriented Programming COP3330 / CGS5409

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Chapter 6 Inheritance Extending a Class

What is Pointer? Pointer is a variable that holds a memory address, usually location of another variable.

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Distributed Real-Time Control Systems. Lecture 14 Intro to C++ Part III

Introduction to Classes

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

G52CPP C++ Programming Lecture 13

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

Classes: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods.

Darshan Institute of Engineering & Technology for Diploma Studies

STRUCTURING OF PROGRAM

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

PROGRAMMING LANGUAGE 2

CPS 506 Comparative Programming Languages. Programming Language

COEN244: Polymorphism

Object-Oriented Programming

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

CS OBJECT ORIENTED PROGRAMMING

Syllabus of C++ Software for Hands-on Learning: This course offers the following modules: Module 1: Getting Started with C++ Programming

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming, numerics and optimization

C++ (classes) Hwansoo Han

Object Oriented Programming. Solved MCQs - Part 2

Transcription:

Pointer C++ Memory Map Once a program is compiled, C++ creates four logically distinct regions of memory: Code Area : Area to hold the compiled program code Data Area : Area to hold global variables Stack Area : Area to hold the return address of function calls, argument passed to the functions, local variables for functions and the current state of the CPU. Heap : Area from which the memory is dynamically allocated to the program. Accessing address of a variable Computer s memory is organized as a linear collection of bytes. Every byte in the computer s memory has an address. Each variable in program is stored at a unique address. We can use address operator & to get address of a variable: POINTER int num = 23; cout << &num; // prints address in hexadecimal A pointer is a variable that holds a memory address, usually the location of another variable in memory. Defining a Pointer Variable int *iptr; iptr can hold the address of an int Pointer Variables Assignment: int num = 25; int *iptr; iptr = &num; Memory layout To access num using iptr and indirection operator * cout << iptr; // prints 0x4a00 cout << *itptr; // prints 25 Similary, following declaration shows: char *cptr; float *fptr; cptr is a pointer to character and fptr is a pointer to float value.

Pointer Arithmetic Some arithmetic operators can be used with pointers: - Increment and decrement operators ++, -- - Integers can be added to or subtracted from pointers using the operators +, -, +=, and -= Each time a pointer is incremented by 1, it points to the memory location of the next element of its base type. If p is a character pointer then p++ will increment p by 1 byte. If p were an integer pointer its value on p++ would be incremented by 2 bytes. Pointers and Arrays Array name is base address of array int vals[] = 4, 7, 11; cout << vals; // displays 0x4a00 cout << vals[0]; // displays 4 Lets takes an example: int arr[]=4,7,11; int *ptr = arr; What is ptr + 1? It means (address in ptr) + (1 * size of an int) cout << *(ptr+1); // displays 7 cout << *(ptr+2); // displays 11 Array Access Array notation arr[i] is equivalent to the pointer notation *(arr + i) Assume the variable definitions int arr[]=4,7,11; int *ptr = arr; Examples of use of ++ and -- ptr++; // points at 7 ptr--; // now points at 4 Character Pointers and Strings Initialize to a character string. char* a = Hello ; a is pointer to the memory location where H is stored. Here a can be viewed as a character array of size 6, the only difference being that a can be reassigned another memory location.

char* a = Hello ; a *a gives H a[0] a++ *a++ gives address of H gives H gives address of e gives e Pointers as Function Parameters A pointer can be a parameter. It works like a reference parameter to allow change to argument from within function Pointers as Function Parameters void swap(int *x, int *y) int temp; temp = *x; *x = *y; *y = temp; swap(&num1, &num2); Pointers to Constants and Constant Pointers Pointer to a constant: cannot change the value that is pointed at Constant pointer: address in pointer cannot change once pointer is initialized Pointers to Structures We can create pointers to structure variables -or- struct Student int rollno; float fees;; Student stu1; Student *stuptr = &stu1; (*stuptr).rollno= 104; Use the form ptr->member: stuptr->rollno = 104; Static allocation of memory In the static memory allocation, the amount of memory to be allocated is predicted and preknown. This memory is allocated during the compilation itself. All the declared variables declared normally, are allocated memory statically. Dynamic allocation of memory

In the dynamic memory allocation, the amount of memory to be allocated is not known. This memory is allocated during run-time as and when required. The memory is dynamically allocated using new operator. Free store Free store is a pool of unallocated heap memory given to a program that is used by the program for dynamic allocation during execution. Dynamic Memory Allocation We can allocate storage for a variable while program is running by using new operator To allocate memory of type integer int *iptr=new int; To allocate array double *dptr = new double[25]; To allocate dynamic structure variables or objects Student sptr = new Student; Releasing Dynamic Memory Use delete to free dynamic memory delete iptr; To free dynamic array memory delete [] dptr; To free dynamic structure delete Student; Memory Leak //Student is tag name of structure If the objects, that are allocated memory dynamically, are not deleted using delete, the memory block remains occupied even at the end of the program. Such memory blocks are known as orphaned memory blocks. These orphaned memory blocks when increase in number, bring adverse effect on the system. This situation is called memory leak Self Referential Structure The self referential structures are structures that include an element that is a pointer to another structure of the same type. struct node int data;

node* next; OOP Concepts There are two common programming methods: procedural programming and object-oriented programming (OOP). So far you have been creating procedural programs. Procedural Programming In a procedural program data is typically stored in a collection of variables and there is a set of functions that perform operations on the data. The data and the functions are separate entities. Usually the variables are passed to the functions that perform the desired operations. As you might imagine, the focus of procedural programming is on creating the functions, or procedures, that operate on the program s data. Procedural programming works well. However, as programs become larger and more complex, the separation of a program s data and the code that operates on the data can lead to problems. Object Oriented programming The object oriented programming design models the real world well and overcomes the shortcomings of procedural paradigm. It views a problem in terms of objects and thus emphasizes on both procedures as well as data. An object is an entity that combines both data and procedures in a single unit. An object s data items, also referred to as its attributes, are stored in member variables. The procedures that an object performs are called its member functions. This wrapping of an object s data and procedures together is calledencapsulation. Not only objects encapsulate associated data and procedures, they also permit data hiding. Data hiding refers to an object s ability to hide its data from code outside the object. Only the object s member functions can directly access and make changes to the object s data. Advantages of Object oriented programming. Software complexity can be easily managed Object-oriented systems can be easily upgraded It is quite easy to partition the work in a project based on object

Class & Objects The mechanism that allows you to combine data and the function in a single unit is called a class. Once a class is defined, you can declare variables of that type. A class variable is called object or instance. In other words, a class would be the data type, and an object would be the variable. Classes are generally declared using the keyword class, with the following format: class class_name private: members1; protected: members2; members3; ; Where class_name is a valid identifier for the class. The body of the declaration can contain members, that can be either data or function declarations, The members of a class are classified into three categories: private, public, and protected. private, protected, and public are reserved words and are called member access specifiers. These specifiers modify the access rights that the members following them acquire. private members of a class are accessible only from within other members of the same class. You cannot access it outside of the class. protected members are accessible from members of their same class and also from members of their derived classes. Finally, public members are accessible from anywhere where the object is visible. By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before one other class specifier automatically has private access. Here is a complete example : class Circle private: double radius;

; void setradius(double r) radius = r; double getarea() return 3.14 * radius * radius; Object Declaration Once a class is defined, you can declare objects of that type. The syntax for declaring a object is the same as that for declaring any other variable. The following statements declare two objects of type circle: Circle c1, c2; Accessing Class Members Once an object of a class is declared, it can access the public members of the class. c1.setradius(2.5); Defining Member function of class You can define Functions inside the class as shown in above example. Member functions defined inside a class this way are created as inline functions by default. It is also possible to declare a function within a class but define it elsewhere. Functions defined outside the class are not normally inline. When we define a function outside the class we cannot reference them (directly) outside of the class. In order to reference these, we use the scope resolution operator, :: (double colon). In this example, we are defining function setradius outside the class: void Circle :: setradius(double r) radius = r; The following program demostrates the general feature of classes. Member funcitons setradius() and getarea() defined outside the class.

#include <iostream> using namespace std; class Circle //specify a class private : double radius; //class data members void setradius(double r); double getarea(); //member function to return area ; void Circle :: setradius(double r) radius = r; double Circle :: getarea() return 3.14 * radius * radius; int main() Circle c1; //define object of class circle c1.setradius(2.5); //call member function to initialize radius cout<<c1.getarea(); //display area of circle object return 0; Constructor and Destructor Constructor It is a member function having same name as it s class and which is used to initialize the objects of that class type with a legel initial value. Constructor is automatically called when object is created. Types of Constructor Default Constructor-: A constructor that accepts no parameters is known as default constructor. If no constructor is defined then the compiler supplies a default constructor. Circle :: Circle()

radius = 0; Parameterized Constructor -: A constructor that receives arguments/parameters, is called parameterized constructor. Circle :: Circle(double r) radius = r; Copy Constructor-: A constructor that initializes an object using values of another object passed to it as parameter, is called copy constructor. It creates the copy of the passed object. Circle :: Circle(Circle &t) radius = t.radius; There can be multiple constructors of the same class, provided they have different signatures. Destructor A destructor is a member function having sane name as that of its class preceded by ~(tilde) sign and which is used to destroy the objects that have been created by a constructor. It gets invoked when an object s scope is over. ~Circle() Example : In the following program constructors, destructor and other member functions are defined inside class definitions. Since we are using multiple constructor in class so this example also illustrates the concept of constructor overloading #include<iostream> using namespace std; class Circle //specify a class private : double radius; //class data members Circle() //default constructor radius = 0; Circle(double r) //parameterized constructor

; radius = r; Circle(Circle &t) //copy constructor radius = t.radius; void setradius(double r) //function to set data radius = r; double getarea() return 3.14 * radius * radius; ~Circle() //destructor int main() Circle c1; //defalut constructor invoked Circle c2(2.5); //parmeterized constructor invoked Circle c3(c2); //copy constructor invoked cout << c1.getarea()<<endl; cout << c2.getarea()<<endl; cout << c3.getarea()<<endl; return 0; Another way of Member initialization in constructors The constructor for this class could be defined, as usual, as: Circle :: Circle(double r) radius = r; It could also be defined using member initialization as: Circle :: Circle(double r) : radius(r) Time Class Case Study In the preceding section, we introduced many basic terms and concepts of C++ object oriented programming. In this section, we take a deeper look at classes. In this Time class case study we will demonstrate several class construction

features. We begin with a Time class that reviews several of the features presented in the preceding section. #include<iostream> #include<iomanip> using namespace std; class Time private : int hour; int minute; int second; public : //constructor with default value 0 Time(int h = 0, int m = 0, int s = 0); //setter function void settime(int h, int m, int s); //print description of object in hh:mm:ss void print(); //compare two time object bool equals(time); ; Time :: Time(int h, int m, int s) hour = h; minute = m; second = s; void Time :: settime(int h, int m, int s) hour = h; minute = m; second = s; void Time :: print() cout << setw(2) << setfill('0') << hour << ":" << setw(2) << setfill('0') << minute << ":" << setw(2) << setfill('0') << second << "\n"; bool Time :: equals(time othertime) if(hour == othertime.hour && minute == othertime.minute &&

else second == othertime.second) return true; return false; int main() Time t1(10, 50, 59); t1.print(); // 10:50:59 Time t2; //object created with default value t2.print(); // 00:00:00 t2.settime(6, 39, 9); //set the new time in object t2.print(); // 06:39:09 if(t1.equals(t2)) cout << "Two objects are equals\n"; else cout << "Two objects are not equals\n"; return 0; Output : 10:50:59 00:00:00 06:39:09 Two objects are not equals Let's us discuss our Time class and add some new concepts of programming Constructors with Default Arguments In Circle class we have created explicit default constructor and parameterized constructor. Compiler overloads constructor based on match. You can combine both statements in one as in Time class example //constructor with default value Time(int h = 0, int m = 0, int s = 0); It works same way just matter of styling code.

Constant Function In some cases, you will need that the member function should not change any private member variables of the calling object. You can do this by adding const to the end of the function declaration (prototype) and in the function definition. Let s make member functions in our Time class const if appropriate: class Time...... //print description of object in hh:mm:ss void print() const;...... ;...... void Time :: print() const cout << setw(2) << setfill('0') << hour << ":" << setw(2) << setfill('0') << minute << ":" << setw(2) << setfill('0') << second << "\n";... Constant Parameters You can make a parameter in a function as being a const parameter by preceding its type with const. This tells the compiler to disallow that parameter changing its value inside that function. This mechanism protects you from making inadvertent mistakes. Let s make parameter constant in our Time class, if appropriate: class Time... //constructor with default value 0 Time(const int h = 0, const int m = 0, const int s = 0); //setter function void settime(const int h, const int m, const int s);

;... Time :: Time(const int h, const int m, const int s) hour = h; minute = m; second = s; void Time :: settime(const int h, const int m, const int s) hour = h; minute = m; second = s;... Passing Objects to Functions Object can be passed by value, by reference or by pointer. In our Time class we passed object by value. bool Time :: equals(time othertime) if(hour == othertime.hour && minute == othertime.minute && second == othertime.second) return true; else return false; This means that equals() receives a copy of object t2 with name othertime. If a function needs to store or change data in an object s member variables, the object must be passed to it by reference. Constant Reference Parameters Passing by const reference is the preferred way to pass objects as an alternative to pass-by-value. When you pass by const reference, you take the argument in by reference, but cannot make any changes to the original object. //object passing by reference with const parameter bool equals(const Time&);

In next example, we'll apply these concept, also we will learn designing C++ programs in three separate files. Static Members of a Class In the previous sections we have shown examples of classes where each object of a class had its own set of data. Member function could access the object's own version of the data. In some situations it may be desirable that one or more common data fields should exist, which are accessible to all objects of the class. In C++, a static member is shared by all objects of the class. Static Data Members A data member of a class can be declared static; be it in the public or private part of the class definition. Such a data member is created and initialized only once. Static data members which are declared public can be accessed by using class name and the scope resolution operator. We only include the declaration of static data in the class declaration. Initialization of a static data-member is done outside the class. This is illustrated in the following code fragment: #include <iostream> using namespace std; class Circle private: double radius; // Radius of a circle static int count; // Constructor definition Circle(double r = 1.0) radius = r; // Increase every time object is created count++; double getarea()

; return 3.14 * radius * radius; // Initialize static member of class Circle int Circle::count = 0; int main() Circle c1(3.3); Circle c2(4.5); // Declare object c1 // Declare object c2 // Print total number of objects. cout << "Total objects: " << Circle::count << endl; return 0; Output: Total objects: 2 Static Member Functions The static functions can acess only the static data of a class. Similarly, static functions cannot call non-static functions of the class. Functions which are static and which are declared in the public section of a class can be called without specifying an object of the class. This is illustrated in the following code fragment: #include <iostream> using namespace std; class Circle private: static int count; double radius; // Radius of a circle // Constructor definition Circle(double r = 1.0) radius = r; // Increase every time object is created count++; double getarea()

; return 3.14 * radius * radius; static int getcount() return count; // Initialize static member of class Circle int Circle::count = 0; int main() Circle c1(3.3); Circle c2(4.5); // Declare object c1 // Declare object c2 // Print total number of objects. cout << "Total objects: " << Circle::getCount() << endl; return 0; Output: Total objects: 2 Friend Functions As we have seen in the previous sections, private and protected data or function members are normally only accessible by the code which is part of same class. However, situations may arise in which it is desirable to allow the explicit access to private members of class to other functions. If we want to declare an external function as friend of a class, thus allowing this function to have access to the private and protected members of this class, we do it by declaring a prototype of this external function within the class, and preceding it with the keyword friend. This is illustrated in the following code fragment: #include <iostream> using namespace std;

class Rectangle private : int length; int width; void setdata(int len, int wid) length = len; width = wid; int getarea() return length * width ; friend double getcost(rectangle); //friend of class Rectangle ; //friend function getcost can access private member of class double getcost (Rectangle rect) double cost; cost = rect.length * rect.width * 5; return cost; int main () Rectangle floor; floor.setdata(20,3); cout << "Expense " << getcost(floor) << endl; return 0; Output : Expense 300 The getcost function is a friend of Rectangle. From within that function we have been able to access the members length and width, which are private members. Friend Classes

One class memmber function can access the private and protected members of other class. We do it by declaring a class as friend of other class. This is illustrated in the following code fragment: #include <iostream> using namespace std; class CostCalculator; class Rectangle private : int length; int width; void setdata(int len, int wid) length = len; width = wid; int getarea() return length * width ; ; friend class CostCalculator; //friend of class Rectangle //friend class costcalculator can access private member of class Rectangle class CostCalculator public : double getcost (Rectangle rect) double cost; cost = rect.length * rect.width * 5; return cost; ; int main () Rectangle floor; floor.setdata(20,3); CostCalculator calc;

cout << "Expense " << calc.getcost(floor) << endl; return 0; Output : Expense 300 Note : An empty declaration of class costcalculator at top is necessary. Operator Overloading in C++ Operator overloading is giving new functionality to an existing operator. It means the behavior of operators when applied to objects of a class can be redefined. It is similar to overloading functions except the function name is replaced by the keyword operator followed by the operator s symbol. There are 5 operators that are forbidden to overload. They are ::..* sizeof?: In the following code fragment, we will overload binary + operator for Complex number class object. #include <iostream> using namespace std; class Complex private : double real; double imag; Complex () ; Complex (double, double); Complex operator + (Complex); void print(); ; Complex::Complex (double r, double i) real = r; imag = i;

Complex Complex::operator+ (Complex param) Complex temp; temp.real = real + param.real; temp.imag = imag + param.imag; return (temp); void Complex::print() cout << real << " + i" << imag << endl; int main () Complex c1 (3.1, 1.5); Complex c2 (1.2, 2.2); Complex c3; c3 = c1 + c2; //use overloaded + operator c1.print(); c2.print(); c3.print(); return 0; Output : 3.1 + i1.5 1.2 + i2.2 4.3 + i3.7 In C++ we can cause an operator to invoke a member function by giving that member function a special name (of the form: operator<symbol>). Hence for the sum operation, the special name is: operator+. So, by naming the member function operator+ we can call the function by statement c3 = c1 + c2 That is similiar to c3 = c1.operator+(c2);

Inheritance The mechanism that allows us to extend the definition of a class without making any physical changes to the existing class is inheritance. Inheritance lets you create new classes from existing class. Any new class that you create from an existing class is called derived class; existing class is called base class. The inheritance relationship enables a derived class to inherit features from its base class. Furthermore, the derived class can add new features of its own. Therefore, rather than create completely new classes from scratch, you can take advantage of inheritance and reduce software complexity. Forms of Inheritance Single Inheritance: It is the inheritance hierarchy wherein one derived class inherits from one base class. Multiple Inheritance: It is the inheritance hierarchy wherein one derived class inherits from multiple base class(es) Hierarchical Inheritance: It is the inheritance hierarchy wherein multiple subclasses inherit from one base class. Multilevel Inheritance: It is the inheritance hierarchy wherein subclass acts as a base class for other classes. Hybrid Inheritance: The inheritance hierarchy that reflects any legal combination of other four types of inheritance.

In order to derive a class from another, we use a colon (:) in the declaration of the derived class using the following format : class derived_class: memberaccessspecifier base_class... ; Where derived_class is the name of the derived class and base_class is the name of the class on which it is based. The member Access Specifier may be public, protected or private. This access specifier describes the access level for the members that are inherited from the base class. Member Access Specifier Private How Members of the Base Class Appear in the Derived Class Private members of the base class are inaccessible to the derived class. Protected members of the base class become private members of the derived class. Public members of the base class become private members of the derived class. Protected Private members of the base class are inaccessible to the derived class. Protected members of the base class become protected members of the derived class. Public members of the base class become protected members of the derived class. Public Private members of the base class are inaccessible to the derived class. Protected members of the base class become protected members of the derived class. Public members of the base class become public members of the derived class.

In principle, a derived classs inherits every member of a base class except constructor and destructor. It means private members are also become members of derived class. But they are inaccessible by the members of derived class. Following example further explains concept of inheritance : class Shape protected: float width, height; void set_data (float a, float b) width = a; height = b; ; class Rectangle: public Shape float area () return (width * height); ; class Triangle: public float area () Shape

; return (width * height / 2); int main () Rectangle rect; Triangle tri; rect.set_data (5,3); tri.set_data (2,5); cout << rect.area() << endl; cout << tri.area() << endl; return 0; output : 15 5 The object of the class Rectangle contains : width, height inherited from Shape becomes the protected member of Rectangle. set_data() inherited from Shape becomes the public member of Rectangle area is Rectangle s own public member The object of the class Triangle contains : width, height inherited from Shape becomes the protected member of Triangle. set_data() inherited from Shape becomes the public member of Triangle area is Triangle s own public member set_data () and area() are public members of derived class and can be accessed from outside class i.e. from main()

Constructor and inheritance The compiler automatically call a base class constructor before executing the derived class constructor. The compiler s default action is to call the default constructor in the base class. If you want to specify which of several base class constructors should be called during the creation of a derived class object. In these cases, you must explicitly specify which base class constructor should be called by the compiler. This is done by specifying the arguments to the selected base class constructor in the definition of the derived class constructor. class Rectangle private : float length; float width; Rectangle () length = 0; width = 0; Rectangle (float len, float wid) length = len; width = wid; ; float area() return length * width ; class Box : public Rectangle private : float height; Box () height = 0; Box (float len, float wid, float ht) : Rectangle(len, wid)

height = ht; ; float volume() return area() * height; int main () Box bx; Box cx(4,8,5); cout << bx.volume() << endl; cout << cx.volume() << endl; return 0; output : 0 160 Overriding Base Class Functions A derived class can override a member function of its base class by defining a derived class member function with the same name and parameter list. It is often useful for a derived class to define its own version of a member function inherited from its base class. This may be done to specialize the member function to the needs of the derived class. When this happens, the base class member function is said to be overridden by the derived class. class mother void display () cout << "mother: display function\n"; ; class daughter : public mother

; void display () cout << "daughter: display function\n\n"; int main () daughter rita; rita.display(); return 0; output: daughter: display function Gaining Access to an Overridden Function It is occasionally useful to be able to call the overridden version. This is done by using the scope resolution operator to specify the class of the overridden member function being accessed. class daughter : public mother void display () cout << "daughter: display function\n\n"; mother::display(); ; output: daughter: display function mother: display function Virtual Base Class Multipath inheritance may lead to duplication of inherited members from a

grandparent base class. This may be avoided by making the common base class a virtual base class. When a class is made a virtual base class, C++ + takes necessary care to see that only one copy of that class is inherited. class A...... ; class B1 : virtual public A...... ; class B2 : virtual public A...... ; class C : public B1, public B2...// only one copy of A...// will be inherited ; Polymorphism, Virtual Functions and Abstract Class

In C++, a pointer variable of a base class type can point to an object of its derived class. There are situations when this feature of C++ can be used to develop generic code for a variety of applications. Pointer of base class Consider the following program to understand pointer compatibility property #include <iostream> using namespace std; class Shape protected: double width, height; void set_data (double a, double b) width = a; height = b; ; class Rectangle: public Shape double area () return (width * height); ; int main () Shape *sptr; //declare pointer variables of type Shape Rectangle Rect; //create the object rect of type Rectangle sptr = &Rect; //make sptr point to the object rect. sptr->set_data (5,3); //set length and width of object rect cout << sptr -> area() << endl; //Compile Error!! return 0;

Notice that even though rectptr is poining to rect (object of type Rectangle), when the program executes, the statement sets length and width of rectangle. If you tried to access area function of class Rectangle with sptr it will give you compiler error. sptr -> area() is a compiler error! It means base class pointer can not access the additional member function of its derived class. If we want to do this we need to type cast the base class pointer. Using Type Casts with Base Class Pointers We can use a type cast to get the compiler to accept the statement: static_cast <Rectangle *> (sptr)->area() so we should write the statment cout << static_cast <Rectangle *> (sptr) -> area() << endl; The type cast informs the compiler that sptr is actually pointing to a Rectangle object derived from the Shape base class. In general, a pointer to a base class that actually points to a derived class object must first be appropriately cast before the additional features of the derived class can be used. Virtual Function and Polymorphism Virtual functions are used in C++ to support polymorphic behavior. We are modifing the above program and will introduce you the concept of virtual function by following example: #include <iostream> using namespace std; class Shape protected: double width, height; void set_data (double a, double b) width = a; height = b;

; virtual double area() return 0; class Rectangle: public Shape double area () return (width * height); ; int main () Shape *sptr; Rectangle Rect; sptr = &Rect; sptr -> set_data (5,3); cout << sptr -> area() << endl; return 0; Output : 15 A member of a class that can be redefined in its derived classes is known as a virtual member. In order to declare a member of a class as virtual, we must precede its declaration with the keyword virtual. The member function area() has been declared as virtual in the base class because it is later redefined in each derived class. The advantage of having virtual function is that we are able to access area function of derived class by pointer variable of base class. Pure Virtual Function and Abstract Class In above example, base class Shape member function area do not need any implementation because it is overriding in derived class. If this is the case, the C++ language permits the programmer to declare the function a pure virtual function. The C++ way of declaring a pure virtual function is to put the expression = 0 in the class declaration. For example, if a member function double area() is being declared pure virtual, then its declaration in its class looks like

virtual double area() = 0; A pure virtual function is sometimes called an abstract function, and a class with at least one pure virtual function is called an abstract class. The C++ compiler will not allow you to instantiate an abstract class. Abstract classes can only be subclassed: that is, you can only use them as base classes from which to derive other classes. A class derived from an abstract class inherits all functions in the base class, and will itself be an abstract class unless it overrides all the abstract functions it inherits. The usefulness of abstract classes lies in the fact that they define an interface that will then have to be supported by objects of all classes derived from it. #include <iostream> using namespace std; class Shape protected: double width, height; void set_data (double a, double b) width = a; height = b; virtual double area() = 0; ; class Rectangle: public Shape double area () return (width * height); ; class Triangle: public Shape double area () return (width * height)/2; ;

int main () Shape *sptr; Rectangle Rect; sptr = &Rect; sptr -> set_data (5,3); cout << "Area of Rectangle is " << sptr -> area() << endl; Triangle Tri; sptr = &Tri; sptr -> set_data (4,6); cout << "Area of Triangle is " << sptr -> area() << endl; return 0; Output : Area of Rectangle is 15 Area of Triangle is 12