Prof B R Mohan SSE www bookspar com
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES OBJECT ORIENTED PROGRAMMING WITH C++ B. R. MOHAN CSE DEPT SSE, MUKKA
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Text Book 1. Object oriented Programming with C++, Sourav Sahay, Oxford Press, 2006 (chapters 1 -10) Reference Books 1. C++ Primer, Stanley Lipmann, Josee Lajoie, Barbara E. Moo, 4 th Edition, Addison Wesley, 2005 2. The Complete Reference C++, Herbert Schildt, 4 th Edition, TMH, 2005
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Unit-1: 1. Introduction to C++ 2. Class and Object Unit-2: 3. Class & Objects contd. Unit-3: 4. Dynamic Memory Management 5. Constructors and Destructors
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Unit-4: 6. Inheritance Unit-5: 7. Virtual Functions & Dynamic Polymorphism Stream Handling Unit-6 9. Stream Handling contd 10. Operator Overloading 8.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Unit-7: 11. Operator Overloading contd. Unit-8: 12. Type Conversion, New style casts, and RTTI 13. Templates FT, CT, STL 14. Exception Handling
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Here we see how to program in C++ - a language that support object oriented programming. Reference – Robert Lafore Key concepts in OOPs – Objects and Classes Oops came into existence due to the limitations discovered in procedural languages.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Procedural Languages – Pascal, C, Basic, Fortran are examples of procedural languages. lays emphasis on executing a set of instructions. -Get some input -Add these numbers -divide by 6 -display the results
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES • A program in procedural language is a list of instructions. For small programs, no other organizing principle is needed. • As program grows larger, it becomes difficult to comprehend. Hence Divide the large program into a number of functions. A Function has a clearly defined purpose and a well defined interface.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Dividing a function into a number of functions can be extended to grouping a number of functions into a larger entity called Module. 2. Dividing a program into functions and modules is one of the cornerstone of Structured Programming( other features include loops and other control structures). 3. As program grow even larger , structured programming signs of strain. 1.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Drawbacks/Disadvantages of Procedural languages. 1. Data is undervalued – given II class status in program organization of procedural languages. 2. Since many functions in a program can access global data / global variables, global data can be corrupted by that have no business to change it. Global variables constitute data are declared outside any function so that they are accessible to all functions
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Since many functions access the same data, the way data is arranged becomes critical. • Data arrangement cannot be changed without modifying the functions that access it. If u add new data items , we need to modify all the functions that access the data so that they can also access these new items
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Global Variable Accessible by Function A Local Var Function A Accessible by any function Accessible by Function B Local Var Function B
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Global. Data Fn A Global Data Fn A
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Hence we need a way to restrict the access to the data , to hide it from all but a few critical functions. This protects the data, simplifies the maintainence and other benefits. Object Oriented Approach Idea of Object Oriented Language – data and the functions that access the data are combined into a single unit called OBJECT. An objects functions are called Member functions in C++. MFs provide only way to access data.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES How to read a data item in an object ? • Call the mf of the object and it will read the data item and return the value to u. • Data cant be accessed directly, it is hidden within the object and safe from accidental alterations. • Data and functions are said to be encapsulated in an object. • Data Encapsulation & Data Hiding are the key terms in OOPs
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES • OOPs simplify writing , debugging and maintaining the program. • C++ prg typically contain a number of objects interacting with each other by calling one another’s member functions.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Organization Of a C++ Program Fig – Object Oriented Paradigm object Data MF MF Object Data MF MF
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Corporate Paradigm CSE Dept Sales Data Sales Manager Secretary Finance Dept Personnel Data Personnel Manager Personnel Staff Finance Data Finance Manager Financial Assistant
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES There is a close match between programming sense & objects in real world Classes – Objects are instances / members of a class. Eg- All programming languages have built in data types like int, char, float, etc. Similarly u can have objects of same class as shown
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES A Class serves as a plan / template like structure, specifies what data & functions will be included in objects of the class. Fig- A Class & its Objects Class Circle Feature A Feature B Object 1 Feature C Specifications for class Circle Class Circle Feature A Feature B Feature C Object 2 Object 3 Class Circle Feature A Feature B Feature C
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Object 1, Object 2 and Object 3 are all objects of a Class Circle that are similar to i, j, k are of integer data type in C language. Saimple programs are given in VC++ D:
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES C++ Program execution Execution starts from main( ). smallobj s 1, s 2; Defines 2 objects s 1, s 2, of class smallobj. Class smallobj doesn’t create any objects , but describes how they look when they are created. Space is set aside for it in memory. S 1. setdata(1066) ; //causes somedata set to 1066. -> class member acess operator connects object name and member function
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES C++ introduces a new keyword class as a substitute for keyword structure members are public by default
Struct Distance { private: int i. Feet; float f. Inches; Public: void set. Feet(int x) { i. Feet=x; } float get. Feet() { return i. Feet; } int set. Inches(float y) { f. Inches = y; } float get. Inches() { return f. Inches; } }; Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES This can also be written as given in next slide
Struct Distance { private: int i. Feet; float f. Inches; void set. Feet(int x) { i. Feet=x; } float get. Feet() { return i. Feet; } int set. Inches(float y) { f. Inches = y; } float get. Inches() { return f. Inches; } }; Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES //All member functions are public by default
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES class members are private by default
class Distance { Private: int i. Feet; float f. Inches; Public: void set. Feet(int x) { i. Feet=x; } float get. Feet() { return i. Feet; } int set. Inches(float y) { f. Inches = y; } float get. Inches() { return f. Inches; } }; Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES class members are private by default
class Distance { Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES int i. Feet; //private by default float f. Inches; //private by default Public: void set. Feet(int x) { i. Feet=x; } float get. Feet() { return i. Feet; } int set. Inches(float y) { f. Inches = y; } float get. Inches() { return f. Inches; } };
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Classes and Objects Classes contain Data and Functions Class Data 1 Data 2 Data 3 Data Function Fn 1 Fn 2 Fn 3
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Class can contain private and public. Usually the data within the class is private and the functions that operate on data are public so that they can be accessed from outside the class. Fig- for public & private Class Not accessible From outside Class Accessible from Outside class private Data or Functions public Data or Functions
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Syntax of a Class Specifier Class Circle name of class { class is a keyword private: int data; private functions & data public: void Display. Radius( ); void Calc. Area( ); public functions & data void Calc. Circum( ); };
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Differences between C and C++ In C, u may / may not Include function Prototypes In C++, you must include function prototypes. C++ lets you specify default values for function‘s parameters
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES C++ lets you specify default values for function‘s parameters in the function’s protoype
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Egvoid x=3, int y=4) In myfunction(int C, the declaration Of a variable must be at the beginning Of the function In C++, u may place the variable declara tions close to the statements that use variables before using it in a statement
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES If a C program uses a Local variable that has Same name as global Variable, then C program uses the value of a local variable. In C++, u can instruct prgm to use value of global variable with scope Resolution operator Egcout << “Iam global var : ” << : : I;
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Lab Program-1 1. Given that Employee class contains following members: employeeno. , empname, basic , da, it, Netsalary and to print data members. Write a C++ program to read the data of n employees and compute netsalary of each employee. (da=52%of basic and it =30% of gross salary, netsalary=basic+da-it)
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES • 1. 2. 3. 4. • • • Steps : Define an Employee class and declare the given data members. Get the employee details using the member function calculate netsalary of given employee using formula display the resultant value write the main function and create Employee objects. Call member functions on the employee objects to read the data , to calculate netsalary and to print the data members Class: The class is a fundamental OOP concept in C++. A class declaration defines a new type that links code(functions/operations) and data. This new type is then used to declare objects of that class.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES • The class is a fundamental OOP concept in C++. A class declaration defines a new type that links code(functions/operations) and data. • This new type is then used to declare objects of that class. Hence , a class is a logical abstraction, but a physical existence. •
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Syntax: class name object name. datamember; //access class members object name. datamember; //calling mf on an object Access specifiers: public: allows fns / data to be accessible to other parts of ur Prg private: by default fucntions and data declared within a class are private to that class and may be accessed only by public members of the same class.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Class definition follows Class Employee{ //declare data members here int empno; char empname[25]; float basic, da, it, netsal; public: void getdata(); void computenetsal(); void display(); };
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Member functions void employee: : getdata() { //get emp details} void employee: : computenetsal() { da=0. 52*basic; gross=basic-da; it=0. 3*gross; //compute netsal=basic+da-it; }
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Void employee: : display() { //display employee info on the monitor }
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES 2. Define a student class with Usn, name , marks in 3 tests of a subject. Declare an array of 10 student objects. Using appropriate functions, find average of 2 better marks for each student. Print usn, name and average marks of all students.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Steps For II Programs 1. 2. 3. 4. Define a Student class and declare the given members. Get the Student details using member functions to get data Find the average of 2 better marks for each student Display resultant values – usn, name and average marks of all students
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES 5. Write main() function and create an array of 10 student objects. Call member functions on student objects to read data to calculate average marks and to print the student details along with average marks.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Steps 1. Define a student class and declare the given data members 2. Get the student details using member functiongetdata() 3. Find average of 2 better marks for each student 4. Display the resultant values-usn, name and average marks of all students 5. Write a main() & create an array of 10 student objects. Call mfs of student objects to read data, to calculate average marks & print the student details along with their avg mks
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Lab Program-3 • Write a C++ program to create a class called COMPLEX and implement following overloading functions ADD that return a COMPLEX number. i) ADD(a, s 2) - where a is an integer (real part) and s 2 is a complex number. ii) ADD(s 1, s 2) – where s 1, s 2 are complex numbers
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Steps for LAB PRG III Constructor : 1. Create a user defined datatype named as COMPLEX. Declare the data members. 2. Initialize data members with default values. This is a default constructor automatically invoked when an object of type COMPLEX is defined / created.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES 3. Or initialize the data members with default values specified while creating the object. This is a Parameterized constructor, automatically invoked when some initial values are passed as parameters while creating an object. 4. Add an integer with a COMPLEX value 5. Add 2 COMPLEX objects overloading the ADD function
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES 6. 7. Display the results directly or by overloading << operator Write a main() function and call member functions on the COMPLEX objects as required by the end user.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Friend Function If u want to explicitly grant access to a function that is not a member of current class, declare that function a friend inside the class / structure declaration. Friend declaration occurs inside the class because compiler reads class definition, size and behaviour of data type
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES • Who can access my private implementation ? Only friend functions can access private Implementations U cant break in from outside if u are not a friend. Hence the operator << is overloaded to print the complex number.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Friend Functions It is possible to grant nonmember function access to the private members of a class by using a friend. Friend function has access to all private and protected members of the class for which it is a friend. To declare a friend , include its prototype within the class, preceding it with keyword friend
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES OBJECT ORIENTED PROGRAMMING WITH C++ REVIEW OF STRUCTURES
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES To understand procedural oriented languages, we need to review structure concept Need for Structures – value of 1 variable depends on the value of another variable. Eg- Date can be programmatically represented in C by 3 different int variables. Say int d, m, y; d-date, m-month, y-year
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Although 3 variables are not grouped in a code, they actually belong to the same group. The value of 1 may influence the value of other. Consider a function nextday( ) that accepts the addresses of 3 integers that represent a date and changes these values to represent next day
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Prototype of this function //for calculating the next day void nextday(int *, int *); Suppose d=1; m=1; y=2002; //1 st january 2002 If we call nextday( &d, &m, &y); D becomes 2, m=1, y=2002
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES But if d=28; m=2; y=1999; //28 th Feb 1999 and we call the function as nextday( &d, &m, &y); d becomes 1, m will become 3 and y will become 1999.
Again if Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES d=31; m=12; y=1999; //31 th Dec 1999 and we call the function as nextday( &d, &m, &y); d will become 1 , m will become 1 and y becomes 2000. A change in 1 variable may change the value of other 2. No language construct exist that actually places them in same group.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Members of wrong group may be accidentally sent to the function d 1=28; d 2=19; m 1=2; y 1=1999; //28 thfeb 99 m 2=3; y 2=1999; //19 thmrch 99 nextday(&d 1, &m 1, &y 1); //ok nextday(&d 1, &m 2, &y 2); //incorrect set passed Above listing show problems in passing groups of programmatically independent but logically dependent variables
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES There is nothing in language itself that prevents the wrong set of variables from being sent to the function. Suppose nextday() accepts an array as parameter, Then its prototype will be void nextday(int *); Let us declare date as an array of 3 integers. int date[3]; date[0]=28; date[1]=2 date[2]=1999; //28 th Feb 1999
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Let us call the function as follows nextday(date); The values of date[0], date[1], date[2] is set to 1, 3 and 1999, respectively. This method is not convincing. There is no data type of date itself. The solution to this problem is to create a datatype called date itself using structures.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Struct date d 1; d 1. d=28; d 1. m=2; //Need for structures d 1. y=1999; nextday(&d 1); d 1. d, d 1. m, d 1. y will be set correctly to 1, 3, 1999, since the function takes the address of an entire structure variable as parameter at a time as there is no chance of variables of different groups being sent to the function. Structure is a programming construct in C that allows us to put the variables together
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Library programmers use structures to create new datatypes. Application programs use these new datatypes by declaring variables of this data type struct date d 1; They call associated functions by passing these variables / addresses to them. d 1. d=31; d 1. m=12; d 1. y=2003; Nextday(&d 1);
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES They use resultant value of the passed variable further as per requirement printf(“The next day is: %d /%d/%dn”, d 1. d, d 1. m, d 1. y); O/P- The next day is: 01/01/2004
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Creating a New Data Type using Structures Creation of a new datatype is a 3 step process. 1. Put structure definition and prototypes of associated functions in a header file. 2. Put the definition of associated functions in a source code and create a library.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES 3. Provide the header file and library in any media to other programmers who want to use this new data type. Creating a structure and its associated functions are 2 steps to constitute one complete process
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES 1. Putting structure definition and prototypes of associated functions in a header file. //date. h contains structure definition & // prototypes of associated functions Struct date { int d, m, y; } Void nextday(struct date *); Void getsysdate(struct date *);
2. Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES put definition and other prototypes in a source code and create a library #include “date. h” Void nextday(struct date *p) {//calculate date represented by *p and set it to *p} Void getsysdate(struct date *p){ // determine //current system date & set it to *p} //definitions of other useful & other relevant //functions to work upon vars of date structure
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Using Structures in Application Programs is a 3 step procedure Include header file provided by programmer in the source code. 2. Declare variables of new data type in the source code 3. Embed calls to the associated functions by passing these variables in the source code 1.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Compile the Source code to get the object file. 5. Link the Object file with the library provided by the library programmer to get the executable or another library. 4.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Step 1 -Include the header file provided programmer in the source code //beginning of dateuser. c #include “date. h” void main() { … … } //end of dateuser. c by the
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES 2. Declare variables of new data type source code. //beginning of dateuser. c #include “date. h” void main() { struct date d; … … } //end of dateuser. c in the
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES 3. Embed calls to associated functions by passing these variables in source code //beginning of dateuser. c #include “date. h” void main() { struct date d; d. d=28; d. m=2; nextday(&d); … } //end of dateuser. c d. y=1999;
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Procedure Oriented System has the following programming pattern 1. Divides code into functions. 2. Data (contained in structure variables) is passed from 1 function to another to be read from or written into. 3. Focus is on Procedures / functions. 4. Procedures / functions are dissociated from data & are not a part of it. Instead receive structure variables / their addresses & work upon them
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Drawback/Disadvantage 1. Data is not secure and can be manipulated by any function/procedure. 2. Associated functions that were designed by library programmer don’t have rights to work upon the data. 3. They are not a part of structure definition itself because application program might modify the structure variables by some code inadvertently written in application program itself
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Consider an application of around 25, 000 lines in which the variables of structure is used quite extensively. Testing may find that date being represented by one of these variables has become 29 th Feb 1999. 2. This faulty piece of code can be anywhere in the program. 3. Hence Debugging will involve a visual inspection of the entire code & will not be limited to associated functions only. 1.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES 4. While distributing his/her application, application programmer cant be sure that program would run successfully. 5. Every new piece of code accessing structure variable will have to be inspected and tested again to ensure that it doesn’t corrupt the members of structure. 6. Compilers that implement procedure oriented programming systems don’t prevent unauthorized functions from accessing / manipulating the structure variables.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES To ensure a successful compilation of his/her code, application programmer is forced to remove those statements that access data members of structure variables. 8. Lack of data security of procedure oriented programs has led to Object Oriented Programming Systems 7.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Object Oriented Programming Systems • Model real-world objects • RWO has internal parts & interfaces that enable us to operate them. Eg-LCD is RWO-has a fan and a lamp. There are 2 switches 1 to operate fan & other to operate lamp. Switch operation has rules. If lamp is switched on, fan is automatically switched on, else lcd will be damaged.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES • Lamp is also switched off if fan is switched off and switches are linked with each other. Common Characteristic of RWO • If a perfect interface is required to work on an object , it will have exclusive rights to do so. • Coming to C++, observed behaviour of LCD projector resembles the desired behaviour of the date’s structure variables.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES • Compilers implementing OOPs enable data security enforcing a prohibition by throwing compile-time errors against the pieces of code. • RWO ensure a guaranteed initialization of objects OOPS Features – 1. Inheritance Polymorphism 2.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Inheritance allows one structure to inherit the Characteristics of other structure. variable of new structure will contain data members mentioned in new structure definition. Due to inheritance, it will also contain data members in existing definition from which new structure has inherited.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES In Inheritance, both data and functions may be inherited • Parent class can be given the general characteristics, while its child may be given more specific characteristics. • Inheritance allows code reusability by keeping code in a common place – the base structure. • Inheritance allows code extensibility by allowing creation of new structures that are suited to our requirements compared to existing structures.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Inheritance – a process by which 1 object can acquire the properties of another object. This is important as it supports classification Most knowledge is made of hierarchical Classification. Eg-Red delicious apple is part of apple classification which in turn is a part of fruit class, which is under the larger class food. Inheritance mechanism makes it possible for one object to be a specific instance of a more general class.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Polymorphism Using operators or functions in different ways depending on what they are operating on is called Polymorphism Static & Dynamic Polymorphism Function overloading & Operator. Overloading
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Function Prototyping • FP is necessary in C++. • C++ strongly supports function prototypes • Prototype describes the function’s interface to the compiler • Tells the compiler the return type of function, number , type and sequence of its formal arguments
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES GENERAL SYNTAX OF FUNCTION PROTOTYPE return_type function_name( argument_list); Egint add ( int, int); indicates add() function returns a int type and takes 2 arguments both of int type and terminates with ;
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES With prototyping , compiler ensures following 1. The return value of a function is handled correctly. 2. Correct number and type of arguments are passed to a function.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Since C++ compiler require function prototyping, it will report error against function call because no function prototype is provided to resolve the function call. Compiler may still give an error, if function call doesn’t match the prototype. Hence prototyping guarantees protection from errors arising out of incorrect function calls
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Sometimes function prototype & function call may not match FD and FP are both created by Library programmer. He/She puts FP in a header file , puts FD in a library. Application programmer includes header file in his/her application program file in which function is called. He creates an object file from application file and links this object file to the library to get an executable file.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Function Prototyping produces automatic type of conversion. Wherever appropriate
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Objects – Variables of classes are known as Objects SCOPE RESOLUTION OPERATOR (SRO) – It is possible and necessary for Library programmer to define member functions outside their respective classes. SRO makes this possible. Example illustrates the use of scope resolution operator
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES class Distance { int i. Feet; float f. Inches; public: void set. Feet(int); //only member function int get. Feet(); //prototypes are given void set. Inches(); //in the class definition. float get. Inches(); };
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Member Functions are prototyped within the class and have been defined outside void Distance : : set. Feet (int x) //definition { i. Feet=x; } int Distance : : get. Feet() //definition {return i. Feet; }
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES void Distance : : set. Inches (int y) //definition { f. Inches=y; } int Distance : : get. Inches() //definition { return f. Inches; } code showing use of scope resolution operator that specifies class to which member function belong. The class name is specified on LHS of SRO and name of member function being defined is on the right hand side
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Creating Libraries using the Scope Resolution Operator Creating a New Data type / class is also a 3 step Process i. e. executed by the Programmer.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Step-1. Place the class definition in a header file. Step-2. Place the definitions of member functions in a C++ source file / library source code / class implementation file. Step-3. Provide header file and library file in any media to other programmers who want to use this new datatype.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Step-1. Place the class definition in a header file. //Distance. h- header file containing Distance class Distance { int i. Feet; float f. Inches; public: void set. Feet(int); //only member function int get. Feet(); //prototypes are given void set. Inches(); //in the class definition. float get. Inches(); };
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Step-2. Place the definitions of member functions in a C++ source file / library source code / class implementation file //implementation file for class Distance – //Distlib. cpp
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES void Distance : : set. Feet (int x)//definition { i. Feet=x; } int Distance : : get. Feet() //definition { return i. Feet; }
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Void Distance: : set. Inches (int y) //definition { i. Feet=x; } int Distance: : get. Inches() //definition { return f. Inches;
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Step-3. Provide header file and library file in any media to other programmers who want to use this new datatype.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Using classes in the Application Programs The five steps followed by Programmers for using this new datatype / class are –
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Step-1. Include the header file provided by the programmer in their source code //distmain. cpp #include “Distance. h” void main() { …. …. } //end of Distmain. cpp
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Step-2. Declare variables of the new datatype in their source code //Distmain. cpp #include “Distance. h” void main() { Distance d 1, d 2; … … } //end of Distmain. cpp
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Step-3 Embed calls to the associated functions by passing these variables in their source code Listing in next slide shows how to use classes in the application programs
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES //distmain. cpp- A sample driver program for creating and using objects of class Distance #include<iostream. h> #include “Distance. h” void main() {Distance d 1, d 2; d 1. set. Feet(2); d 2. set. Inches(2. 2); d 1. set. Feet(3); d 2. set. Inches(3. 3); cout << d 1. get. Feet() << “ “ << d 1. get. Inches(); cout << d 1. get. Feet() << “ “ << d 2. get. Inches(); } }
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Step-4 Compile the source code to get the object file. Step-5 Link the object file with the library provided by the library programmer to get the executable or any library. Output – 2 2. 2 3 3. 3 Implementation files are compiled and converted into static and dynamic libraries
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES The ‘this’ pointer-The facility to create and call member functions of class objects is provided by the compiler. Compiler does this by using a unique pointer -> this pointer - always a constant pointer. - points at the object with respect to which the function was called
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Working of this pointer. Once the compiler is sure that no attempt is made to access the private members of an object by nonmember functions, it converts C++ code into an ordinary code as Follows.
1. Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES It converts class into structure with only data members as follows Before class Distance { int i. Feet; float f. Inches; public: void set. Feet(int); int get. Feet(); void set. Inches(); float get. Inches(); }; //only member function //prototypes are given //in the class definition.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES After Struct Distance { int i. Feet; float f. Inches; };
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES 2. It puts a declaration of the this pointer as a leading formal argument in the prototypes of all member functions as follows Before – void set. Feet(int); After void set. Feet( Distance * const int);
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Before – void get. Feet() After – void get. Feet(Distance * const ); Before – void set. Inches( float); After – void set. Inches(Distance * const, float); Before – float get. Inches(); After – float get. Inches(Distance * const);
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES 3. It puts the definition of this pointer as a leading formal argument in the definitions of all member functions as follows It also modifies all statements to access object members by accessing through the this pointer using the pointerto-member access operator (->).
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Before – void Distance : : set. Feet ( int x) { i. Feet = x; } After – void set. Feet( Distance * const this, int x) { this -> i. Feet = x; }
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Before – int Distance : : get. Feet() { return i. Feet; } After – int get. Feet( Distance * const this) { return this -> i. Feet; }
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Before – void Distance : : set. Inches (float y) { f. Inches = y; } After – Void set. Inches(Distance * const this, float y) { this -> f. Inches = y; }
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Before – float Distance : : get. Inches () { return f. Inches; } After – void get. Inches(Distance * const this) { return this -> f. Inches; }
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES SRO - operates on its operands. - binary operator taking 2 operands. • Operand on its left is the name of a predefined class. Right is a member function of the class. • Based on this info, SRO inserts a constant operator of correct type as a leading formal argument to function on its right.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES 4. Passes the address of invoking object as leading parameter to each call to the member function as follows Before – D 1. set. Feet(1); After set. Feet(&d 1, 1); Before – d 1. set. Inches(1. 1); After – set. Inches(&d 1 , 1. 1);
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Before – cout << d 1. get. Feet() << endl; After – cout << get. Feet(&d 1) << endl; Before – cout << d 1. get. Inches() << endl; After – cout << get. Inches(&d 1) << endl; In case of C++, dot operator’s definition is extended
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Its evident that ‘this’ pointer should continue to point at same object – the object with respect to which the member Function has been called – throughout the lifetime. Hence the compiler creates it as a constant pointer.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES The accessibility of the implicit object is similar to the other objects passed as parameters in function call and local objects inside that function A new function – add() has been added to the existing definition of the class
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES class Distance //Distance. h { int i. Feet; float f. Inches; public: void set. Feet(int); //only member function int get. Feet(); //prototypes are given void set. Inches(); //in the class definition. float get. Inches(); Distance add( Distance); };
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Distance add( Distance dd) { Distance temp; temp. i. Feet = i. Feet+dd. i. Feet; temp. f. Inches=f. Inches+ dd. f. Inches; return f. Inches; } described conversion for this add() using this ptr Distance add( Distance * const this dd) { Distance temp; temp. i. Feet = this->i. Feet+dd. i. Feet; temp. f. Inches=this->f. Inches+ dd. f. Inches; return f. Inches; } A statement d 3=d 1. add(d 2) is invoked as
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES temp Temp. i. Feet Temp. f. Inches i. Feet f. Inches d 3=d 1. add(d 2); d 1 Data in temp is assigned to d 3 using temp in add(d 2) function d 2 i. Feet f. Inches Similarly d 1. i. Feet, d 1. f. Inches. D 2. f. Inches, d 2. i. Feet can be accessed
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Explicit Address Manipulation An Application Programmer can manipulate the member data of any object by explicit address manipulation. Like Dot , arrow operator is also extended in C++. Arrow operator takes data members and member functions as its right hand side operand. A statement dptr -> set. Feet(1); after conversion becomes set. Feet ( dptr, 1); The value of dptr is copied into ‘this’ pointer. Hence this pointer also points at the same object at which dptr points //d 01. cpp, d 11. cpp
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Calling 1 member function from another 1 member function can be called from another. The call to the A : : setxindirect() function changes from A 1. setxindirect(1); //c++ call To setxindirect(&A 1, 1); //c call
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Function Definition of A : : setxindirect() function changes from void A : : setxindirect( int q) { setx(q); } to void A : : setxindirect( A * const this, int q) { this -> setx(q); //calling function through pointer } that changes to
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES void A : : setxindirect( A * const this, int q) { setx(this, q); //action of arrow operator }
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Member Functions and Member Data We see different types of member data & member functions that classes in C++ have Member functions can be overloaded just like nonmember functions. Code d 14. cpp illustrates the point.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Function Overloading enables us to have 2 functions of same name and same signature in 2 different classes illustrated below. Class A { Public: void show(); }; Class B { Public: void show(); };
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Knowledge of this pointer tell the signatures of show() are different Function prototypes in respective classes are void show(A* const); void show(B* const);
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Default Values for Formal Arguments of Member Functions Default values can be assigned to arguments of non-member functions and member functions. Member functions should be overloaded with care. If default values are specified for some or all of its arguments. D 15. cpp For example- Compiler will report an ambiguity error when it finds the second prototype for the function for show() of class A as follows. Class A { public: void show(); void show(int =0); }; //d 17. cpp
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Reasons for Ambiguity In case of nonmember functions, if default values are specified for more than 1 formal argument, they must be specified from right to left. Default values must be specified in the function prototypes, not in function definitions. Further default values can be specified formal arguments of any type.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Inline Member Functions Member functions are made inline by 2 Methods. 1. By defining function within the class itself. 2. By only prototyping and not defining the function within the class. The function is defined outside the class using Scope Resolution Operator. The definition is prefixed by inline keyword. As in noninline member functions, the definition of inline function must appear before the function is called. Hence the function should be defined in the same header file in which the class is defined.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Class Distance { int i. Feet, f. Inches; //private by default Public: void set. Feet(int x) { i. Feet =x; } int get. Feet() { return i. Feet; } Void set. Inches(float y) { return f. Inches; } float get. Inches() { return f. Inches; } };
//meminline. cpp Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Class A { public: void show(); }; Inline void A : : show() //definition in header file { //definition of A : : show() function } Inline member Functions
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Constant Member Functions The Library Programmer may desire that one of member functions of his/her class shouldn’t be able to change the value of member Data. Function should merely read values contained in the data Members, but not change them even accidentally while defining the function. Compiler’s help may be sought by declaring function as constant Function & attempting to change data value through member Function, the compiler may throw an error. get. Feet() & get. Inches() and add() of Distance class should obviously be constant functions and shouldn’t change the i. Feet / f. Inches members of invoking object even by accident. Member functions are specified as constants by suffixing prototype And function definition header with const keyword. Modified Distance class is written as
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Class Distance { int i. Feet; float f. Inches; public: void set. Feet(int); int get. Feet() const; //constant function void set. Inches(float); float get. Inches() const; //constant function Distance add(Distance) const; //constant function };
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES void Distance: : set. Feet(int x) { i. Feet=x; } void Distance: : get. Feet() const { i. Feet++; //ERROR!! return i. Feet; } void Distance: : set. Inches(float y) { f. Inches=y; } void Distance: : get. Inches() const { f. Inches=0. 0; //ERROR!! return f. Inches; } //const function
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES void Distance: : add(Distance dd) const //const function { Distance temp; temp. i. Feet= i. Feet + dd. i. Feet; temp. set. Inches (f. Inches + dd. f. Inches); i. Feet++; //ERROR!! return temp; } For const. member functions, memory occupied by invoking object is a read-only memory. Only const. member functions can be called with respect to constant objects. However nonconstant functions can be called with respect to nonconstant objects.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Mutable Data Members Mutable data member is never constant. 1. It can be modified inside constant functions also. 2. Prefixing the declaration of a data member with the key word mutable makes it mutable. Code shows in next slide
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Class A //mutable. h { int x; mutable int y; public: void abc() const //a constant member function { //error: cant modify a non-constant da x++; //ta member in a const. mf y++; //ok can modify a mutable data member in } // const. mf void def() //non-const. mf { x++; //ok can modify nonconstant data member //in a non-const. mf y++; //ok can modify mutable data member in a //nonconst. mf } }; /*end of mutable. h*/
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES We frequently need a data member that can be modified even for constant objects. Suppose there is a member function that saves the data of an invoking object in a disk file. This function should be declared as a constant to prevent even an inadvertent change to the data members of the invoking object. If we need to maintain a flag inside each object that tells whether the object has already saved or not, such data should be modified within above constant member function. Hence this data member should be declared a mutable member.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Friends- A class can be global non-member function and member functions of other classes as friends. Such functions can directly access private data members of objects of class. Friend Non-member functions a Friend function is a non-member function that has special rights to access private data members of any object of class of whom it is a friend. Here we study only those friend functions that are not member functions of some other class.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Friend function is prototyped within the definition of Class of which it is intended to be friend. It is prefixed with the keyword friend. Since it is a non-member function, it is defined without using scope resolution operator. It is not called with respect to an object.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Friend Functions • Friend keyword should appear in the prototype only and not in the definition • Since it is a nonmember function of the class of which it is a friend, it can be prototyped in either private or public section of the class. • A friend function takes 1 extra parameter compared to a member function that perform a same task • No need of using scope resolution operator for defining a member function.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES • Friend functions don’t contradict the principles of OOPs. • The benefits provided by data hiding are not compromised by friend functions.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Friend Classes • A class can be friend of another class. Member Functions of a friend class can access private data members of objects of class of which it is a friend. If class B is made a friend of class A, example illustrates this Class A {friend class B; //declaring class B as a friend of class A /* rest of class A*/ //doesn’t matter to declare in priv or //public section for friend function }; fig- declaring friend classes
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Member functions of class B can access private members of objects of class A Listing the effect declaring a friend class frie Class B; // forward declaration needed because //definition of class B is after stmt declaring //class B is a friend of class A Class A {int x; Public: void setx(const int =0); void getx() const; friend class B; //declaring class B as a friend of A };
Class B { A * Aptr; Public: Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES void Map(const A * const); void test_friend( const int); }; void B : : Map(const A*, const p); { Aptr=p; }
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Void B : : test_friend(int i) { Aptr -> x=i; //accessing private data member } Code effect of declaring a friend class
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES • Member functions of class B are able to access private data member of objects of class A although they are not member functions of class A. This is because they are member functions of class B i. e. a friend of class A. • Friendship is not transitive. • Consider the listing in next slide
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Class B; Class C; Class A { friend class B; int a; }; Class B { friend class C; }; //friendtran. cpp
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Class C { void f( A *p) { p->a++; //error: C is not a friend of A despite // being a friend of friend } }; //end of friendtran. cpp Code to show that friendship is not transitive
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Friend Member Functions Can we make specific member functions of 1 class friendly to another class ? For making only ‘ B: : test_friend() ’ function a friend of class A, replace the line Friend void B: : test_friend(); The modified definition of class A is given in next slide
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Class A { /*rest of class A Friend void B : : test_friend(); }; To compile this code successfully, compiler should first see definition of class B, else it doesn’t know that test_friend() is a member function of class B. However, a pointer of type A * is a private member of class B. This problem of circular dependence is solved by forward declaration by inserting a line Class A; //Declaration , only not definition!! before definition of class B. declarations and definitions of 2 classes appear in next slide.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES //Friendmemfunc. h class A; class B { A *Aptr; Public: void Map(const A * const); void test_friend(const int=0); }; class A { int x; public: friend void B : : test_friend ( const int=0) }; Forward declaring a class that requires a friend.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Class A; Class B { A *Aptr; public: void map(const A *A); void test_friend(const int =0); }; Class A {int x; Public: friend void B: : test_friend(const int =0); }; inline void B: : test_friend( const p) { Aptr->x=p; }
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Static Data Members – hold global data i. e. common to all objects Examples of such global data are – 1. Count of Objects currently present 2. Common data accessed by all objects, etc.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Consider class Account and we may Want all objects to calculate interest rate at 4. 5%. Hence this data should be available globally to all objects of this class. This data should be stored globally to All objects of this class.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Objects and Functions – Objects appear as local variables. They can also be passed by reference to Functions. Finally they can be returned by value or by reference from the functions. Distloc. cpp, distarray. cpp largedist. cpp
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Arrays Inside Objects – An array can be declared inside the class. Such an array becomes a member all objects of class. It can be accessed / manipulated by all member functions of the class. #define SIZE 3 /*A class to duplicate the behavior of an integer array*/ class A { int i. Array[SIZE]; Public: void set. Element (unsigned int, int); int get. Element (unsigned int); };
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES /*function to write the value passed as a second parameter At position passed as first parameter*/ void A: : set. Element(unsigned int, int) { if (p<=SIZE)return; //better to throw an exception i. Array[p]=v; } /*function to read the value from the position passed as parameter*/ int A: : get. Element(unsigned int p) { if (p<=SIZE)return -1; //better to throw an exception return i. Array[p]; } code for arrays inside the objects, always better to throw exceptions rather than terminating the functions
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Namespaces – enable C++ programmer to prevent pollution of global namespace that lead to name clashes Global namespace refer to the entire source code. It Includes all the directly and indirectly included header files. By default, name of each class is visible in the source code i. e. in the global space. This can lead to problems. Suppose a class with same name is defined in 2 header files. /*A 1. h*/ class A { }; class B { }; Lets include both these header files in a program and see what happens if we declare objects of the class
//multidef 01. cpp #include “A 1. h” #include “A 2. h” Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES void main() { A Aobj; //Ambiguity error due to multiple definitions of A } Code showing a reference to a globally declared class can lead to ambiguity error. Global visibility of definition of class A make the inclusion of 2 header Files mutually exclusive. Consequently, this makes use of 2 definitions of class A mutually exclusive. An application accesses both definitions of class A simultaneously by enclosing 2 definitions of the classin separate namespaces can overcome this problem.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES /*A 1. h*/ namespace A 1 { class A { }; } /*end of namespace A 1. h*/ /*A 2. h*/ namespace A 2 { class A { }; } /*end of namespace A 2. h*/
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES The 2 definitions of class are enveloped in 2 different Namespaces. Corresponding namespaces, followed by SRO, must be prefixed to the class name while referring to It anywhere in the source code. Hence the ambiguity encountered in above listing can be overcome. Revised definition of main() function #include “A 1. h” #include “A 2. h” void main() { A 1: : A Aobj 1; //ok: Aobj 1 is an object of class defined in A 1. h A 2: : A Aobj 2; //ok: Aobj 2 is an object of class defined in A 2. h } enclosing classes in namespaces prevent pollution of namespaces
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Qualifying the name of the class with that of the Namespace can be cumbersome. The using directive enable us to make class definition inside A namespace visible so that qualifying the name of referred Class by name of namespace is no longer required. Code below tells how this is done /*using. cpp*/ #include “A 1. h” #include “A 2. h” void main() { using namespace A 1; A 1: : A Aobj 1; //ok: Aobj 1 is an object of class defined in A 1. h A 2: : A Aobj 2; //ok: Aobj 2 is an object of class defined in A 1. h } using directive makes qualifying of referred class names by names of enclosing namespaces unnecessary
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Using directive brings back global namespace pollution That namespaces mechanism was supposed to remove in the first place! The last line in above listing compiles only because the classname was qualified by the name of namespace. Having long name for namespaces. Qualifying the name of a class i. e. enclosed within such name of namespace is cumbersome
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES /*longname 1. cpp*/ name_space a_very_long_name { class A { }; } void main() {a_very_long_name: : A A 1; //cumbersome long name } Assigning a suitably short alias to such a long name solves the problem /*longname 2. cpp*/ name_space a_very_long_name { class A { }; } namespace x=a_very_long_name;
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES /*longname 2. cpp*/ name_space a_very_long_name { class A { }; } namespace x=a_very_long_name; Void main() { X: : A A 1; //convenient short name }
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Aliases – provide an incidental benefit also. If alias name has been used at a number of places in the source code. Changing the alias declaration so that it stands as an alias for a different namespace will make each reference of enclosed class refer to a completely different class Suppose an alias x refers to a namespace ‘N 1’. namespace x = N 1; //declaring an alias Further suppose this alias has been used extensively in code X: : A Aobj; //Aobj is an object of class A i. e. enclosed in namespace N 1 Aobj. f 1(); //f 1() is a member function of above class If declaration of alias is changed to namespace N 2, Namespace x=N 2; Then all existing qualifications of referred class names that use x would now refer to a class A i. e. contained in namespace N 2.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Nested Classes – A class can eb defined inside another class. Such a class is called Nested class. A class that contain a nested class is called Enclosing class. Nested classes are defined in private, protected, or public portions of enclosing class • Class B is defined in the private section of the class. /*nestedprivate. h*/ Class A { class B { /* definition of class B*/ {/* definition of class A*/ }; /*end of nestedprivate. h*/ Nested classes
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Here class B is defined in public section of class A. A nested class is created if it doesn’t have any relevance outside its enclosing class. Naming Collision can be avoided with nested class Class A /*nestpublic. h*/ { public: class B {/* definition of class B*/ }; /*definition of class A*/ }; A public nested class
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES In the listings of the 2 slides , even If there is a class B defined as A global class, its name will not clash with the nested class B. The size of objects of an enclosing class is not affected by the presence of nested class. //size. cpp How are members of a nested class defined ? Members of a nested class can be defined outside the definition of the enclosing class by prefixing the function name with name of enclosing class followed by SRO. This inturn is followed by name of nested class followed again by SRO.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website Class A /*nestclassdef. h*/ for students | VTU NOTES { public: class B { public: void BTest(); //prototype only }; //definition of class A } #include “nestclassdef. h” void A: : BTest() { //definition of A: : BTest() function } /* definition of rest of functions of class B*/ Code Defining member functions of nested classes
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES A nested class may be only prototyped within its enclosing class and defined later. Again , name of enclosing class with SRO is required. Class A /nestclassdef. h { class B; //prototype only }; Class A: : B { /*definition of the class B*/ } Defining a nested class outside the enclosing class. Objects of nested class are defined outside the member functions of the enclosing class followed by SRO(scope resolution operator) A: : B B 1; line will compile only if class B is defined within public section of class A, else compile time error occurs
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES An Object of the nested class an be used in any of the member functions of the enclosing class without the scope resolution operator. Moreover an object of nested Class can be a member of enclosing class. In either case , only the public member functions of the object can be accessed unless the enclosing class is a friend of the nested class
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES //nestlclassobj. h Class A { class B { public: void ATest(); }; //nestclassobj. cpp #include “nestclassobj. h” void A: : ATest() { B 1. BTest(); B B 2; B 2. BTest(); } Declaring objects of nested class in the member functions of the enclosing class
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES Member functions of the nested class can access the nonstatic public members of the enclosing class through an object, a pointer, or a reference only. //enclclassobj. h Class A { Public: void ATest(); class B { public: void BTest(); void BTest 1(); }; };
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES //enclclassobj. cpp #include “enclclassobj. h” void A: : BTest(A& ARef) { ARef. ATest() //ok } void A: : BTest 1() { ATest(); //Error } Accessing nonstatic members of the enclosing the class in member functions of the nested class.
Prof. B. R. Mohan, SSE--> www. bookspar. com | Website for students | VTU NOTES It can be observed that an error is produced when a direct Access is made to the member of the enclosing class through the function of the nested class. CREATION OF AN OBJECT OF A NESTED CLASS DOES NOT CAUSE AN OBJECT OF ENCLOSING CLASS TO BE CREATED. The classes are nested to merely control the visibility. Since A: : BTest() function will be called with respect to an object Of class B, a direct access to a member of the enclosing class A can be made through an object of that class only.
- Slides: 186