1 Pointers A Pointer in C++ is a variable whose value is a memory address of another variable i.e. It holds the memory address of a variable The general form of a pointer variable declaration in C++ is: type *variable-name; • type - the pointer´s base type. It must be a valid C++ type. • variable-name - the name of the pointer variable The * and & operators - & operator is the address-of operator (reference operator) Variables are stored in memory, and each has a unique memory address returns the memory address of the variable - * operator is the dereferencing operator. It is used in pointers declaration returns the value of the variable located at the address specified by its operand Used to access the value stored at the memory address held by a pointer
2 D eclaration of pointers int * int_pointer ; // pointer to an integer float * float_pointer ; // pointer to a float double * double_pointer ; // pointer to a double char *str; // pointer to a char or string int ** ptrptr ; // pointer to a pointer
3 Using Pointers in C++ We define a pointer variable Assign the address of a variable to a pointer Finally access the value at the address available in the pointer variable This is done by using the unary operator * that returns the value of the variable located at the address specified by its operand int var = 20; // actual integer variable int * ip ; // pointer to an integer variable declaration ip = &var; // store address of var in pointer variable cout << ip << endl ; // print the address stored in ip pointer variable cout <<* ip << endl ; // access the value of the address available in pointer Dereferencing a pointer gives the value stored at the memory address
4 Example
5 Example
6 Example
7 Pointer Arithmetic Performing arithmetic operations on pointers Adding or subtracting an integer value to a pointer moves it to a different memory location Increment/decrement pointers ( ++ or -- ) (* ptr )++; “At the location pointed to by ptr , increment the value by 1.” Add/subtract an integer to/from a pointer ( + or += , - or -= ) (* ptr )+=8; (* ptr )-=5;
The this Pointer The "this" pointer is a reserved pointer in C++ that points to the current object. It allows objects to access their own members and methods. In this example, the "this" pointer is used to print the address of the current object.
When to Use "this" Pointer You use the "this" pointer when there is a need to differentiate between class member variables and function parameters with the same name. "this" pointer is particularly useful in situations where member variables and function parameters share the same name, preventing confusion and enabling access to class members. this->width = width; assigns the value of the width parameter (the one passed to the setDimensions function) to the class member width. This effectively sets the width of the rectangle. this->height = height; assigns the value of the height parameter (the one passed to the setDimensions function) to the class member height. This effectively sets the height of the rectangle.
Example The setName method is used to change the student's name. This method demonstrates three different ways to access the name member variable: name = newName ;: Here, we access the member variable directly. this->name = newName ;: We use this-> to access the member variable explicitly. (*this).name = newName ;: We use (*this). to access the member variable explicitly .
Introduction to Function Templates So, what exactly are function templates? Function templates are a way of writing functions that can work with multiple data types. They're like flexible blueprints for functions.
Function Overloading Recap Before we dive into function templates, let's briefly recap function overloading. Function overloading allows us to have multiple functions with the same name but different parameter lists. It's an important concept that forms the foundation for function templates.
Function Definition Define function header and function body Value-returning functions – int, double, char, float return-data-type function-name(parameter list) { constant declarations variable declarations other C++ statements return value }
Function Definition (cont.) Non value-returning functions void function-name(parameter list) { constant declarations variable declarations other C++ statements }
Calling a function A function is called by specifying its name followed by its arguments. Non-value returning functions: function-name (data passed to function); Value returning functions: results = function-name (data passed to function); int maxNum = maximum(4,67);
Advantages of using functions Functions can be called multiple times from different parts of the program. Code can be reused, eliminating the need for redundant code and saving time and effort. Functions simplify code maintenance by allowing changes in specific functions instead of the entire program
Overloading Providing two or more different definitions of the same function name. Overloading a function: more than one function in the same class having the same name but differing either in the number of parameters or the types of their parameters. The easiest way to remember this: the functions’ parameters should qualify any one or more than one of the following conditions: They should have a different type. They should have a different number. They should have a different sequence of parameters. We need to overload the function if we have to perform a single operation with different numbers or types of arguments .
Here’s a small function that you might write to find the maximum of two integers. int maximum(int a, int b) { if (a > b) return a; else return b; } Finding the Maximum of Two Integers
Here’s a small function that you might write to find the maximum of two double numbers. int maximum( double a, double b) { if (a > b) return a; else return b; } Finding the Maximum of Two Doubles
Function Template Function templates are special functions that can operate with generic types. Function templates allow the logic to be written once and used for all data types – generic function. This allows us to create a function template whose functionality can be adapted to multiple types or classes without repeating the entire code for each type.
Function Template For example, a function to add two integer and float numbers requires two functions. One function accepts integer types and the other accepts float types as parameters even though the functionality is the same. Using a function template, a single function can be used to perform both additions. It avoids unnecessary repetition of code for doing the same task on various data types For each call, the compiler generates the complete function, replacing the type parameter with the type or class to which the arguments belong.
Function Template Syntax A function template starts with the keyword template Followed by template parameter(s) inside <> which is followed by the function definition T is a template argument that accepts different data types (int, float, etc.) and typename is a keyword This 'T' can be replaced with any data type when we use the template When an argument of a data type is passed to functionname (), the compiler generates a new version of functionname () for the given data type
This template function can be used with many data types. template <class Item> Item maximum(Item a, Item b) { if (a > b) return a; else return b; } A Template Function for Maximum
A template prefix is also needed immediately before the function’s implementation: template <class Item> Item maximum(Item a, Item b) { if (a > b) return a; else return b; } A Template Function for Maximum
Once a template function is defined, it may be used with any adequate data type in your program... template <class Item> Item maximum(Item a, Item b) { if (a > b) return a; else return b; } Using a Template Function cout << maximum(1,2); cout << maximum(1.3, 0.9); ...
Friend Function We have seen that private members can't be accessed from outside class. Non member function cannot have access to the private data of a class. Friend function : a function that is not a member of a class, but has access to private members of the class A friend function can be a stand-alone function or a member function of another class This function can be defined else where in the program. It can be declared either in the public or private part of a class without affecting its meaning It is declared a friend of a class with the friend keyword in the function prototype 11- 26
Friend Function Friend functions of an object can "see" inside the object and access private member functions and data. Syntax: Friend returntype function_name ( arguements ); Eg : Friend void add();
A friend function has certain special characteristics: It is not in the scope of class to which it has been declared as friend Since it is not in the scope of class, it cannot be called using object of that class It can be invoked like a normal function without the help of any object. Unlike member function it can’t access member names directly and has to use an object name and dot membership operator with each member name
Access functions To allow clients to read the value of private data, the class can provide a get function. To allow clients to modify private data, the class can provide a set function.
Implementation of the Friend Function Student &nm Student &age
Operator Overloading If we want to make the operator ‘+’ add two class objects, we have to redefine the meaning of the ‘+’ such that it add two class objects We achieve this by using the concept of “Operator overloading” Redefining the meaning of operators does not change their original meaning It gives them additional meaning along with their existing ones Overloaded operators are functions with special names: the keyword "operator" followed by the symbol for the operator being defined. Box operator+( const Box&); Declares the addition operator to add two Box objects and returns the final Box object
The syntax for C++ Operator Overloading To overload an operator, we use a special operator function The function is mostly defined inside the class or structure whose objects/variables we want the overloaded operator to work with Here returnType is the return type of the function operator is a keyword symbol is the operator we want to overload like: +, <, -, ++, etc. arguments is the arguments passed to the function
Restrictions on Operator Overloading C++ operators that can be overloaded C++ Operators that cannot be overloaded
Rules of operator overloading We can overload an operator as its type only i.e., a unary operator cannot be overloaded as a binary operator and vice versa. We can’t overload operators that are not a part of C++. At least one operand must be a user-defined class object We cannot change the operator’s existing functionality. When unary operators are overloaded through a member function , they do not take any explicit arguments. But when overloaded by a friend function or non-member function , they take one argument. When binary operators are overloaded through a member function , they take one explicit argument. If overloaded through a friend function or non-member function , they instead take two explicit arguments. There is a left-hand-side operand and a right-hand-side operand x ‘operator’ y ( x+y or x*y), x is the left-hand-side operand and y is the right-hand-side operand The whole expression has a value after applying the operator
Ways of operator overloading Operator overloading of member functions . Operator overloading of non-member or friend functions .
Difference between Member and friend function Friend or non-member function: More parameters can be passed. Unary operators take one explicit parameter. Binary operators take two explicit parameters (need parameters for both operands) You can make the operator overloading function a friend function if it needs to access the private and protected class members. If the left operand must be a built-in type or object of a different class, it must be a non-member function
Non-member function Example
Difference between Member and friend function cont.. Member function: The number of parameters to be passed is reduced by one, as the calling object is implicitly supplied as an operand. The leftmost object must be of the same class as the operator Unary operators take no explicit parameters. Binary operators take only one explicit parameter. The operator overloading function may be a member function when the left operand is an object of the Class.
Member Function - Example Point result; result.x = this->x + other.x ; result.y = this->y + other.y ;
Overloading Types of Operators ++ , -- operators overloaded differently for prefix vs. postfix notation Prefix notation Increment and decrement operators are placed before the operand (++obj, --obj) Overloaded increment/decrement operator returns the updated object after incrementing or decrementing It performs the operation first, then returns the modified object Postfix notation Increment and decrement operators are placed after the operand ( obj ++, obj --) Overloaded increment/decrement operator returns a copy of the original object before incrementing or decrementing It creates a temporary copy of the object, performs the operation on the original object, then returns the copy Overloaded relational operators should return a bool value Overloaded stream operators >> , << must return istream , ostream objects and take istream , ostream objects as parameters 11- 40
41 Stream Insertion and Extraction Operators as Global Functions Overload << operator used where Left operand of type ostream & Such as cout object in cout << classObject Overload >> has left operand of istream & Left operand of type istream & Such as cin object in cout >> classObject Reason:– These operators are associated with class of right operand
What Is Inheritance? Provides a way to create a new class from an existing class The new class is a specialized version of the existing class 42
The "is a" Relationship Inheritance establishes an "is a" relationship between classes. A poodle is a dog A car is a vehicle A flower is a plant A football player is an athlete 43
Inheritance Base class (or parent) – inherited from Derived class (or child) – inherits from the base class Notation: class Student // base class { . . . }; class UnderGrad : public student { // derived class . . . }; 44
Back to the ‘is a’ Relationship An object of a derived class 'is a(n)' object of the base class Example: an UnderGrad is a Student a Mammal is an Animal A derived object has all of the characteristics of the base class 45
What Does a Child Have? An object of the derived class has: all members defined in the child class t hese are the members unique to the derived class and not inherited from the parent class. All members declared in parent class all the members (both variables and functions) declared in the parent class. This includes public, protected, and private members, but the access level depends on the inheritance type (public, protected, or private). An object of the derived class can use: All public members defined in the child class All public members defined in the parent class 46
Class Access Specifiers public – object of derived class can be treated as object of base class (not vice-versa) protected – more restrictive than public , but allows derived classes to know details of parents private – prevents objects of derived class from being treated as objects of base class. 47
Inheritance vs. Access 48 private: x protected: y public: z private: x protected: y public: z private: x protected: y public: z Base class members x is inaccessible private: y private: z x is inaccessible protected: y protected: z x is inaccessible protected: y public: z How inherited base class members appear in derived class private base class protected base class public base class
Inheritance vs. Access 49 private members: char letter; float score; void calcGrade (); public members: void setScore (float); float getScore (); char getLetter (); class Grade private members: int numQuestions ; float pointsEach ; int numMissed ; public members: Test(int, int); class Test : public Grade When Test class inherits from Grade class using public class access, it looks like this: private members: int numQuestions : float pointsEach ; int numMissed ; public members: Test( int , int ); void setScore (float); float getScore (); char getLetter ();
Inheritance vs. Access 50 private members: char letter; float score; void calcGrade(); public members: void setScore(float); float getScore(); char getLetter(); class Grade private members: int numQuestions; float pointsEach; int numMissed; public members: Test(int, int); When Test class inherits from Grade class using protected class access, it looks like this: private members: int numQuestions: float pointsEach; int numMissed; public members: Test(int, int); protected members: void setScore(float); float getScore(); float getLetter(); class Test : protected Grade
Inheritance vs. Access 51 private members: int numQuestions: float pointsEach; int numMissed; void setScore(float); float getScore(); float getLetter(); public members: Test(int, int); private members: char letter; float score; void calcGrade(); public members: void setScore(float); float getScore(); char getLetter(); class Grade private members: int numQuestions; float pointsEach; int numMissed; public members: Test(int, int); When Test class inherits from Grade class using private class access, it looks like this: class Test : private Grade
Constructors and Destructors in Base and Derived Classes Derived classes can have their own constructors and destructors When an object of a derived class is created, the base class’s constructor is executed first, followed by the derived class’s constructor When an object of a derived class is destroyed, its destructor is called first, then that of the base class 53
Recursion Sometimes, the best way to solve a problem is by solving a smaller version of the exact same problem first Recursion is a technique that solves a problem by solving a smaller problem of the same type In programming recursion is a method call to the same method. In other words, a recursive method is one that calls itself. Recursive algorithms are simple to understand and prove correct, easy to implement But! Recursive calls can result in an infinite loop of calls Recursion needs a base case in order to stop
Content of a Recursive Method Base case(s). There is a base case (or cases) that is tested upon entry Values of the input variables for which we perform no recursive calls are called base cases (there should be at least one base case). Every possible chain of recursive calls must eventually reach a base case. Recursive calls. Calls to the current method. Each recursive call should be defined so that it makes progress towards a base case.
How to write a recursive function? Determine the size factor how the problem size is reduced with each recursive call. Determine the base case(s) (the one for which you know the answer) When the base case is reached, the recursion stops. Determine the general case(s ) (the one where the problem is expressed as a smaller version of itself) Verify the algorithm (use the "Three-Question-Method") - next slide
Three-Question Verification Method Does the function always reach the base case? Ensure that the recursion progress leads to the base case to prevent infinite recursion Does the function correctly solve the base case? Verify that the base case solution is correct. Does the function correctly combine results of recursive calls to solve the general case? Ensure that the recursive calls and their results are combined accurately to solve the overall problem.
Recursion vs. iteration Iteration can be used in place of recursion An iterative algorithm uses a looping construct A recursive algorithm uses a branching structure Recursive solutions are often less efficient, in terms of both time and space, than iterative solutions Recursion can simplify the solution of a problem, often resulting in shorter, more easily understood source code
Write a function that computes the sum of numbers from 1 to n int sum (int n) use a loop recursively i < = n; i++) //with a loop int sum (int n) { int s = 0; for (int i = ; s+= i; return s; } //recursively int sum (int n) { if (n == 1 ) return 1 ; else return n + sum(n-1); } Example
Example Write a function that computes the sum of numbers from 1 to n, using Loop Recursive function
Deciding whether to use a recursive solution When the depth of recursive calls is relatively "shallow“ Recursive solutions involve function calls that are added to the call stack. Shallow recursive call doesn't lead to excessive memory usage or performance issues. When the recursive version does about the same amount of work as the nonrecursive version Choosing recursion might lead to more elegant and readable code without significantly affecting performance. When the recursive version is shorter and simpler than the nonrecursive solution Improves the readability and maintainability of the code.
Using Input/Output Files stream - a sequence of characters interactive ( iostream ) cin - input stream associated with keyboard. cout - output stream associated with display file ( fstream ) ifstream - defines new input stream (normally associated with a file). The stream extraction operator (>>) may be used to read information from a file. ofstream - defines new output stream (normally associated with a file). The stream insertion operator (<<) may be used to write information to a file. outputFile << “I love C++ programming !”
General File I/O Steps Include the header file fstream in the program. Declare file stream variables. Associate the file stream variables with the input/output sources. Open the file Use the file stream variables with >>, <<, or other input/output functions. Close the file.
I fstreams and ofstreams File Type Default Open Mode The file is opened for input only. (Information may be read from the file, but not written to it.) The file ’ s contents will be read from its beginning. If the file does not exist, the open function fails. ifstream inStream ; instream.open (“infile.dat”); Int OneNum , anotherNum ; instream >> oneNum >> anotherNum Instream.close (); The file is opened for output only. (Information may be written to the file, but not read from the file.) If the file does not exist, it is created. If the file already exists, its contents are deleted ofstream outStream ; outstream.open (“outfile.dat”) outstream<<“ oneNum = “<< oneNum <<“ anotherNUm = << anotherNum ; outstream.close (); i f s t r e a m o f s t r e a m
Member Functions The eof () member function reports when the end of a file has been encountered. The eof () function returns true when there is no more information to be read. if ( inFile.eof ()) inFile.close (); The put Member Function outFile.put ( ch ); The get Member Function inFile.get ( ch ); The getline Member Function dataFile.getline (str, 81, ‘\n’); str – This is the name of a character array. The information read from the file will be stored here. 81 – This number is one greater than the maximum number of characters to be read. In this example, a maximum of 80 characters will be read. ‘\n’ – This is a delimiter character of your choice. If this delimiter is encountered, it will cause the function to stop reading before it has read the maximum number of characters. (This argument is optional. If it’s left out, ‘\n’ is the default.)
File I/O Example: Reading Read char by char Read a line #include < iostream > #include < fstream > int main() { //Declare and open a text file ifstream openFile.open (“data.txt "); char ch ; //do until the end of file while ( ! OpenFile.eof () ) { OpenFile.get ( ch ); // get one character cout << ch ; // display the character } OpenFile.close (); // close the file return 0; } #include < iostream > #include < fstream > #include <string> int main() { //Declare and open a text file ifstream openFile.open ( "data.txt" ); string line; while (! openFile.eof ()) {//fetch line from data.txt and put it in a string getline ( openFile , line); cout << line; } openFile.close (); // close the file return 0; }
Why do we use Files Convenient way to deal with large quantities of data. Store data permanently (until the file is deleted). Avoid typing data into the program multiple times. Share data between programs. We need to know: how to "connect" file to the program how to tell the program to read data how to tell the program to write data error checking and handling EOF
FUNCTIONS USE D IN FILE HANDLING Function Operation open() To create a file close() To close an existing file get() Read a single character from a file put() write a single character in file. read() Read data from file write() Write data into file.