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

Size: px
Start display at page:

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

Transcription

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

The mechanism that allows us to extend the definition of a class without making any physical changes to the existing class is called inheritance. Class : BCA 3rd Semester Course Code: BCA-S3-03 Course Title: Object Oriented Programming Concepts in C++ Unit III Inheritance The mechanism that allows us to extend the definition of a class without making

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

Inheritance, and Polymorphism.

Inheritance, and Polymorphism. Inheritance and Polymorphism by Yukong Zhang Object-oriented programming languages are the most widely used modern programming languages. They model programming based on objects which are very close to

More information

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

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year Object Oriented Programming Assistant Lecture Omar Al Khayat 2 nd Year Syllabus Overview of C++ Program Principles of object oriented programming including classes Introduction to Object-Oriented Paradigm:Structures

More information

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

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer: Chapter-11 POINTERS Introduction: Pointers are a powerful concept in C++ and have the following advantages. i. It is possible to write efficient programs. ii. Memory is utilized properly. iii. Dynamically

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

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

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

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

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com More C++ : Vectors, Classes, Inheritance, Templates with content from cplusplus.com, codeguru.com 2 Vectors vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information

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

More C++ : Vectors, Classes, Inheritance, Templates Vectors More C++ : Vectors,, Inheritance, Templates vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes defined differently can be resized without explicit

More information

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

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay Classes - 2 Data Processing Course, I. Hrivnacova, IPN Orsay OOP, Classes Reminder Requirements for a Class Class Development Constructor Access Control Modifiers Getters, Setters Keyword this const Member

More information

Introduction Of Classes ( OOPS )

Introduction Of Classes ( OOPS ) Introduction Of Classes ( OOPS ) Classes (I) A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class.

More information

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

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT Two Mark Questions UNIT - I 1. DEFINE ENCAPSULATION. Encapsulation is the process of combining data and functions

More information

What is Class? Remember

What is Class? Remember What is Class? The mechanism that allows you to combine data and the function in a single unit is called a class. Once a class is defined, you can declare variables of that type. A class variable is called

More information

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

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

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

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual

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

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

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

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

POINTERS - Pointer is a variable that holds a memory address of another variable of same type. - It supports dynamic allocation routines. - It can improve the efficiency of certain routines. C++ Memory

More information

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR 603203 DEPARTMENT OF COMPUTER SCIENCE & APPLICATIONS QUESTION BANK (2017-2018) Course / Branch : M.Sc CST Semester / Year : EVEN / II Subject Name

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

ECE 3574: Dynamic Polymorphism using Inheritance

ECE 3574: Dynamic Polymorphism using Inheritance 1 ECE 3574: Dynamic Polymorphism using Inheritance Changwoo Min 2 Administrivia Survey on class will be out tonight or tomorrow night Please, let me share your idea to improve the class! 3 Meeting 10:

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

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

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

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

Recharge (int, int, int); //constructor declared void disply(); Constructor and destructors in C++ Constructor Constructor is a special member function of the class which is invoked automatically when new object is created. The purpose of constructor is to initialize

More information

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

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University) Estd: 1994 JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli - 621014 (An approved by AICTE and Affiliated to Anna University) ISO 9001:2000 Certified Subject Code & Name : CS 1202

More information

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate

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

C++ Classes, Constructor & Object Oriented Programming

C++ Classes, Constructor & Object Oriented Programming C++ Classes, Constructor & Object Oriented Programming Object Oriented Programming Programmer thinks about and defines the attributes and behavior of objects. Often the objects are modeled after real-world

More information

C++ Quick Guide. Advertisements

C++ Quick Guide. Advertisements C++ Quick Guide Advertisements Previous Page Next Page C++ is a statically typed, compiled, general purpose, case sensitive, free form programming language that supports procedural, object oriented, and

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

Object-Oriented Design (OOD) and C++

Object-Oriented Design (OOD) and C++ Chapter 2 Object-Oriented Design (OOD) and C++ At a Glance Instructor s Manual Table of Contents Chapter Overview Chapter Objectives Instructor Notes Quick Quizzes Discussion Questions Projects to Assign

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

Object Oriented Programming(OOP).

Object Oriented Programming(OOP). Object Oriented Programming(OOP). OOP terminology: Class : A class is a way to bind data and its associated function together. It allows the data to be hidden. class Crectangle Data members length; breadth;

More information

Lecture 5: Inheritance

Lecture 5: Inheritance McGill University Computer Science Department COMP 322 : Introduction to C++ Winter 2009 Lecture 5: Inheritance Sami Zhioua March 11 th, 2009 1 Inheritance Inheritance is a form of software reusability

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

Constructor - example

Constructor - example Constructors A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is same as the class name. The constructor is invoked whenever

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

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

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

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

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018 Pointer Basics Lecture 13 COP 3014 Spring 2018 March 28, 2018 What is a Pointer? A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory

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

C++ Programming: Polymorphism

C++ Programming: Polymorphism C++ Programming: Polymorphism 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Run-time binding in C++ Abstract base classes Run-time type identification 2 Function

More information

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

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c. Chapter 9: Pointers 9.1 Getting the Address of a Variable C++ Variables [ not in book ] A Variable has all of the following attributes: 1. name 2. type 3. size 4. value 5. storage class static or automatic

More information

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

A A B U n i v e r s i t y A A B U n i v e r s i t y Faculty of Computer Sciences 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 Week 10: I n h e r i t a n c e Asst. Prof. Dr. M entor Hamiti mentor.hamiti@universitetiaab.com

More information

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

Classes and Objects. Class scope: - private members are only accessible by the class methods. Class Declaration Classes and Objects class class-tag //data members & function members ; Information hiding in C++: Private Used to hide class member data and methods (implementation details). Public

More information

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

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FACULTY INFORMATION TECHNOLOGY AND COMMUNICATION (FTMK) BITE 1513 GAME PROGRAMMING I. y UNIVERSITI TEKNIKAL MALAYSIA MELAKA FACULTY INFORMATION TECHNOLOGY AND COMMUNICATION (FTMK) BITE 1513 GAME PROGRAMMING I Lab Module 7 CLASSES, INHERITANCE AND POLYMORPHISM Department of Media Interactive

More information

Data Structures using OOP C++ Lecture 3

Data Structures using OOP C++ Lecture 3 References: th 1. E Balagurusamy, Object Oriented Programming with C++, 4 edition, McGraw-Hill 2008. 2. Robert L. Kruse and Alexander J. Ryba, Data Structures and Program Design in C++, Prentice-Hall 2000.

More information

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

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes Based on Introduction to Java Programming, Y. Daniel Liang, Brief Version, 10/E 1 Creating Classes and Objects Classes give us a way of defining custom data types and associating data with operations on

More information

PROGRAMMING IN C++ COURSE CONTENT

PROGRAMMING IN C++ COURSE CONTENT PROGRAMMING IN C++ 1 COURSE CONTENT UNIT I PRINCIPLES OF OBJECT ORIENTED PROGRAMMING 2 1.1 Procedure oriented Programming 1.2 Object oriented programming paradigm 1.3 Basic concepts of Object Oriented

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

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

Cpt S 122 Data Structures. Course Review Midterm Exam # 2 Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm

More information

Module 10 Inheritance, Virtual Functions, and Polymorphism

Module 10 Inheritance, Virtual Functions, and Polymorphism Module 10 Inheritance, Virtual Functions, and Polymorphism Table of Contents CRITICAL SKILL 10.1: Inheritance Fundamentals... 2 CRITICAL SKILL 10.2: Base Class Access Control... 7 CRITICAL SKILL 10.3:

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

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

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++ No. of Printed Pages : 3 I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination 05723. June, 2015 BCS-031 : PROGRAMMING IN C ++ Time : 3 hours Maximum Marks : 100 (Weightage 75%)

More information

What is an algorithm?

What is an algorithm? Announcements CS 142 C++ Pointers Reminder Program 6 due Sunday, Nov. 9 th by 11:55pm 11/3/2014 2 Pointers and the Address Operator Pointer Variables Each variable in a program is stored at a unique address

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

COEN244: Class & function templates

COEN244: Class & function templates COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library

More information

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

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING CS6456 OBJECT ORIENTED PROGRAMMING DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING CS6456 OBJECT ORIENTED PROGRAMMING Unit I : OVERVIEW PART A (2 Marks) 1. Give some characteristics of procedure-oriented

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

Department of Computer science and Engineering Sub. Name: Object oriented programming and data structures Sub. Code: EC6301 Sem/Class: III/II-ECE Staff name: M.Kavipriya Two Mark Questions UNIT-1 1. List

More information

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

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics PIC 10A Pointers, Arrays, and Dynamic Memory Allocation Ernest Ryu UCLA Mathematics Pointers A variable is stored somewhere in memory. The address-of operator & returns the memory address of the variable.

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

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

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. 1 C How to Program, 6/e 1 Structures : Aggregate data types are built using elements of other types struct Time { int hour; int minute; Members of the same structure must have unique names. Two different

More information

CLASSES AND OBJECTS IN JAVA

CLASSES AND OBJECTS IN JAVA Lesson 8 CLASSES AND OBJECTS IN JAVA (1) Which of the following defines attributes and methods? (a) Class (b) Object (c) Function (d) Variable (2) Which of the following keyword is used to declare Class

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

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

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

Module Operator Overloading and Type Conversion. Table of Contents

Module Operator Overloading and Type Conversion. Table of Contents 1 Module - 33 Operator Overloading and Type Conversion Table of Contents 1. Introduction 2. Operator Overloading 3. this pointer 4. Overloading Unary Operators 5. Overloading Binary Operators 6. Overloading

More information

Sri Vidya College of Engineering & Technology

Sri Vidya College of Engineering & Technology UNIT I INTRODUCTION TO OOP AND FUNDAMENTALS OF JAVA 1. Define OOP. Part A Object-Oriented Programming (OOP) is a methodology or paradigm to design a program using classes and objects. It simplifies the

More information

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

KLiC C++ Programming. (KLiC Certificate in C++ Programming) KLiC C++ Programming (KLiC Certificate in C++ Programming) Turbo C Skills: Pre-requisite Knowledge and Skills, Inspire with C Programming, Checklist for Installation, The Programming Languages, The main

More information

Object Oriented Programming COP3330 / CGS5409

Object Oriented Programming COP3330 / CGS5409 Object Oriented Programming COP3330 / CGS5409 Classes & Objects DDU Design Constructors Member Functions & Data Friends and member functions Const modifier Destructors Object -- an encapsulation of data

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

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

What is Pointer? Pointer is a variable that holds a memory address, usually location of another variable. CHAPTER 08 POINTERS What is Pointer? Pointer is a variable that holds a memory address, usually location of another variable. The Pointers are one of the C++ s most useful and powerful features. How Pointers

More information

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

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value Paytm Programming Sample paper: 1) A copy constructor is called a. when an object is returned by value b. when an object is passed by value as an argument c. when compiler generates a temporary object

More information

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

Distributed Real-Time Control Systems. Lecture 14 Intro to C++ Part III Distributed Real-Time Control Systems Lecture 14 Intro to C++ Part III 1 Class Hierarchies The human brain is very efficient in finding common properties to different entities and classify them according

More information

Introduction to Classes

Introduction to Classes Introduction to Classes Procedural and Object-Oriented Programming Procedural and Object-Oriented Programming Procedural programming focuses on the process/actions that occur in a program Object-Oriented

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

G52CPP C++ Programming Lecture 13

G52CPP C++ Programming Lecture 13 G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and

More information

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

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology Lecture 8: Object-Oriented Programming (OOP) 1 Introduction to C++ 2 Overview Additional features compared to C: Object-oriented programming (OOP) Generic programming (template) Many other small changes

More information

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

Classes: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods. Classes: Methods, Constructors, Destructors and Assignment For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Piyush Kumar Classes: Member functions // classes

More information

Darshan Institute of Engineering & Technology for Diploma Studies

Darshan Institute of Engineering & Technology for Diploma Studies 1. Explain Call by Value vs. Call by Reference Or Write a program to interchange (swap) value of two variables. Call By Value In call by value pass value, when we call the function. And copy this value

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

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Classes Chapter 4 Classes and Objects Data Hiding and Encapsulation Function in a Class Using Objects Static Class members Classes Class represents a group of Similar objects A class is a way to bind the

More information

PROGRAMMING LANGUAGE 2

PROGRAMMING LANGUAGE 2 31/10/2013 Ebtsam Abd elhakam 1 PROGRAMMING LANGUAGE 2 Java lecture (7) Inheritance 31/10/2013 Ebtsam Abd elhakam 2 Inheritance Inheritance is one of the cornerstones of object-oriented programming. It

More information

CPS 506 Comparative Programming Languages. Programming Language

CPS 506 Comparative Programming Languages. Programming Language CPS 506 Comparative Programming Languages Object-Oriented Oriented Programming Language Paradigm Introduction Topics Object-Oriented Programming Design Issues for Object-Oriented Oriented Languages Support

More information

COEN244: Polymorphism

COEN244: Polymorphism COEN244: Polymorphism Aishy Amer Electrical & Computer Engineering Polymorphism means variable behavior / ability to appear in many forms Outline Casting between objects Using pointers to access objects

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming 1. What is object-oriented programming (OOP)? OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object

More information

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

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1 Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1 Inheritance Consider a new type Square. Following how we declarations for the Rectangle and Circle classes we could declare it as follows:

More information

CS OBJECT ORIENTED PROGRAMMING

CS OBJECT ORIENTED PROGRAMMING UNIT-4 INHERITANCE AND RUN TIME POLYMORPHISM Inheritance public, private, and protected derivations multiple inheritance virtual base class abstract class composite objects Runtime polymorphism virtual

More information

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

Syllabus of C++ Software for Hands-on Learning: This course offers the following modules: Module 1: Getting Started with C++ Programming Syllabus of C++ Software for Hands-on Learning: Borland C++ 4.5 Turbo C ++ V 3.0 This course offers the following modules: Module 1: Getting Started with C++ Programming Audience for this Course Job Roles

More information

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

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module

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

C++ (classes) Hwansoo Han

C++ (classes) Hwansoo Han C++ (classes) Hwansoo Han Inheritance Relation among classes shape, rectangle, triangle, circle, shape rectangle triangle circle 2 Base Class: shape Members of a class Methods : rotate(), move(), Shape(),

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