MAHALAKSHMI ENGINEERING COLLEGE B TIRUCHIRAPALLI 621213 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Sub code: CS2203 SEM: III Sub Name: Object Oriented Programming Year: II UNIT-IV PART-A 1. Write the properties of virtual function.(may-2010) * A pure virtual function has no implementation in the base class. * A class with pure virtual function cannot be instantiated. * It acts like an empty bucket that the derived class is supposed to fill. * A pure virtual member function can be invoked by its derived class. 2. What is visibility mode? What are different inheritance visibility modes supported by c++?(may-2010,nov-2009) There are three visibilities of class members.they are i) Public visibility ii)private visibility iii)protected visibility public visibility The class members are visible to the base class, derived classes and outside the class through the objects private visibility The class members are visible only to the base class itself but not to the derived class protected visibility The class members are visible to the base and derived classes 3. What is Pure Virtual function? (MAY-2011) Pure virtual function is declared as a function with its declaration followed by = 0. Virtual functions are defined with a null body. It has no definition. These are similar to do nothing or dummy function. 4. What is meant by dynamic casting? (MAY-2011)
Dynamic_casting is a new type of operator which enables us to cast polymorphic object in a safe way. It casts the source type to destination type only if valid. 5. Write the prototype for typical pure virtual function. (NOV-2009) class myclass virtual returntype functionname(args) = 0 ; ; 6. Define late binding. (NOV-2010,DEC2011) Binding refers to the linking of a procedure to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at the run-time. 7. What is Inheritance? What are the types of inheritance? (NOV-2012) Inheritance is the most important property of object oriented programming. It is a mechanism of creating a new class from an already defined class. The old class is referred to as base class. And the new one is called derived class. 8. What is meant by Abstract Class? (NOV-2012,MAY2010) Classes containing at least one pure virtual function become abstract classes. Classes inheriting abstract classes must redefine the pure virtual functions; otherwise the derived classes also will become abstract. Abstract classes cannot be instantiated. 9. Give the use of protected access specifier. (NOV-2011) In case of protected derivation, the protected members of the baseclass become protected members of the derived class. The public members of the base class also become the protected members of the derived class. A member is declared as protected is accessible by the member functions within its 10. Difference between virtual function and pure virtual function.(may2011) Virtual Function Virtual functions allow programmers to declare functions in a baseclass, which can be defined in each derived class. A pointer to an object of a base class can also point to the objects of its derived class. Pure Virtual Function
Pure virtual function is declared as a function with its declaration followed by = 0. Virtual functions are defined with a null body. It has no definition. These are similar to do nothing or dummy function. 11. Write some of the basic rules for virtual functions(nov2011) Virtual f unctions must be member of some class. They cannot be static members and they are accessed by using object pointers Virtual f unction in a base class must be defined. Prototypes of base class version of a virtual function and all the derived class versions must be identical. If a virtual function is defined in the base class, it need not be redefined in the derived class 12. What is compile time polymorphism?(may 2011) The overloaded member functions are selected for invoking by matching arguments both type and number.this information is known to the compiler at the compile time and therefore compiler is able to select the appropriate function for a particular call at the compile time itself.this is called early binding or static binding or static linking.also known as compile time polymorphism the following are the types of compile time polymorphism a)function overloading b)operator overloading 13. Define RTTI. Run Time Type Information (RTTI) is a very powerful tool in C++ for finding out the type of an object at run time. RTTI also impacts the performance of the system. Most of the compilers provide RTTI, but disable it by default. Part-B 1. Write short notes on RTTI Down Casting?(MAY-2011) Down Casting: to the base class is UP CASTING. dynamic casting. Example: Class base
virtual void vf( ) ; Class derived : public base( ) ; int main( ) base b; derived d; derived *pd = dynamic_cast <derived*> (&b); return 0; 2. Discuss the different types of inheritance supported by C++ with suitable example (NOV2011,DEC2010) The new classes are created from the existing one is known as Inheritance. The important property of inheritance is Re usability. The properties of existing class are extended to new class. New class are called as derived class and the existing class is known as base class TYPES OF INHERITANCE: (1) Simple / Single (2) Multilevel (3) Hierarchical (4) Multiple (5) Hybrid Single Inheritance: This contains one base class as well as one derived class. Multiple Inheritances: This contains two base classes and one derived class. Multilevel Inheritance: This contains one base class more than one derived classes. Hierarchal Inheritance: This contains one base class more than one derived classes arranged in a level order. Hybrid or Multi - path Inheritance: This contains one base class more than one derived classes and from the derived classes another derivation can be done to get sub derived class. This is the combination of Multiple, Multilevel and Hierarchal Inheritance.
Multiple Inheritances: This contains two base classes and one derived class. Program to derive a class from Multiple Base Classes: Class A int a; ; // Class A declaration Class B int b; ; // Class B declaration Class C int c; ; // Class C declaration Class D int d; ; // Class D declaration Class E : public A, public B, public C, public D // Class E int e; void getdata( ) cout<< Enter the values of a, b, c, d and e: ; cin >>a>>b>>c>>d>>e; void putdata( ) cout<< a= <<a << b= <<b << c= <<c<< d= <<d<< e= <<e; ; void main( ) E x; x.getdata( ); x.putdata( ); Output: Enter the values of a, b, c, d and e: 1 2 3 4 5 a=1 b=2 c=3 d=4 e=5 3. Explain Run Time Polymorphism with an Example(NOV2011) Run-Time Polymorphism Run-time polymorphism is a way for a programmer to take advantage of the benefits offered by polymorphism and late binding. Run-time polymorphism uses virtual functions to create a standard interface and to call the underlying functions. Those function definitions are bound to function calls during run time.
The term virtual function is one of those computer terms that is baffling the first few times you hear it used. Let s pick apart the term and review an example to clear up any confusion you might have. Virtual means that something appears to be real, but isn t real. For example, a flight simulator lets you fly a virtual airplane. The airplane isn t really there, but you have the feeling you are flying a real airplane. In the case of a virtual function, the computer is tricked into thinking a function is defined, but the function doesn t have to be defined at that moment. Instead, the virtual function can be a placeholder for the real function. The real function is defined when the program is running. Run-Time Polymorphism in Action Examining an example is the best way to understand how run-time polymorphism works. The following example is very similar to the previous C++ example. Both programs write and display information about a student. The previous example is a C++ program that uses overloaded methods to implement polymorphism. The following example is a C++ program that uses virtual functions to implement polymorphism. Three classes are defined in this example: Student, UndergradStudent, and GraduateStudent. The Student class is the base class that is inherited by the other classes in the program. A base class is a class that is inherited by another class, which is called a derived class. The Student class defines an attribute called m_id that is used to store the student s ID. It also defines a constructor that receives the student ID in the argument list and assigns the student ID to the m_id attributes. The constructor is called whenever an instance of the class is declared. The last two statements in the Student class definition define two virtual functions: Display() and Write(). The declaration of a virtual function in C++ consists of the keyword virtual, the function signature (name and argument list), and a return value. In Java, methods are virtual by default, unless you use the final keyword. Virtual functions may be actual functions or merely placeholders for real functions that derived classes must provide. If you define a virtual function without a body, that means the derived class must provide it (it has no choice, and the program will not compile otherwise). Classes with such functions are called abstract classes, because they aren t complete classes and are more a guideline for creating actual classes. (For example, an abstract class might state you must create the Display() method. ) In C++, you
can create a virtual function without a body by appending =0 after its signature (also known as a pure virtual function). You use the abstract keyword in Java to create a virtual function without a body. The UndergradStudent class and GraduateStudent class are practically the same except the Display() function identifies the student as either an undergraduate or graduate student when student information is shown on the screen. Both classes define a Write() function and a Display() function. The Write() function copies student information received in the argument list to attributes of the class. The Display() function displays the contents of those attributes and the student ID attribute in the Student class. The main() function is where all the action takes place. The first statement declares a pointer that points to an instance of the Student class. The next two statements declare an instance of the UndergradStudent class and the GraduateStudent class. Notice that the student ID is passed to the constructor of each instance. Each constructor calls the constructor of the Student class, which assigns the student ID to the m_id attribute. Run-time polymorphism is implemented in the next three statements, beginning with the assignment of the address of ustudent to the pointer p. The pointer is then used with the pointer-to-member (->) operator to point to the function Write() and then Display(). After attributes of the undergraduate student are displayed, the program assigns the address of gstudent to the pointer p and then proceeds to call the Write() and Display() functions. Here is the output of the next program: Undergraduate Student: 10 Bob Smith 1 Graduate Student: 23 Mary Jones 1 #include <iostream> #include <string> using namespace std; class Student protected:
int m_id; Student (int i) m_id = i; virtual void display() = 0; virtual void write( int, char[], char[]) = 0; ; class UndergradStudent : public Student protected: int m_graduation; char m_first[80]; char m_last[80]; UndergradStudent(int i) : Student (i) void write( int Grad, char Fname[], char Lname[]) m_graduation = Grad; strcpy(m_first,fname); strcpy(m_last, Lname); void display()
cout << "Undergraduate Student: "<< m_id << " " << m_first <<" " << m_last << " " << m_graduation<< endl; ; class GraduateStudent : public Student protected: int m_graduation; char m_first[80]; char m_last[80]; GraduateStudent(int i) : Student(i) void write( int Grad, char Fname[], char Lname[]) m_graduation = Grad; strcpy(m_first,fname); strcpy(m_last, Lname); void display() cout << "Graduate Student: "<< m_id << " " << m_first <<" " << m_last << " " << m_graduation<< endl; ;
int main() Student * p; UndergradStudent ustudent(10); GraduateStudent gstudent(23); p = &ustudent; p->write(1,"bob","smith") ; p->display(); p = &gstudent; p->write(1,"mary","jones") ; p->display(); return 0; 4. Explain Dynamic Casting, Down Casting and Cross Casting? (DEC2012) Dynamic Casting: points to the user instead it safely converts from a pointer to base type to a pointer to a derived type. Syntax: dynamic_cast <Type*> (object or pointer) This converts pointer to the Type* Example: Class base ; Class derived : public base ; int main( ) base b;
derived d; base *pb=dynamic_cast <base*> (&d); (Derived to Base) derived *pd=dynamic_cast <derived*> (&b); (Base to Derived but can t access) return 0; Down Casting: ference to the base class is UP CASTING. dynamic casting. Example: Class base virtual void vf( ) ; Class derived : public base( ) ; int main( ) base b; derived d; derived *pd = dynamic_cast <derived*> (&b); return 0; Cross Casting: Another dynamic cast feature is Cross Casting. Class A public : virtual ~A( ); ; Class B public : virtual ~B( ); ; Class C : public A, public B ; A* ap = new C; B* bp = dynamic_cast <B*> (ap); Classes A & B are completely unrelated. By creating an instance to C it can be safely up cast to A*. Then the pointer to A can be (ap) cross casting to pointer B. In this the A pointer ap really points at object C. C derives from B. 5. What is the difference between compile time and run time polymorphism in C++?(DEC2012) Polymorphism is defined as one interface to control access to a general class of actions. There are two types of polymorphism one is compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is functions and operators overloading. Runtime time polymorphism is done using inheritance
and virtual functions. Polymorphism means that functions assume different forms at different times. In case of compile time it is called function overloading. For example, a program can consist of two functions where one can perform integer addition and other can perform addition of floating point numbers but the name of the functions can be same such as add. The function add() is said to be overloaded. Two or more functions can have same name but their parameter list should be different either in terms of parameters or their data types. The functions which differ only in their return types cannot be overloaded. The compiler will select the right function depending on the type of parameters passed. In cases of classes constructors could be overloaded as there can be both initialized and uninitialized objects. Here is a program which illustrates the working of compile time function overloading and constructor overloading. eg. namespace CommonClasses public interface IAnimal string Name get; string Talk(); <i>// Assembly: Animals</i> using System; using CommonClasses; namespace Animals public abstract class AnimalBase public string Name get; private set; protected AnimalBase(string name) Name = name; public class Cat : AnimalBase, IAnimal
public Cat(string name) : base(name) public string Talk() return "Meowww!"; public class Dog : AnimalBase, IAnimal public Dog(string name) : base(name) public string Talk() return "Arf! Arf!"; <i>// Assembly: Program</i> <i>// References and Uses Assemblies: Common Classes, Animals</i> using System; using System.Collections.Generic; using Animals; using CommonClasses; namespace Program public class TestAnimals <i>// prints the following:</i> <i>// Missy: Meowww!</i> <i>// Mr. Bojangles: Meowww!</i> <i>// Lassie: Arf! Arf!</i> <i>//</i> public static void Main(string[] args) var animals = new List<IAnimal>() new Cat("Missy"), new Cat("Mr. Bojangles"), new Dog("Lassie") ;
foreach (var animal in animals) Console.WriteLine(animal.Name + ": " + animal.talk()); 6. Write short notes on Virtual Function and Pure Virtual Functions? (DEC2010) The Virtual keyword prevents the compiler from Early Binding. function name in any derived class even if the number and type of arguments are matching. e matching function overrides the base class function of same name. It can only be a member function. int b::get(int) compiler considers them as a different one that is a normal function. Syntax for declaring a virtual function, Pointer variable -> function name; Example: *point -> get(int); Rules for Virtual Functions:. as Friend for another class. virtual. Program to Use Pointer for Both Base Class and Derived Class and Call the Member Function Using Virtual Keyword: Class super virtual void display( )
cout<< In Function display() Class Super ; virtual void show( ) cout<< In Function show() Class Super ; ; Class sub : public super void display( ) cout<< In Function display() Class Sub ; void show( ) cout<< In Function show() Class Sub ; ; int main( ) super s; sub a; super *point; (instead of using a dot operator to call member Function) cout<< Pointer points to the Class Super ; point = &s; point -> display(); point -> show(); cout<< Pointer points to the Class Sub ; point = &a; point -> display(); point -> show(); return 0; Output: Pointer points to the Class Super In Function display() Class Super In Function show() Class Super Pointer points to the Class Sub In Function display() Class Sub In Function show() Class Sub Pure Virtual Function:
In many programs the member function of base class is rarely used for doing any operation. Such functions are called do nothing, dummy function or pure virtual function. abstract class. class then the class becomes Syntax: virtual return-type function-name() = 0 Example: virtual void display( ) = 0; The zero is used to instruct the compiler that the function is a pure virtual function and it will not have a definition. Program for Pure Virtual Function in Base Class: Class first int b; first( ) b = 10; virtual void display( ) = 0; // Pure Virtual Function ; Class second : public first int d; second( ) d = 10; void display( ) cout<< b= <<b<< d= <<d; ; int main( ) first *p; p -> display( ); // Abnormal Program Termination second s; p = &s; p -> display( ); return 0;
Because of pure virtual function the base class function display () can t be invoked by pointer operation. If the user tries to invoke the base class function compiler throws the Abnormal Program Termination error to the user. Output: b = 10 d = 20