PESIT Bangalore South Campus

Similar documents
mywbut.com Inheritance

Constructor - example

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING REWRAP TEST I CS6301 PROGRAMMING DATA STRUCTURES II

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:

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

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

Module Operator Overloading and Type Conversion. Table of Contents

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

C++ 8. Constructors and Destructors

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

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

More Tutorial on C++:

public : int min, hour ; T( ) //here constructor is defined inside the class definition, as line function. { sec = min = hour = 0 ; }

Downloaded from

Data Structures using OOP C++ Lecture 3

OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES

UNIT POLYMORPHISM

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

CHAPTER 4 FUNCTIONS. 4.1 Introduction

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

Darshan Institute of Engineering & Technology for Diploma Studies

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

VIRTUAL FUNCTIONS Chapter 10

CONSTRUCTORS AND DESTRUCTORS

Object-Oriented Programming (OOP) Fundamental Principles of OOP

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

MAHALAKSHMI ENGINEERING COLLEGE B TIRUCHIRAPALLI

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

DE122/DC106 Object Oriented Programming with C++ DEC 2014

Some important concept in oops are 1) Classes 2) Objects 3) Data abstraction & Encapsulation. 4) Inheritance 5) Dynamic binding. 6) Message passing

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

Overloading operators

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

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

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

Pointers and Dynamic Memory Allocation

Introduction Of Classes ( OOPS )

Object Oriented Programming. Solved MCQs - Part 2

Object Oriented Programming

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Electronics and Communication

Operator overloading: extra examples


cout<< \n Enter values for a and b... ; cin>>a>>b;

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

Instantiation of Template class

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

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

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Electronics and Communication

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


Developed By Strawberry

Overloading Operators in C++

Operator overloading

III. Classes (Chap. 3)

CS35 - Object Oriented Programming

OOP. Unit:3.3 Inheritance

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

Bangalore South Campus

Introduction to C++ Systems Programming

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified) Subject Name: Object Oriented Programming

DELHI PUBLIC SCHOOL TAPI

W3101: Programming Languages C++ Ramana Isukapalli

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

CS201 - Introduction to Programming Glossary By

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

Example : class Student { int rollno; float marks; public: student( ) //Constructor { rollno=0; marks=0.0; } //other public members };

Polymorphism Part 1 1

Constructors and Destructors. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

Programming in C++: Assignment Week 4

2. Distinguish between a unary, a binary and a ternary operator. Give examples of C++ operators for each one of them.

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.

Interview Questions of C++

Data Structures using OOP C++ Lecture 6

CS304 Object Oriented Programming

Short Notes of CS201

INTRODUCTION TO PROGRAMMING

UNIT III- INHERITANCE AND POLYMORPHISM

AN OVERVIEW OF C++ 1

Object oriented programming

Exercise1. // classes first example. #include <iostream> using namespace std; class Rectangle. int width, height; public: void set_values (int,int);

+2 Volume II OBJECT TECHNOLOGY OBJECTIVE QUESTIONS R.Sreenivasan SanThome HSS, Chennai-4. Chapter -1

Advanced Systems Programming

Programming in C++: Assignment Week 4

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

- HALF YEARLY EXAM ANSWER KEY DEC-2016 COMPUTER SCIENCE ENGLISH MEDIUM

Chapter 10 Introduction to Classes

STRUCTURING OF PROGRAM

Function Overloading

C++ Important Questions with Answers

CS304 Object Oriented Programming Final Term

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of MCA

EL2310 Scientific Programming

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

Object Oriented Programming

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

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Transcription:

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 using C++ - Sem & Sec: 5 th A & B 15EC562 Name of faculty : Shwetha S Bhat Time : 11:30am -1:00pm Note: Answer FIVE full questions, selecting any ONE full question from each part Marks PART 1 1 a Define c++ features: a) Polymorphism b) Multiple Inheritance c) String handling d) Multiple level Inheritance 8 OR 2 a Define destructor and explain the use of destructor with example 4 b Write the characteristics of constructors 4 PART 2 3 a Define this pointer. Give example of accessing and returning of object using this pointer b What is Operator Overloading function? Write a program to add two complex numbers using overloading the operator + function OR 4 a Explain private, public and protected inheritance of a derived class from base class with an example for each 4 4 8 PART 3 5 a Write a program to overload both prefix and postfix increment operator using 8 operator function and display the output before and after the operation OR 6 a What are the types of constructors and explain each with an example 8 PART 4 7 a What are the rules followed for operator overloading if the function is declared as member function and as friend function for unary and binary operators 8

OR 8 a Explain the difference between Virtual function and Pure Virtual function with example b Write the methods to access the data member or member function using pointer to objects 6 2 PART 5 9 a Write a program to add two integer numbers. Use numbers as base class, readnums, printnums and caladdn as derived class and incorporate inheritance OR 10 a Write a program to get a square and cube of a number using hierarchical inheritance 8 8

P.E.S. Institute of Technology( Bangalore South Campus) Hosur Road, ( 1Km Before Electronic City), Bangalore 560100. Department of Electronics and Communication SCHEME AND SOLUTION _II INTERNAL TEST Faculty: Shwetha S Bhat Semester: 5 th A & B Subject: Object Oriented Programming using C++ Sub. Code: 15EC562 Q.No. Questions and its answers Marks 1. a.) Define C++ features (8 marks) a) Polymorphism Property by which objects belonging to different classes are able to respond to name/work in different forms It is supported by C++ both at compile time and at run time. Compile-time polymorphism is achieved by overloading functions and operators. Run-time polymorphism is accomplished by using inheritance and virtual functions. b) Multiple Inheritance It is possible for a derived class to inherit two or more base classes. Deriving directly from more than one class is usually called multiple inheritance. c) String handling Class by name string is available to perform any operations like merging of strings, conditional checks on strings etc. The class can be used best with new operator to allocate memory for each string and a pointer variable to point to the string array. d) Multiple level Inheritance A child class is derived from a base class and again a new child class is derived from this 1 st child class and so on. Hence the property of base class and the property of the 1 st child class can be accessed by the 2 nd child class. 2.) a.) Define destructor and explain the use of destructor with example (4 marks) A destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class. A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc. Syntax ~sample() // Destructor for the constructor sample()

#include <iostream> class Line void setlength( double len ); double getlength( void ); Line(); ~Line(); private: double length; ; Line::Line(void) cout << "Object is being created"; Line::~Line(void) cout << "Object is being deleted"; void Line::setLength( double len ) length = len; double Line::getLength( void ) return length; int main( ) Line line; line.setlength(6.0); // set line length cout << "Length of line : " << line.getlength(); return 0; b.) Write the characteristics of constructors (4 marks) It must be declared in the public section Constructor has the same of a class to which it belongs Does not have a return type, not even void Every object of the class containing a constructor is initialized A constructor cannot be inherited although a derived class can call the base class constructor. A constructor can have default arguments. Address of constructor cannot be referred to. A constructor cannot be virtual. An object with a constructor must not be used as a member of a union 3.) a.) Define this pointer. Give example of accessing and returning of object using this pointer (4 marks)

Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object. This pointer are not modifiable. This pointer is a pointer to the class type. Therefore it can be used to access the data members of the object. Accessing : #include<iostream> class where private: int alpha; void tester() this->alpha=11; //same as alpha=11 cout<<this->alpha; //same as cout<<alpha; int main() where w; w.tester(); return 0; Returning : The expression *this is commonly used to return the current object from a member function as in return *this; The special property of the this pointer is that, it points to the invoking object. When the method requires reference to the invoking object as a whole, it uses the expression *this; However, when you want to return an object this cannot be used since it is the address of the object. Therefore to return the object itself return *this; is used applying deference operator * to a pointer,gives the value to which the pointer is pointing b.) What is Operator Overloading function? Write a program to add two complex numbers using overloading the operator + function (4 marks)

Operator overloading function is a special function which provides the relation of an operator to the class it belongs to. Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list. Syntax return-type classname ::operator op (argument list) //statements return-type datatype of the value returned by operator function. Mostly it s the classtype for which it is defined. operator is the keyword op is the operator which is overloaded and operator op is the function name argument list list of arguments to be passed #include <iostream.h> using namespace std class complex float x,y; complex() //constructor 1 complex(float r, float i) // constructor 2 x = r ; y=i ; void display(void); complex operator +(complex); ; complex complex::operator +(complex c) complex temp; temp.x = x+c.x; temp.y = y+c.y; return(temp); void complex :: display(void) cout <<x<< +j <<y<<endl; void main() complex c1, c2, c3; //invoke constructor1 c1 = complex (1.1, 2.1); //invoke constructor2 c2 = complex (3.5, 4.2); //invoke constructor 2 c3 = c1 + c2; //activates operator+( ) function // c3 = c1.operator+(c2) cout << c1.display(); //c1 = 1.1 + j2.1 cout << c2.display(); //c2 = 3.5 + j4.2 cout << c3.display(); //c3 = 4.6 + j6.3 return 0;

4.) a.) Explain private, public and protected inheritance of a derived class from base class with an example for each (8 Marks) PUBLIC Inheritance: If a child class is inherited as Public from the base then: A private member of a base class is not accessible by other parts of your program, including any derived class. Protected members behave differently. If the base class is inherited as public, then the base class' protected members become protected members of the derived class and also accessible by the derived class #include <iostream> using namespace std; class base protected: int i, j; // private to base until a child class is created void set(int a, int b) i=a; j=b; void show() cout << i << " " << j ; ; class derived : public base int k; // derived may access base's i and j void setk() k= i * j; void showk() cout << k << "\n"; ; // which can access protected members

int main() derived ob; ob.set(2, 3); ob.show(); ob.setk(); ob.showk(); return 0; // OK, known to derived // OK, known to derived Protected Inheritance: If a child class is inherited as Protected from the base then: It is possible to inherit a base class as protected. When this is done, all public and protected members of the base class become protected members of the derived class. #include <iostream> using namespace std; class base protected: int i, j; // private to base until a child class is // created and can access void setij(int a, int b) i=a; j=b; void showij() cout << i << " " << j << "\n"; ; // Inherit base as protected. class derived : protected base int k; // derived may access base's i and j and setij(). void setk() setij(10, 12); k = i*j; // may access showij() here void showall() cout << k << " "; showij(); ; int main()

derived ob; // ob.setij(2, 3); // illegal, setij() isprotected member of derived ob.setk(); // OK, public member of derived ob.showall(); // OK, public member of derived // ob.showij(); // illegal, showij() is protected // member of derived return 0; Private Inheritance : When the base class is inherited by using the private access specifier, all public and protected members of the base class become private members of the derived class. But they are still accessible by members of the derived class but cannot be accessed by parts of your program that are not members of either the base or derived class. #include <iostream> using namespace std; class base int i, j; void set(int a, int b) i=a; j=b; void show() cout << i << " " << j << "\n"; ; // Public elements of base are private in derived. class derived : private base int k; derived(int x) k=x; void showk() cout << k << "\n"; ; int main() derived ob(3); ob.set(1, 2); // error, can't access set()

ob.show(); // error, can't access show() return 0; 5.) a.) Write a program to overload both prefix and postfix increment operator using operator function and display the output before and after the operation (8 marks) #include<iostream.h> class increment private: int val; increment() val=0; increment(int a) val=a; void operator ++(); void operator ++(int); void show(); ; void increment :: operator ++() ++ val ; void increment :: operator ++(int) val ++; void show () cout<<val; void main() increment d1(5); cout<< Before Incrementing: ; d1.show(); cout<< after overloading prefix++ : ; ++d1; d1.show(); d1++; cout<< After overloading postfix++ : ; d1.show();

Output : Before Incrementing: 5 After overloading prefix++ : 6 After overloading postfix++ : 7 6.) a.) What are the types of constructors and explain each with an example (8 marks) Default Constructor Default constructor is the constructor which doesn't take any argument. It has no parameter. Syntax classs class_name () Constructor Definition ; Ex: class Cube int side; Cube() side=10; ; int main() Cube c; cout << c.side; Parametrized Constructor These are the constructors with parameter. Using this Constructor you can provide different values to data members of different objects, by passing the appropriate values as argument. Ex: class Cube int side; Cube(int x) side=x; ; int main() Cube c1(10); Cube c2(20); Cube c3(30); cout << c1.side;

cout << c2.side; cout << c3.side; Copy Constructor The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to: Initialize one object from another of the same type. Copy an object to pass it as an argument to a function. Copy an object to return it from a function. Ex: class sample private: int m,n; sample() // sample s0; // default constructor sample (int a, int b) // sample s1(100,200); // initializes s1 using constructor1 m=a; n=b; sample() // sample s2; // initializes s0 as a default constructor m=0; n=0; // with initializing the members to zero sample(sample &s1) m=s1.m; n=s1.n; // sample s3(s1); // copy constructor, copies s1 to s3 sample s4= s3; // copy constructor,copies s3 to s4 s3=s1;// does not invoke copy constructor Multiple Constructor (overloading constructor) Class containing more than one constructor All constructor defined with the same name as the class they belong to. All constructors contain different number of arguments. Depending upon the number of arguments, the compiler executes appropriate constructor. Ex: class num private: int a; float b; char c; num (int m, float j, char k);

num (int m, float j); num ( ); ; main() class num x (2, 1.2); class num y (2, 1.1, S ); class num z; Dynamic Constructor Dynamic constructor is used to allocate the memory to the objects at the run time. Memory is allocated at run time with the help of 'new' operator. By using this constructor, we can dynamically initialize the objects. #include <iostream.h> #include <conio.h> class dyncons int * p; dyncons() p=new int; *p=10; dyncons(int v) p=new int; *p=v; int dis() return(*p); ; void main() clrscr(); dyncons o, o1(9); cout<<"the value of object o's p is:"; cout<<o.dis(); cout<<"\nthe value of object 01's p is:"<<o1.dis(); getch(); Output: The value of object o's p is:10 The value of object 01's p is:9

7.) a.) What are the rules followed for operator overloading if the function is declared as member function and as friend function for unary and binary operators (8 marks) a.) If a friend function : For Unary operator : only 1 argument Syntax :- object_name op or op object_name => Interpreted as operator op (object_name) Binary operator (syntax) : 2 arguments Syntax :- obj_1 op obj_2 => Interpreted as operator op (obj_1,obj_2) b.) If member function : (As object is passed implicitly and easily available) For unary operator : No arguments For binary operator : Only 1 argument => Interpreted as x.operator op (y) 8.) a.) Explain the difference between Virtual function and Pure Virtual function with example (6 marks) Pure Virtual function: A pure virtual function is one with the expression =0 added to the declaration. Derived class must either define function or redeclare it as pure virtual functions again The syntax =0 tells the compiler that a virtual function will be pure. No definition is needed for base class show() only declaration is enough In main() if u attempt to create objects of class base, the compiler will complain that you are trying to initiate an object of an abstract class After placing pure virtual function, in base class you must override it in all the derived classes If a class doesn t override the pure virtual function, it will remain as a pure virtual function in an abstract class can t initiate objects from it in the main(). #include <iostream> using namespace std class base virtual void show()=0; // pure virtual fun ; class derv1:public base void show() cout<< derv1 ; ; class derv2:public base void show() cout<< derv2 ; ; int main()

//base bad // can t make objects from abstract class base* arr[2]; //arrays of pointers to base class derv1 dv1; // objects of derived class1 derv2 dv2; // objects of derived class2 arr[0]=&dv1; //put address of dv1 in array arr[1]=&dv2; // put address of dv2 in array arr[0] -> show(); arr[1] -> show(); return 0; OUTPUT: derv1 derv2 Virtual function : A virtual function is a member function that is declared within a base class and redefined by a derived class. To create a virtual function, precede the function's declaration in the base class with the keyword virtual. They can also be empty functions i.e only declared. If the function had not been declared virtual, then the base class function would have been called all the times. Because, the function address would have been statically bound during compile time. But now, as the function is declared virtual it is a candidate for run-time linking and the derived class function is being invoked. Choosing of the function is done at run-time based on the type of object pointed by the base pointer. #include<iostream.h> #include<conio.h> class base virtual void show() cout<<"\n Base class show:"; void display() cout<<"\n Base class display:" ; ; class derived : public base void display() cout<<"\n Derived class display:"; void show() cout<<"\n Derived class show:"; ;

void main() clrscr(); base obj1; base *p; cout<<"\n\t P points to base:\n" ; p=&obj1; p->display(); p->show(); cout<<"\n\t P points to derived:\n"; derived obj2; p=&obj2; p->display(); p->show(); getch(); Output: P points to Base Base class display Base class show P points to derived Base class Display Derived class Show b.) Write the methods to access the data member or member function using pointer to objects (2 marks) Any type that can be used to declare a variable/object can also have a pointer type. Useful in creating objects at run time. Object pointers helps in accessing the public members of an object. Consider the following class: class Rational private: int numerator; int denominator; Rational(int n, int d); void Display(); ; Rational *rp = NULL; Rational r(3,4); rp = &r; r.display() // same as rp->display() // same as (*rp).display() If rp is a pointer to an object, then two notations can be used to reference the instance/object rp points to.

Using the de-referencing operator * (*rp).display(); Using the member access operator -> rp -> Display(); 9.) a.) Write a program to add two integer numbers. Use numbers as base class, readnums, printnums and caladdn as derived class and incorporate inheritance (8 marks) #include <iostream> using namespace std; //class definition class Numbers private: int a; int b; //member function declaration void readnumbers(void); void printnumbers(void); int caladdition(void); ; //member function definitions void Numbers::readNumbers(void) cout<<"enter first number: "; cin>>a; cout<<"enter second number: "; cin>>b; void Numbers::printNumbers(void) cout<<"a= "<<a<<",b= "<<b<<endl; int Numbers::calAddition(void) return (a+b); //main function int main() //declaring object

Numbers num; int add; //variable to store addition //take input num.readnumbers(); //find addition add=num.caladdition(); //print numbers num.printnumbers(); //print addition cout<<"addition/sum= "<<add<<endl; return 0; Output Enter first number: 100 Enter second number: 200 a= 100,b= 200 Addition/sum= 300 10.) a.) Write a program to get a square and cube of a number using hierarchical inheritance (8 marks) /*C++ program to demonstrate example of hierarchical inheritance to get */ /* square and cube of a number.*/ #include <iostream> using namespace std; class Number private: int num; void getnumber(void) ; cout << "Enter an integer number: "; cin >> num; //to return num int returnnumber(void) return num; //Base Class 1, to calculate square of a number class Square:public Number int getsquare(void)

; int num,sqr; num=returnnumber(); //get number from class Number sqr=num*num; return sqr; //Base Class 2, to calculate cube of a number class Cube:public Number private: int getcube(void) int num,cube; num=returnnumber(); //get number from class Number cube=num*num*num; return cube; ; int main() Square objs; Cube objc; int sqr,cube; objs.getnumber(); sqr =objs.getsquare(); cout << "Square of "<< objs.returnnumber() << " is: " << sqr << endl; objc.getnumber(); cube=objc.getcube(); cout << "Cube of "<< objs.returnnumber() << " is: " << cube << endl; return 0; Enter an integer number: 10 Square of 10 is: 100 Enter an integer number: 20 Cube of 10 is: 8000