Unit III Virtual Functions. Developed By Ms. K.M.Sanghavi

Size: px
Start display at page:

Download "Unit III Virtual Functions. Developed By Ms. K.M.Sanghavi"

Transcription

1 Unit III Virtual Functions Developed By Ms. K.M.Sanghavi

2 Topics Pointers- indirection Operators Memory Management: new and delete : Slide / (Covered In Unit I Too) Accessing Arrays using pointers : 25 Slide Function pointers Pointers to Objects Pointer to Pointers Linked List Example

3 Topics Smart pointers Shared pointers Unique Pointers

4 Introduction A pointer is a variable which contains the address (in memory) of another variable. Pointers are symbolic representation of addresses We can have a pointer to any variable type.

5

6

7 Declare Type of data stored in the address of the variable. Indirection operator

8

9 Declaring pointer Passing Address

10

11

12 Example #include <iostream.h> void main( ) int data = 100; float value = 56.47; data cout << data << &data << endl; cout << value << &value << endl; Output: 100 FFF FFF0 value FFF0 FFF1 FFF2 FFF3 FFF4 FFF5 FFF CSC Data Structures/Algorithms 12

13 //Demonstration. #include<conio.h> #include<iostream.h> void main() int x ; float y; Pointers. Every Block is a memory cell Cell no s / Address Memory x = 10; 10 x y 4007 y = 20.0; 20.0 cout<< Value s of x and y = <<x<<y; getch();

14 & * Pointer Operator s. Address of (Reference) Operator. Value At Address (Indirection) operator. void main() int *int_ptr; float *float_ptr; int x = 10 ; float y = 20.0; Value at Address. Address Name od address x cout<< Value s of x and y = <<x<< <<y; int_ptr = &x; float_ptr = &y; cout<<"int_ptr = "<<int_ptr; cout<<"\n float_ptr = "<<float_ptr; cout<<"\n value in int_pointer = "<< *int_ptr; cout<<"\n value in float_ptr = "<< *float_ptr; getch(); y

15 Pointers contd. & Address of (Reference) Operator. * Value At Address (Indirection) operator. // Demonstration. #include <iostream.h> #include<conio.h> void main () int variable ; int *mypointer; mypointer = &variable; *mypointer = 50; variable Address of variable = mypointer 50 = value at address cout << "value in variable is " <<variable<<endl; getch(); Value in variable is 50

16 //Demonstration #include <iostream.h> #include<conio.h> main () int x=10; int *y; int **z; cout<<"value of x = "<<x; cout<<"\nadd of x = "<<&x; cout<<"\nvalue of x = "<<*(&x); y=&x; cout<<"\nadd of y = "<<&y; cout<<"\nadd in y = "<<y; z=&y; cout<<"\nadd of z = "<<&z; cout<<"\nadd in z = "<<z; getch(); & Address of (Reference) Operator. * Value At Address (Indirection) operator x Value of x = 10 *y Add of x = 2554 Value of x = 10 Add of y = 5888 Add in y = 2554 Add of y = 6550 Add in z = **z

17 //Demonstration #include <iostream.h> #include<conio.h> main () int x=10; int *y; int **z; & Address of (Reference) Operator. * Value At Address (Indirection) operator x *y **z cout<<"value of x = "<<x; cout<<"\nadd of x = "<<&x; Value of x = 10 y=&x; cout<< Accessing x via ptr y = <<*y; Add of x = 2554 z=&y; x via prt y = 10 cout<< Accessing x via ptr z <<**z; getch(); x via prt z = 10

18 Facts & Address of (Reference) Operator. * Value At Address (Indirection) operator. 1. *& variable = variable 2. *(&)variable = *&variable Example 1 : int x =10; cout<<*&x; cout<<*(&)x; Example 2 : int x = 10; int * p; p = &x; cout<<* p; 10 10

19 Operations on Pointer Variables Assignment the value of one pointer variable can be assigned to another pointer variable of the same type Relational operations - two pointer variables of the same type can be compared for equality, and so on Some limited arithmetic operations integer values can be added to and subtracted from a pointer variable value of one pointer variable can be subtracted from another pointer variable 19

20

21

22 Example: Pointer Arithmetic #include <iostream.h> void main() int* p1; // simple way of defining pointers int* p2; int* p3; int x; p2 = &x; p1 = p2; p2 = p2 + 5; cout << (p2 - p1);// prints the number of elements // between the two pointers, which is 5 // p3 = p2 + p1; is illegal operation

23 Allowed Pointer Arithmetic Following are the allowed pointer operations: Subtraction of pointers results in the number of elements between the pointers Addition of integral values in pointers Add or subtract pointers with an integral value Adding two pointers is not allowed

24 Dynamic memory management new operator allocates memory and returns a pointer to the newly created object. When an object, that is allocated by new, is no longer referenced, an operator delete must be applied to the object, through its pointer, to avoid memory leakage

25 Cont. Example: string *str_ptr; str_ptr = new string("hello"); cout<< *str_ptr << endl; //Hellow cout<< (*str_ptr).length() <<endl; //5 delete str_ptr;

26 Relationship Between Pointers and Arrays Arrays and pointers closely related Array name like constant pointer Pointers can do array subscripting operations Accessing array elements with pointers Element b[ n ] can be accessed by *( bptr + n ) Called pointer/offset notation Addresses &b[ 3 ] same as bptr + 3 Array name can be treated as pointer b[ 3 ] same as *( b + 3 ) Pointers can be subscripted (pointer/subscript notation) bptr[ 3 ] same as b[ 3 ] 1

27

28 Pointers to arrays A pointer variable can be used to access the eleme of an array of the same type. int gradelist[8] = 92,85,75,88,79,54,34,96; int *mygrades = gradelist; cout << gradelist[1]; cout << *mygrades; cout << *(mygrades + 2); cout << mygrades[3]; Note that the array name gradelistacts like the pointer variable mygrades. 3

29 // Using subscripting and pointer notations with arrays. #include <iostream> using std::cout; using std::endl; int main() int b[] = 10, 20, 30, 40 ; int *bptr = b; // set bptr to point to array b // output array b using array subscript notation cout << "Array b printed with Array subscript notation\n"; for ( int i = 0; i < 4; i++ ) cout << "b[" << i << "] = " << b[ i ] << '\n'; Using array sub notation. // output array b using the array name and pointer/offset notation cout << "\npointer/offset notation where the pointer is the array name\n";

30 for ( int offset1 = 0; offset1 < 4; offset1++ ) cout << "*(b + " << offset1 << ") = " << *( b + offset1 ) << '\n'; // output array b using bptr and array subscript notation cout << "\npointer subscript notation\n"; for ( int j = 0; j < 4; j++ ) cout << "bptr[" << j << "] = " << bptr[ j ] << '\n'; cout << "\npointer/offset notation\n"; // output array b using bptr and pointer/offset notation for ( int offset2 = 0; offset2 < 4; offset2++ ) cout << "*(bptr + " << offset2 << ") = " << *( bptr + offset2 ) << '\n'; return 0; // indicates successful termination // end main

31

32 Arrays of Pointers Arrays can contain pointers Commonly used to store array of strings char *suit[ 4 ] = "Hearts", "Diamonds", "Clubs", "Spades" ; Each element of suit points to char * (a string) Array does not store strings, only pointers to strings suit[0] H e a r t s \0 suit[1] D i a m o n d s \0 suit[2] C l u b s \0 suit[3] S p a d e s \0 suitarray has fixed size, but strings can be of any size 7

33 Example // string and pointer example #include < iostream> using namespace std; int main ( ) int n; char *seasons [ ] = Winter, Spring, Summer, Fall ; cout << \n Enter a month (use 1 for Jan, 2 for Feb, etc): ;

34 Example (Cont..) cin >> n; n = (n % 12) / 3; // create the correct subscript cout << The month entered is a << seasons [ n // or * (seasons + n) << month << endl; return 0;

35 Example The following example is the modification to previous example in this case a function is used to print seasons. #include <iostream> using namespace std; void st_pt ( char *ys [ ], int n); int main ( ) int n; char *seasons [ ] = Winter, Spring, Summer, Fall ;

36 Example (Cont..) cout << \n Enter a month ( use 1 for Jan, etc.) : ; cin >> n; st_pt (seasons, n); return 0; void st_pt (char *ys [ ], int n)

37 Example (Cont..) n = (n%12)/3; cout << The month entered is a << *(ys + n) << month. <<endl;

38 Example (Cont..) The output of the above program is: Enter a month ( use 1 for Jan 2 for Feb, etc.) : 12 The month entered is a Winter month

39 Function Pointers Pointer that can hold function addresses is called Function Pointer Steps required are Define a function pointer Initialise the pointer with function address Call the function by using pointer While defining a function pointer, parenthesis are required otherwise it becomes function declaration

40 Example: Function Pointer void func() cout << "func() called..." << endl; int main() void (*fp)(); // define a function pointer fp = func; // Initialise it, assign function address (*fp)(); // call function using function pointer

41 Pointer To Objects Just like other pointers, the object pointers are declared by placing in front of a object pointer's name. It takes the following general form : class-name object-pointer ; where class-name is the name of an already defined class and object-pointer is the pointer to an object of this class type. For example, to declare optr as an object pointer of Sample class type, we shall write Sample optr ; where Sample is already defined class. When accessing members of a class using an object pointer, the arrow operator (->) is used instead of dot operator.

42 Pointer To Objects Consider Rational r(4,3); Rational rptr = &r; To select a member of r using rptr and member selection, operator precedence requires Invokes member Insert() of the object to which rptr points (r) (*rptr).insert(cout); This syntax is clumsy, so C++ provides the indirect member selector operator -> Invokes member Insert() of the object to which rptr points (r) rptr->insert(cout);

43 Pointer To Objects The following program illustrates how to access an object given a pointer to it. This C++ program illustrates the use of object pointer #include<iostream.h> #include<conio.h> class Time short int hh, mm, ss; public: Time() hh = mm = ss = 0; void getdata(int i, int j, int k)

44 Pointer To Objects void getdata(int i, int j, int k) hh = i; mm = j; ss = k; void prndata(void) cout<<"\ntime is<< hh<< ": << mm << ": <<ss<<"\n"; ; //class Time Ends

45 Pointer To Objects void main() clrscr(); Time T1, *tptr; cout<<"initializing data members using the object\n"; T1.getdata(12,22,11); cout<<"printing members using the object "; T1.prndata(); tptr = &T1; cout<<"printing members using the object pointer "; tptr->prndata(); cout<<"\ninitializing data members using the object pointer, \n";

46 Pointer To Objects tptr->getdata(15, 10, 16); cout<<"printing members using the object "; T1.prndata(); cout<<"printing members using the object pointer "; tptr->prndata(); getch();

47 Pointer To Pointers A pointer to a pointer is a form of multiple indirection or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below. A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name. For example, following is the declaration to declare a pointer to a pointer of type int int **var;

48 Pointer To Pointers What is the output?

49 Pointer To Pointers When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk operator be applied twice, as is shown below in the example #include <iostream> using namespace std; int main () int var; int *ptr; int **pptr; var = 3000;

50 // take the address of var ptr = &var; Pointer To Pointers // take the address of ptr using address of operator & pptr = &ptr; // take the value using pptr cout << "Value of var :" << var << endl; cout << "Value available at *ptr :" << *ptr << endl; cout << "Value available at **pptr :" << **pptr << endl; return 0;

51 Output When the above code is compiled and executed, it produces the following result Value of var :3000 Value available at *ptr :3000 Value available at **pptr :3000

52 Linked List Example struct link // one element of list int data; // data item link *next; // pointer to next element ; class linklist private: link* first; // pointer to first link public: linklist() first = NULL; // no argument constructor void additem(int d); // add data item (one link) void display(); // display all links

53 Linked List Example void linklist::additem(int d) // add data item link* newlink = new link; // create a new link newlink->data = d; // give it data d newlink->next=first; // it points to the next link first = newlink; // now first points to this link void linklist::display() // display all links link* current=first; // set ptr to first link while(current!= NULL) // until ptr points beyond last link cout << current->data << ; // print data current=current->next; // move to next link

54 Smart Pointers class Person int age; char* pname; public: Person(): pname(0),age(0) Person(char* pname, int age): pname(pname), age(age) ~Person() void Display() cout<< Name = <<pname<< Age = <<age;

55 Smart Pointers void prin() cout<< Hello ; ; void main() Person* pperson = new Person("Scott", 25); pperson->display(); delete pperson;

56 Smart Pointers Now look at this code, every time I create a pointer, I need to take care of deleting it. This is exactly what we need to avoid. An automatic mechanism is needed which deletes the pointer. Using smart pointers, we can make pointers to work in way that we don t need to explicitly call delete.

57 Smart Pointers Smart pointer is a wrapper class over a pointer with operator like * and -> overloaded. The objects of smart pointer class look like pointer, but can do many things that a normal pointer can t, like automatic destruction reference counting and more. The idea is to make a class with a pointer, destructor and overloaded operators like * and ->.

58 Smart Pointers Since destructor is automatically called when an object goes out of scope, the dynamically allocated memory would automatically deleted (or reference count can be decremented).

59 Example for Smart Pointers #include<iostream> using namespace std; class SmartPtr Person *ptr; // Actual pointer public: // Constructor SmartPtr(Person *p) ptr = p;

60 Example for Smart Pointers // Destructor ~SmartPtr() delete ptr; // Overloading dereferencing operator Peron &operator *() return *ptr; Person *operator ->() //Overloading Access operator return ptr; ;

61 Example for Smart Pointers int main() SmartPtr ptr(new Person()); *ptr = 20; cout << *ptr; // We don't need to call delete ptr: when the object // ptr goes out of scope, destructor for it is automatically // called and destructor does delete ptr. return 0;

62 Use of Smart Pointers Automatic cleanup. Automatic initialization Ownership transfer Reference counting To shorten allocation and deallocation time. Since C++ does not provide automatic garbage collection like some other languages, smart pointers can be used for that purpose.

63 Smart Pointers We can make Smart pointers to work on all types. For this we need to use Templates (covered in next unit) C++ libraries provide implementations of smart pointers in the form of auto_ptr : deprecated unique_ptr : Same as auto_ptr shared_ptr and weak_ptr All these pointers exist in <memory> header file

64 Unique Pointers unique_ptr is a container for a raw pointer, which the unique_ptr is said to own. A unique_ptr explicitly prevents copying of its contained pointer (as would happen with normal assignment), But the std::move function can be used to transfer ownership of the contained pointer to another unique_ptr. A unique_ptr cannot be copied because its copy constructor and assignment operators are explicitly deleted.

65 Unique Pointers std::unique_ptr<int> p1(new int(5)); std::unique_ptr<int> p2 = p1; //Compile error. std::unique_ptr<int> p3 = std::move(p1); //Transfers ownership. p3 now owns the memory and p1 is rendered invalid. p3.reset(); //Deletes the memory. p1.reset(); //Does nothing.

66

67

68

69 Shared Pointers Shared_ptr is a container for a raw pointer. It maintains reference counting ownership of its contained pointer in cooperation with all copies of the shared_ptr. An object referenced by the contained raw pointer will be destroyed when and only when all copies of the shared_ptr have been destroyed.

70 Shared Pointers std::shared_ptr<int> p1(new int(5)); std::shared_ptr<int> p2 = p1; //Both now own the memory. p1.reset(); //Memory still exists, due to p2. p2.reset(); //Deletes the memory, since no one else owns the memory.

71 Pointers to Derived Classes C++ allows base class pointers to point to derived class objects. Let we have class base ; class derived : public base ; Then we can write: base *p1; derived d_obj; p1 = &d_obj;

72 class Base public: void show() cout << base\n ; ; class Derv1 : public base public: void show() cout << derived1\n ; class Derv2 : public base public: void show() cout << derived2\n ; ; void main() Derv1 dv1; Derv2 dv2; Base *ptr ptr = &dv1; ptr->show(); ptr = &dv2; ptr ->show(); return 0; OUTPUT : base base

73 class Base public: virtual void show() cout << base\n ; ; class Derv1 : public base public: void show() cout << derived1\n ; class Derv2 : public base public: void show() cout << derived2\n ; ; void main() Derv1 dv1; Derv2 dv2; Base *ptr ptr = &dv1; ptr->show(); ptr = &dv2; ptr ->show(); return 0; OUTPUT : derived1 derived2

74 Virtual Functions A virtual function is a member function that is declared within a base class and redefined by a derived class. Virtual functions implements the "one interface, multiple methods" philosophy under polymorphism.

75 Virtual Functions The virtual function within the base class defines the form of the interface to that function. Each redefinition of the virtual function by a derived class implements its operation as it relates specifically to the derived class. That is, the redefinition creates a specific method.

76 Non-Virtual Pointer Access

77 Virtual Functions A virtual function is a member function that is declared within a base class and redefined by a derived class. Virtual functions implements the "one interface, multiple methods" philosophy under polymorphism.

78 Virtual Functions The virtual function within the base class defines the form of the interface to that function. Each redefinition of the virtual function by a derived class implements its operation as it relates specifically to the derived class. That is, the redefinition creates a specific method.

79 Virtual Functions To create a virtual function, precede the function s declaration in the base class with the keyword virtual. Example: class base public: virtual void member_func() ;

80 Virtual Functions Base Virtual function Derived1 Derived2 override override

81 Virtual Functions How to implement run-time polymorphism? - create base-class pointer can be used to point to an object of any class derived from that base - initialize derived object(s) to base class object. Based upon which derived class objects assignment to the base class pointer, c++ determines which version of the virtual function to be called. And this determination is made at run time.

82 Virtual Functions The redefinition of a virtual function by a derived class appears similar to function overloading? No The prototype for a redefined virtual function must match exactly the prototype specified in the base class.

83 Restrictions: Virtual Functions All aspects of its prototype must be the same as base class virtual function. Virtual functions are of non-static members. Virtual functions can not be friends. Constructor functions cannot be virtual. But destructor functions can be virtual. NOTE: Function overriding is used to describe virtual function redefinition by a derived class.

84 Virtual Functions When accessed "normally" virtual functions behave just like any other type of class member function. But virtual functions importance and capacity lies in supporting the run-time polymorphism when they accessed via a pointer.

85 Abstract Classes and Pure Virtual Functions A base class whose objects are never instantiated is called an abstract class. Such a class exists only to act as a parent of derived classes that will be used to instantiate objects. A base class made as an abstract class must contain at least one pure virtual function. A pure virtual function is one with the expression =0 added to the function declaration. e.g., virtual void show() = 0;

86 Pure Virtual Functions When a virtual function is made pure, any derived class must provide its definition. If the derived class fails to override the pure virtual function, a compile-time error will result. NOTE: When a virtual function is declared as pure, then all derived classes must override it.

87 class Base public: virtual void show() = 0; ; class Derv1 : public base public: void show() cout << derived1\n ; class Derv2 : public base public: void show() cout << derived2\n ; ; void main() Base bad; Derv1 dv1; Derv2 dv2; Base *ptr ptr = &dv1; ptr->show(); ptr = &dv2; ptr ->show(); return 0; //ERROR

88 Virtual Destructors Without Normally, when one deletes an instance of a derived class (e.g., Car), the destructors of the derived class and those of all the ancestor classes are executed (in this case, the Vehicle destructor) But let s assume that we are given the following statement Vehicle* a = new Car( Ferrari ); What happens when one executes the following statement? delete a;

89 Virtual Destructors Why? Since the classes involved in the example do not have virtual destructors, only the Vehicle destructor is executed! Further, if additional classes appeared in the hierarchy between Vehicle and Car, their destructors would not be executed, either This behavior can lead to memory leaks and other problems, especially when dynamic memory or class variables are managed by the derived class A solution to the problem is the use of virtual destructors

90 Virtual Destructors What? A virtual destructor is simply a destructor that is declared as a virtual function If the destructor of a base class is declared as virtual, then the destructors of all its descendant classes become virtual, too (even though they do not have the same names)

91 Virtual Destructors - rule Rules of thumb for virtual destructors If any class in a hierarchy manages class variables or dynamic memory, make its destructor virtual If none of the classes in a hierarchy have userdefined destructors, do not use virtual destructors

92 #include iostream.h class Base public: Base() cout<<"constructing Base"; // this is a destructor: ~Base() cout<<"destroying Base"; ;

93 class Derive: public Base public: Derive() cout<<"constructing Derive"; ~Derive() cout<<"destroying Derive"; ; void main() Base *baseptr = new Derive(); delete baseptr; OUTPUT : Constructing Base Constructing Derive Destroying Base

94 Based on the output above, we can see that the constructors get called in the appropriate order when we create the Derive class object pointer in the main function. But there is a major problem with the code above: the destructor for the "Derive" class does not get called at all when we delete baseptr.

95 Remedy..? VIRTUAL DESTRUCTOR Well, what we can do is make the base class destructor virtual, and that will ensure that the destructor for any class that derives from Base (in our case, its the "Derive" class) will be called.

96 #include iostream.h class Base public: Base() cout<<"constructing Base"; // this is a destructor: virtual ~Base() cout<<"destroying Base"; ;

97 class Derive: public Base public: Derive() cout<<"constructing Derive"; ~Derive() cout<<"destroying Derive"; ; void main() Base *baseptr = new Derive(); delete baseptr; OUTPUT : Constructing Base Constructing Derive Destroying Derive Destroying Base

98 Early vs. Late Binding Early binding refers to events that occur at compile time. Early binding occurs when all information needed to call a function is known at compile time. Examples : function calls,overloaded function calls, and overloaded operators.

99 Early vs. Late Binding Late binding refers to function calls that are not resolved until run time. Late binding can make for somewhat slower execution times. Example: virtual functions

100 Containership If we create the object of one class into another class and that object will be a member of the class, then it is called containership. This relation is calles has_a relation. While the inheritance is called kind_of and is_a relation.

101 Class upper Public: Void display() Cout<< hello <<endl; ; Class lower Upper obj; Public: Lower() Obj.display(); o/p hello Void main() Lower l; ;

102 Container class also call upper class constructor first like inheritance.it can use only public member of upper class not the private and protected members

103 Class upper Public: upper() Cout<< it is upper class constructor <<endl ; ; Class lower Upper obj; Public: lower() Cout<< it is lower class constructor <<endl ; ; o/p Void main() lower l; it is upper class constructor it is lower class constructor

Pointers. Developed By Ms. K.M.Sanghavi

Pointers. Developed By Ms. K.M.Sanghavi Pointers Developed By Ms. K.M.Sanghavi Memory Management : Dynamic Pointers Linked List Example Smart Pointers Auto Pointer Unique Pointer Shared Pointer Weak Pointer Memory Management In order to create

More information

CSC 211 Intermediate Programming. Arrays & Pointers

CSC 211 Intermediate Programming. Arrays & Pointers CSC 211 Intermediate Programming Arrays & Pointers 1 Definition An array a consecutive group of memory locations that all have the same name and the same type. To create an array we use a declaration statement.

More information

VIRTUAL FUNCTIONS Chapter 10

VIRTUAL FUNCTIONS Chapter 10 1 VIRTUAL FUNCTIONS Chapter 10 OBJECTIVES Polymorphism in C++ Pointers to derived classes Important point on inheritance Introduction to virtual functions Virtual destructors More about virtual functions

More information

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:

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: Unit IV Pointers and Polymorphism in C++ Concepts of Pointer: A pointer is a variable that holds a memory address of another variable where a value lives. A pointer is declared using the * operator before

More information

OOP THROUGH C++(R16) int *x; float *f; char *c;

OOP THROUGH C++(R16) int *x; float *f; char *c; What is pointer and how to declare it? Write the features of pointers? A pointer is a memory variable that stores the address of another variable. Pointer can have any name that is legal for other variables,

More information

The Address-of Operator &: The & operator can find address occupied by a variable. If var is a variable then, &vargives the address of that variable.

The Address-of Operator &: The & operator can find address occupied by a variable. If var is a variable then, &vargives the address of that variable. VIRTUAL FUNCITONS Pointers: Some C++ tasks are performed more easily with pointers, and other C++ tasks, such as dynamic memory allocation, cannot be performed without them. As you know every variable

More information

Pointers! Arizona State University 1

Pointers! Arizona State University 1 Pointers! CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 10 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Pointers and Strings Prentice Hall, Inc. All rights reserved.

Pointers and Strings Prentice Hall, Inc. All rights reserved. Pointers and Strings 1 sizeof operator Pointer Expressions and Pointer Arithmetic Relationship Between Pointers and Arrays Arrays of Pointers Case Study: Card Shuffling and Dealing Simulation sizeof operator

More information

Object Oriented Programming. Solved MCQs - Part 2

Object Oriented Programming. Solved MCQs - Part 2 Object Oriented Programming Solved MCQs - Part 2 Object Oriented Programming Solved MCQs - Part 2 It is possible to declare as a friend A member function A global function A class All of the above What

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

CSE 333 Lecture smart pointers

CSE 333 Lecture smart pointers CSE 333 Lecture 14 -- smart pointers Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia Midterm Friday - Review in sections this week - Closed book; topic list

More information

Polymorphism Part 1 1

Polymorphism Part 1 1 Polymorphism Part 1 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid

More information

C++ 8. Constructors and Destructors

C++ 8. Constructors and Destructors 8. Constructors and Destructors C++ 1. When an instance of a class comes into scope, the function that executed is. a) Destructors b) Constructors c) Inline d) Friend 2. When a class object goes out of

More information

Pointers and Dynamic Memory Allocation

Pointers and Dynamic Memory Allocation Pointers and Dynamic Memory Allocation ALGORITHMS & DATA STRUCTURES 9 TH SEPTEMBER 2014 Last week Introduction This is not a course about programming: It s is about puzzling. well.. Donald Knuth Science

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.. COMP6771 Advanced C++ Programming Week 5 Part Two: Dynamic Memory Management 2016 www.cse.unsw.edu.au/ cs6771 2.. Revisited 1 #include 2 3 struct X { 4 X() { std::cout

More information

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2 Review Fall 2013 CISC2200 Yanjun Li 1 Outline Array Pointer Object-Oriented Programming Fall 2013 CISC2200 Yanjun Li 2 1 Array Arrays are data structures containing related data items of same type. An

More information

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2017 CISC2200 Yanjun Li 1. Fall 2017 CISC2200 Yanjun Li 2

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2017 CISC2200 Yanjun Li 1. Fall 2017 CISC2200 Yanjun Li 2 Review Fall 2017 CISC2200 Yanjun Li 1 Outline Array Pointer Object-Oriented Programming Fall 2017 CISC2200 Yanjun Li 2 1 Computer Fall 2017 CISC2200 Yanjun Li 3 Array Arrays are data structures containing

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

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

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am CMSC 202 Section 010x Spring 2007 Computer Science II Final Exam Name: Username: Score Max Section: (check one) 0101 - Justin Martineau, Tuesday 11:30am 0102 - Sandeep Balijepalli, Thursday 11:30am 0103

More information

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak! //Example showing a bad situation with naked pointers CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms void MyFunction() MyClass* ptr( new

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

PESIT Bangalore South Campus

PESIT Bangalore South Campus USN 1 P E PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of ECE INTERNAL ASSESSMENT TEST 2 Date : 03/10/2017 Marks: 40 Subject & Code : Object Oriented Programming

More information

CSE 333 Lecture smart pointers

CSE 333 Lecture smart pointers CSE 333 Lecture 14 -- smart pointers Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia New exercise out today, due Wednesday morning Exam Friday

More information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms AUTO POINTER (AUTO_PTR) //Example showing a bad situation with naked pointers void MyFunction()

More information

Chapter 1: Object-Oriented Programming Using C++

Chapter 1: Object-Oriented Programming Using C++ Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms

More information

by Pearson Education, Inc. All Rights Reserved.

by Pearson Education, Inc. All Rights Reserved. Let s improve the bubble sort program of Fig. 6.15 to use two functions bubblesort and swap. Function bubblesort sorts the array. It calls function swap (line 51) to exchange the array elements array[j]

More information

CSC1322 Object-Oriented Programming Concepts

CSC1322 Object-Oriented Programming Concepts CSC1322 Object-Oriented Programming Concepts Instructor: Yukong Zhang February 18, 2016 Fundamental Concepts: The following is a summary of the fundamental concepts of object-oriented programming in C++.

More information

Pointer in C SHARDA UNIVERSITY. Presented By: Pushpendra K. Rajput Assistant Professor

Pointer in C SHARDA UNIVERSITY. Presented By: Pushpendra K. Rajput Assistant Professor Pointer in C Presented By: Pushpendra K. Rajput Assistant Professor 1 Introduction The Pointer is a Variable which holds the Address of the other Variable in same memory. Such as Arrays, structures, and

More information

Programming for Engineers Pointers

Programming for Engineers Pointers Programming for Engineers Pointers ICEN 200 Spring 2018 Prof. Dola Saha 1 Pointers Pointers are variables whose values are memory addresses. A variable name directly references a value, and a pointer indirectly

More information

Increases Program Structure which results in greater reliability. Polymorphism

Increases Program Structure which results in greater reliability. Polymorphism UNIT 4 C++ Inheritance What is Inheritance? Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the

More information

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty! Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns

More information

C++ Programming Chapter 7 Pointers

C++ Programming Chapter 7 Pointers C++ Programming Chapter 7 Pointers Yih-Peng Chiou Room 617, BL Building (02) 3366-3603 ypchiou@cc.ee.ntu.edu.tw Photonic Modeling and Design Lab. Graduate Institute of Photonics and Optoelectronics & Department

More information

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

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PROGRAMMING Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PARADIGM Object 2 Object 1 Data Data Function Function Object 3 Data Function 2 WHAT IS A MODEL? A model is an abstraction

More information

Lecture 05 POINTERS 1

Lecture 05 POINTERS 1 Lecture 05 POINTERS 1 Pointers Powerful, but difficult to master Simulate call-by-reference Close relationship with arrays and strings Pointer Variable vs. Normal Variable Normal variables contain a specific

More information

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8 Pointers Variables vs. Pointers: A variable in a program is something with a name and a value that can vary. The way the compiler and linker handles this is that it assigns a specific block of memory within

More information

CS201- Introduction to Programming Current Quizzes

CS201- Introduction to Programming Current Quizzes CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements

More information

Programación de Computadores. Cesar Julio Bustacara M. Departamento de Ingeniería de Sistemas Facultad de Ingeniería Pontificia Universidad Javeriana

Programación de Computadores. Cesar Julio Bustacara M. Departamento de Ingeniería de Sistemas Facultad de Ingeniería Pontificia Universidad Javeriana POINTERS Programación de Computadores Cesar Julio Bustacara M. Departamento de Ingeniería de Sistemas Facultad de Ingeniería Pontificia Universidad Javeriana 2018-01 Pointers A pointer is a reference to

More information

Homework #3 CS2255 Fall 2012

Homework #3 CS2255 Fall 2012 Homework #3 CS2255 Fall 2012 MULTIPLE CHOICE 1. The, also known as the address operator, returns the memory address of a variable. a. asterisk ( * ) b. ampersand ( & ) c. percent sign (%) d. exclamation

More information

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

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1 Polymorphism Part 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid adult

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

RAII and Smart Pointers. Ali Malik

RAII and Smart Pointers. Ali Malik RAII and Smart Pointers Ali Malik malikali@stanford.edu Game Plan Recap Conversion Operators RAII Smart Pointers Recap Initialisation: Initialisation vs Assignment Transforms an object s initial junk data

More information

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016 Chapter 6: User-Defined Functions Objectives In this chapter, you will: Learn about standard (predefined) functions Learn about user-defined functions Examine value-returning functions Construct and use

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Smart Pointers and Constness Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de Summer

More information

C Pointers. sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then

C Pointers. sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then 1 7 C Pointers 7.7 sizeof Operator 2 sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then int myarray[ 10 ]; printf( "%d", sizeof(

More information

Homework 4. Any questions?

Homework 4. Any questions? CSE333 SECTION 8 Homework 4 Any questions? STL Standard Template Library Has many pre-build container classes STL containers store by value, not by reference Should try to use this as much as possible

More information

CS304- Object Oriented Programming LATEST SOLVED MCQS FROM FINALTERM PAPERS. MC

CS304- Object Oriented Programming LATEST SOLVED MCQS FROM FINALTERM PAPERS. MC CS304- Object Oriented Programming LATEST SOLVED MCQS FROM FINALTERM PAPERS JAN 28,2011 MC100401285 Moaaz.pk@gmail.com Mc100401285@gmail.com PSMD01 FINALTERM EXAMINATION 14 Feb, 2011 CS304- Object Oriented

More information

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

OBJ. ORI.& MULT. PROG., M.C.Q. BANK, FOR UNIT -2, SECOND YEAR COMP. ENGG. SEM-4, 2012 PATTERN, U.O.P. UNIT-2 UNIT-2 Syllabus for Unit-2 Introduction, Need of operator overloading, overloading the assignment, binary and unary operators, overloading using friends, rules for operator overloading, type conversions

More information

Pointers. Variable Declaration. Chapter 10

Pointers. Variable Declaration. Chapter 10 Pointers Chapter 10 Variable Declaration When a variable is defined, three fundamental attributes are associated with it: Name Type Address The variable definition associates the name, the type, and the

More information

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2 Discussion 1E Jie(Jay) Wang Week 10 Dec.2 Outline Dynamic memory allocation Class Final Review Dynamic Allocation of Memory Recall int len = 100; double arr[len]; // error! What if I need to compute the

More information

Kapi ap l S e S hgal P T C p t u er. r S. c S ienc n e A n A k n leshw h ar ar Guj u arat C C h - 8

Kapi ap l S e S hgal P T C p t u er. r S. c S ienc n e A n A k n leshw h ar ar Guj u arat C C h - 8 Chapter 8 Introduction C++ Memory Map Free Stores Declaration and Initialization of pointers Dynamic allocation operators Pointers and Arrays Pointers and Const Pointers and Function Pointer and Structures

More information

Smart Pointers. Some slides from Internet

Smart Pointers. Some slides from Internet Smart Pointers Some slides from Internet 1 Part I: Concept Reference: Using C++11 s Smart Pointers, David Kieras, EECS Department, University of Michigan C++ Primer, Stanley B. Lippman, Jesee Lajoie, Barbara

More information

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

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Chapter 6 Inheritance Extending a Class Chapter 6 Inheritance Extending a Class Introduction; Need for Inheritance; Different form of Inheritance; Derived and Base Classes; Inheritance and Access control; Multiple Inheritance Revisited; Multilevel

More information

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... CISC 2000 Computer Science II Fall, 2014 Note 12/1/2014 1 Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... (a) What s the purpose of inheritance?

More information

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

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi Modern C++ for Computer Vision and Image Processing Igor Bogoslavskyi Outline Move semantics Classes Operator overloading Making your class copyable Making your class movable Rule of all or nothing Inheritance

More information

04-24/26 Discussion Notes

04-24/26 Discussion Notes 04-24/26 Discussion Notes PIC 10B Spring 2018 1 When const references should be used and should not be used 1.1 Parameters to constructors We ve already seen code like the following 1 int add10 ( int x

More information

STRUCTURING OF PROGRAM

STRUCTURING OF PROGRAM Unit III MULTIPLE CHOICE QUESTIONS 1. Which of the following is the functionality of Data Abstraction? (a) Reduce Complexity (c) Parallelism Unit III 3.1 (b) Binds together code and data (d) None of the

More information

Pointers, Dynamic Data, and Reference Types

Pointers, Dynamic Data, and Reference Types Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple

More information

More Tutorial on C++:

More Tutorial on C++: More Tutorial on C++: OBJECT POINTERS Accessing members of an object by using the dot operator. class D { int j; void set_j(int n); int mul(); ; D ob; ob.set_j(4); cout

More information

Midterm Review. PIC 10B Spring 2018

Midterm Review. PIC 10B Spring 2018 Midterm Review PIC 10B Spring 2018 Q1 What is size t and when should it be used? A1 size t is an unsigned integer type used for indexing containers and holding the size of a container. It is guarenteed

More information

Fundamentals of Programming Session 20

Fundamentals of Programming Session 20 Fundamentals of Programming Session 20 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

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

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi Modern C++ for Computer Vision and Image Processing Igor Bogoslavskyi Outline Using pointers Pointers are polymorphic Pointer this Using const with pointers Stack and Heap Memory leaks and dangling pointers

More information

Programming, numerics and optimization

Programming, numerics and optimization Programming, numerics and optimization Lecture A-4: Object-oriented programming Łukasz Jankowski ljank@ippt.pan.pl Institute of Fundamental Technological Research Room 4.32, Phone +22.8261281 ext. 428

More information

CS 376b Computer Vision

CS 376b Computer Vision CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves

More information

MYcsvtu Notes LECTURE 34. POINTERS

MYcsvtu Notes LECTURE 34.  POINTERS LECTURE 34 POINTERS Pointer Variable Declarations and Initialization Pointer variables Contain memory addresses as their values Normal variables contain a specific value (direct reference) Pointers contain

More information

C++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

C++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck C++ Crash Kurs Polymorphism Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck http://www.itm.uni-luebeck.de/people/pfisterer C++ Polymorphism Major abstractions of C++ Data abstraction

More information

Chapter 9: Pointers. Copyright 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved.

Chapter 9: Pointers. Copyright 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 9: Pointers 9.1 Getting the Address of a Variable Getting the Address of a Variable Each variable in program is stored at a unique address Use address operator & to get address of a variable: int

More information

Chapter 9: Getting the Address of a Variable. Something Like Pointers: Arrays. Pointer Variables 8/23/2014. Getting the Address of a Variable

Chapter 9: Getting the Address of a Variable. Something Like Pointers: Arrays. Pointer Variables 8/23/2014. Getting the Address of a Variable Chapter 9: Pointers 9.1 Getting the Address of a Variable Getting the Address of a Variable Each variable in program is stored at a unique address Use address operator & to get address of a variable: int

More information

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

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

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

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity. OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

More information

CS304 Object Oriented Programming Final Term

CS304 Object Oriented Programming Final Term 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes? Generalization (pg 29) Sub-typing

More information

Functions. Introduction :

Functions. Introduction : Functions Introduction : To develop a large program effectively, it is divided into smaller pieces or modules called as functions. A function is defined by one or more statements to perform a task. In

More information

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Object-Oriented Programming (OOP) Fundamental Principles of OOP Object-Oriented Programming (OOP) O b j e c t O r i e n t e d P r o g r a m m i n g 1 Object-oriented programming is the successor of procedural programming. The problem with procedural programming is

More information

Friend Functions, Inheritance

Friend Functions, Inheritance Friend Functions, Inheritance Friend Function Private data member of a class can not be accessed by an object of another class Similarly protected data member function of a class can not be accessed by

More information

CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE

CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE a) Mention any 4 characteristic of the object car. Ans name, colour, model number, engine state, power b) What

More information

CS304 Object Oriented Programming

CS304 Object Oriented Programming 1 CS304 Object Oriented Programming 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes?

More information

CS2255 HOMEWORK #1 Fall 2012

CS2255 HOMEWORK #1 Fall 2012 CS55 HOMEWORK #1 Fall 01 1.What is assigned to the variable a given the statement below with the following assumptions: x = 10, y = 7, and z, a, and b are all int variables. a = x >= y; a. 10 b. 7 c. The

More information

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

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING THROUGH C++ Practical: OOPS THROUGH C++ Subject Code: 1618407 PROGRAM NO.1 Programming exercise on executing a Basic C++

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

CS31 Discussion. Jie(Jay) Wang Week8 Nov.18

CS31 Discussion. Jie(Jay) Wang Week8 Nov.18 CS31 Discussion Jie(Jay) Wang Week8 Nov.18 Outline Pointer Struct Memory Management When the program gets executed, it gets some amount of memory allocated for use. memory Program 1 Program 2 Memory Management

More information

Pointers. Pointers. Pointer Variables. Pointers

Pointers. Pointers. Pointer Variables. Pointers Pointers Pointers Pointers Pointers and Arrays Pointers and function arguments Dynamic memory management New and delete Pointers are used to: Access array elements Passing arguments to functions when the

More information

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a. Intro to OOP - Object and class - The sequence to define and use a class in a program - How/when to use scope resolution operator - How/when to the dot operator - Should be able to write the prototype

More information

C++ (Non for C Programmer) (BT307) 40 Hours

C++ (Non for C Programmer) (BT307) 40 Hours C++ (Non for C Programmer) (BT307) 40 Hours Overview C++ is undoubtedly one of the most widely used programming language for implementing object-oriented systems. The C++ language is based on the popular

More information

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable Basic C++ Overview C++ is a version of the older C programming language. This is a language that is used for a wide variety of applications and which has a mature base of compilers and libraries. C++ is

More information

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions. Dr.G.R.Damodaran College of Science (Autonomous, affiliated to the Bharathiar University, recognized by the UGC)Reaccredited at the 'A' Grade Level by the NAAC and ISO 9001:2008 Certified CRISL rated 'A'

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010 CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)

More information

Fundamentals of Programming Session 24

Fundamentals of Programming Session 24 Fundamentals of Programming Session 24 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Evolution of Programming Languages

Evolution of Programming Languages Evolution of Programming Languages 40's machine level raw binary 50's assembly language names for instructions and addresses very specific to each machine 60's high-level languages: Fortran, Cobol, Algol,

More information

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

CS 162, Lecture 25: Exam II Review. 30 May 2018 CS 162, Lecture 25: Exam II Review 30 May 2018 True or False Pointers to a base class may be assigned the address of a derived class object. In C++ polymorphism is very difficult to achieve unless you

More information

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

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++ CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many

More information

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

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object CHAPTER 1 Introduction to Computers and Programming 1 1.1 Why Program? 1 1.2 Computer Systems: Hardware and Software 2 1.3 Programs and Programming Languages 8 1.4 What is a Program Made of? 14 1.5 Input,

More information

Advanced C++ 4/13/2017. The user. Types of users. Const correctness. Const declaration. This pointer and const.

Advanced C++ 4/13/2017. The user. Types of users. Const correctness. Const declaration. This pointer and const. The user. Advanced C++ For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 #define private public #define protected public #define class struct Source: Lutz

More information

Ch. 12: Operator Overloading

Ch. 12: Operator Overloading Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42

More information

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE? 1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity

More information

Functions, Arrays & Structs

Functions, Arrays & Structs Functions, Arrays & Structs Unit 1 Chapters 6-7, 11 Function Definitions! Function definition pattern: datatype identifier (parameter1, parameter2,...) { statements... Where a parameter is: datatype identifier

More information

CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism

CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism Review from Lecture 22 Added parent pointers to the TreeNode to implement increment and decrement operations on tree

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

More information

CSE 303: Concepts and Tools for Software Development

CSE 303: Concepts and Tools for Software Development CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects

More information