UNIT - IV INHERITANCE AND FORMATTED I/O

Size: px
Start display at page:

Download "UNIT - IV INHERITANCE AND FORMATTED I/O"

Transcription

1 UNIT - IV INHERITANCE AND FORMATTED I/O CONTENTS: Inheritance Public, private and protected derivations Multiple inheritance Virtual base class Abstract class Composite objects Runtime polymorphism\ Virtual functions Pure virtual functions RTTI Typeid Dynamic casting RTTI and templates Cross casting Down casting Inheritance: Introduction: C++ strongly support the reusability, that is one class has been written and tested already it can be adapted or used to create a new class. The reusable property will reduce the debugging time The time overhead and cost overhead will be reduced. Thus, the reusability mechanism is apply to the Inheritance Definition: The mechanism of deriving the new class from an old one is called inheritance. The old class is called as base class and the new class is called as derived class. General Syntax for Inheritance: class NewClass_name:visibility_code OldClass_name Member of derived class If the class is derived from base class by private, the public members of base class becomes private members of derived class. So it is inaccessed to the object of derived class.

2 If the class is derived from base class by public, the public members of base class by public, the public members of base class becomes public members of derived class. So it is accessed to the object of derived class. But, in both cases, the private members are not inherited. Types of inheritance: 1. Single Level Inheritance 2. Multiple Inheritance 3. Multiple Inheritance 4. Hierarchical Inheritance 5. Hybrid Inheritance i. Single Inheritance: The new class can be derived from only one base class is called single inheritance. This can be represented Single Inheritance Defining derived classes: A derived class is defined by specifying its relationship with the base class in addition to its own details. The general format is class derived classname: visibility mode baseclassname..... // body of derived class ; Visibility mode is optional; it may be either private or public. The default visibility mode is private. Eg: class ABC : private xyz // body of ABC

3 ; class ABC : public xyz //body of ABC ; class ABC : xyz // private derivation by default //body of ABC ; Example program: #include <iostream.h> class A protected: int data; void getdata(int x) data1 = x; ; class B: public A private: void setdata(int y) data2 = y; void display( ) cout<< data1 <<data1; cout<< data2 << data2; ; void main( )

4 B s; s.getdata(10); s.setdata(20); s.display( ); Explanation: The new class B can be derived by the base class A. The base class A publicly inherited to a derived class A. Protected: The protected data members will be accessible by its own class and which class is immediately derived from its that class also have the rights to access the protected data member (will be act as protected data member of a derived class also). In the program, using the derived class object we can access the member function of getdata and setdata fro giving the value of data1 and data2. In the display function multiply the value of data1 and data2 and display the result. ii. Multilevel inheritance: The multilevel inheritance is defined as, the new class is derived from another derived class. It is represented as, Multilevel Inheritance Here the class A serves as a base class for the derived class B which in turn serves as a base class for the derived class C. The derived class is defined as, G.F. class A //body of base class A ;

5 class B : public A //body of intermediate base class B ; class C : public B //body of derived class ; Example Program: #include <iostream.h> class student protected: int rollno: void getroll(int x) rollno = x; ; void test: public student protected: float sub1, sub2; void getmart(int y, int z) sub1 = y; sub2= z; ; void result : public test float total; void display( ) total = sub1 + sub2; cout<<rollno<<sub1<<sub2; cout<<total; ; void main( ) result s; s.getroll(101); s.getmark(90, 100); s.display( );

6 iii. Multiple Inheritance A class can inherit the attributes or properties of two or more classes that is a new class can be derived from more than one base class is called multiple inheritance. This can be represented as: Multilevel Inheritance Here the class A and class B serves as a base class for the derived class D. The derived class definition syntax is: class d: visibility base-1, visibility base 2, body of class D; ; Example: #include<iostream.h> class A protected: int rollno; void getroll(int x) rollno=x; ; class B protected: int sub1,sub2; void getmark(int y,int z) sub1=y; sub2=z; ;

7 class C : public A, public B int total; void display() total=sub1+sub2; cout<< roll no: <<rollno<< sub1: <<sub1<< sub2: <<sub2; cout<< total <<total; ; void main() C s; s. getroll(435); s.getmark(100,90); s.display(); Output: Roll no : 435 Sub1: 100 Sub2: 90 iv. Hierarchical Inheritance: Another interesting application of inheritance is to use it as a support to the hierarchical design of a program. Many programming problems can be cast into a hierarchy where certain features of one level are shared by many others below that level. Students Arts Engineering Medical Mech Elec Civil Hierarchical classification of students

8 v. Hybrid Inheritance: The hybrid inheritance is defined as a combination of multilevel and multiple inheritances. This new class can be derived by either multilevel or multiple method or both. Example program: In this program the derived class (result) object will be inheriting the properties of both test class and sports class. #include <iostream.h> class student protected: int rollno; void getroll (int x) rollno = x; ; class test: public student protected: int sub1, sub2 void getmark (int y, int z) sub1 = y; sub2 = z; ; class sports protected: int score; void getscore (int a ) score=a; ; class result: public test, public sports int total; void display() total= sub1+sub2+score; cout<< rollno: <<rollno<< total: << Score: <<total;

9 ; void main( ) result S; s.getroll(101); s.getmark(90,98); s.getscore(2000); s. display( ); Output: Rollno: 101 Total: 188 Score: 2000 Public: It is accessed in member function of base class and derived class. It is accessible object of derived class. Protected: It is accessed in member function of base class and derived class. But it is not accessible object of derived class. Ambiguity Errors in Inheritance: When the functions with same name declared in more than one base class the ambiguity errors will occurs. The derived class can not understand the correct member function of base class. To avoid this problem using :: operator. Using Constructors in Inheritance: Constructors can be used to initiative an object data members and allocating required resources such as memory. There 10 cases apply the constructor to the derived class. Case 1: No Constructor in the base class and derived class : When there are no constructors either in the base or derived classes, the compiler automatically creates objects of classes without any error. Class A void dis( ) cout<< Hai Friends ; ;

10 Class B: public A void display( ) cout<< Have a nice day ; ; void main( ) B 8; B.dis( ); B. display( ); Case 2: Constructors only in the base class: #include <iostream.h> Class A A ( ) cout<< Have a nice day ; ; Class B: public A ; void main( ) B s; If the derived class object is created it will check the base class first and execute the corresponding default constructor. Case 3: Constructor only in the derived class #include <iostream.h> Class A ; Class B: public A A ( )

11 cout<< Have a nice day ; ; void main( ) B s; If the derived class object is created, it will check the base class first if there is no constructor in the base class, it will skip the base class & run the constructor in the derived class. Case 4: Constructor in both base and derived class: #include <iostream.h> Class A A ( ) cout<< Have a nice day ; ; class B: public A B ( ) cout<< Welcome ; ; void main( ) B s; If the derived class object is created it will check the base class & execute thecorresponding constructor and then it will execute the corresponding derived classconstructor. Case 5: Multiple constructor in base class single constructor in derived class #include <iostream.h> Class A A ( ) cout<< Have a nice day ;

12 A (int a) cout<< Welcome ; ; class B: public A B (int a) cout<< Good Morning ; ; void main( ) B s(10); In multiple constructors first the base class default constructor will be executed, if the parameters constructor is not explicitly called in the derived class means it will skip the parameter Constructor and will execute the corresponding derived class constructor. Case 6: Constructor in base and derived class without default constructor: #include <iostream.h> class A A (int a) cout<< Welcome ; ; class B: public A B (int a): A (a) cout<< Good Morning ; ; void main( ) B s(10); Output: Welcome Good Morning

13 Base class constructor is explicitly called in derived class (i.e.) B(int a): A(a); whenever derived class object is created it will execute the base class constructor first and then derived class constructor. Virtual Base Classes: In multipath inheritance the last derived class constants duplicate set of members. The public and protected members of main base class are inherited into the child class twice. So child class contains duplicate members of base class grand parent. To avoid this problem by making base class as virtual. Advantage of virtual Base class: To avoid the duplicate members of base class in derived class. Grand parent Parent1 Parent2 Child An element of ambiguity can be introduced into a C++ program when multiple base classes are inherited. For example, consider this incorrect program: // This program contains an error and will not compile. #include <iostream> using namespace std; class base int i; ; // derived1 inherits base. class derived1 : public base int j; ; // derived2 inherits base. class derived2 : public base int k; ;

14 /* derived3 inherits both derived1 and derived2. This means that there are two copies of base in derived3! */ class derived3 : public derived1, public derived2 int sum; ; int main() derived3 ob; ob.i = 10; // this is ambiguous, which i??? ob.j = 20; ob.k = 30; // i ambiguous here, too ob.sum = ob.i + ob.j + ob.k; // also ambiguous, which i? cout << ob.i << " "; cout << ob.j << " " << ob.k << " "; cout << ob.sum; return 0; As the comments in the program indicate, both derived1 and derived2 inherit base. However, derived3 inherits both derived1 and derived2. This means that there are two copies of base present in an object of type derived3. Therefore, in an expression like ob.i = 10; which i is being referred to, the one in derived1 or the one in derived2? Because there are two copies of base present in object ob, there are two ob.is! As you can see, the statement is inherently ambiguous. There are two ways to remedy the preceding program. The first is to apply the scope resolution operator to i and manually select one i. For example, this version of the program does compile and run as expected: // This program uses explicit scope resolution to select i. #include <iostream> using namespace std; class base int i; ;

15 // derived1 inherits base. class derived1 : public base int j; ; // derived2 inherits base. class derived2 : public base int k; ; /* derived3 inherits both derived1 and derived2. This means that there are two copies of base in derived3! */ class derived3 : public derived1, public derived2 int sum; ; int main() derived3 ob; ob.derived1::i = 10; // scope resolved, use derived1's i ob.j = 20; ob.k = 30; // scope resolved ob.sum = ob.derived1::i + ob.j + ob.k; // also resolved here cout << ob.derived1::i << " "; cout << ob.j << " " << ob.k << " "; cout << ob.sum; return 0; As you can see, because the :: was applied, the program has manually selected derived1's version of base. However, this solution raises a deeper issue: What if only one copy of base is actually required? Is there some way to prevent two copies from being included in derived3? The answer, as you probably have guessed, is yes. This solution is achieved using virtual base classes. When two or more objects are derived from a common base class, you can prevent multiple copies of the base class from being present in an object derived

16 from those objects by declaring the base class as virtual when it is inherited. You accomplish this by preceding the base class' name with the keyword virtual when it is inherited. For example, here is another version of the example program in which derived3 contains only one copy of base: // This program uses virtual base classes. #include <iostream> using namespace std; class base int i; ; // derived1 inherits base as virtual. class derived1 : virtual public base int j; ; // derived2 inherits base as virtual. class derived2 : virtual public base int k; ; /* derived3 inherits both derived1 and derived2. This time, there is only one copy of base class. */ class derived3 : public derived1, public derived2 int sum; ; int main() derived3 ob; ob.i = 10; // now unambiguous ob.j = 20; ob.k = 30; // unambiguous ob.sum = ob.i + ob.j + ob.k; // unambiguous cout << ob.i << " "; cout << ob.j << " " << ob.k << " "; cout << ob.sum;

17 return 0; The keyword virtual precedes the rest of the inherited class specification. Now that both derived1 and derived2 have inherited base as virtual, any multiple inheritance involving them will cause only one copy of base to be present. Therefore, in derived3, there is only one copy of base and ob.i = 10 is perfectly valid and unambiguous. One further point to keep in mind: Even though both derived1 and derived2 specify base as virtual, base is still present in objects of either type. For example, the following sequence is perfectly valid: // define a class of type derived1 derived1 myclass; myclass.i = 88; The only difference between a normal base class and a virtual one is what occurs when an object inherits the base more than once. If virtual base classes are used, then only one base class is present in the object. Otherwise, multiple copies will be found. Polymorphism 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, Virtual Functions: 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. When a class containing a virtual function is inherited, the derived class redefines the virtual function to fit its own needs. In essence, virtual functions implement the "one interface, multiple methods" philosophy that underlies polymorphism. The virtual function within the base class defines the form of the interface to that function. Each redefinition of the virtual function by a derived class implements its operation as it relates specifically to the derived class. That is, the redefinition creates a specific method.

18 When accessed "normally," virtual functions behave just like any other type of class member function. However, what makes virtual functions important and capable of supporting runtime polymorphism is how they behave when accessed via a pointer. As discussed in Chapter 13, a base-class pointer can be used to point to an object of any class derived from that base. When a base pointer points to a derived object that contains a virtual function, C++ determines which version of that function to call based upon the type of object pointed to by the pointer. And this determination is made at runtime. Thus, when different objects are pointed to, different versions of the virtual function are executed. The same effect applies to base-class references. To begin, examine this short example: #include <iostream> using namespace std; class base virtual void vfunc() cout << "This is base's vfunc().\n"; ; class derived1 : public base void vfunc() cout << "This is derived1's vfunc().\n"; ; class derived2 : public base void vfunc() cout << "This is derived2's vfunc().\n"; ; int main() base *p, b; derived1 d1; derived2 d2;

19 // point to base p = &b; p->vfunc(); // access base's vfunc() // point to derived1 p = &d1; p->vfunc(); // access derived1's vfunc() // point to derived2 p = &d2; p->vfunc(); // access derived2's vfunc() return 0; Output: This is base's vfunc(). This is derived1's vfunc(). This is derived2's vfunc(). As the program illustrates, inside base, the virtual function vfunc() is declared. Notice that the keyword virtual precedes the rest of the function declaration. When vfunc() is redefined by derived1 and derived2, the keyword virtual is not needed. (However, it is not an error to include it when redefining a virtual function inside a derived class; it's just not needed.) class definition, vfunc() is redefined relative to that class. Inside main(), four variables are declared: Name p b d1 d2 Type base class pointer object of base object of derived1 object of derived2 Next, p is assigned the address of b, and vfunc() is called via p. Since p is pointing to an object of type base, that version of vfunc() is executed. Next, p is set to the address of d1, and again vfunc() is called by using p. This time p points to an object of type derived1. This causes derived1::vfunc() to be executed. Finally, p is assigned the address of d2, and p >vfunc() causes the version of vfunc() redefined inside derived2 to be executed. The key point here is that the kind of object to which p points determines which version of vfunc() is executed. Further, this determination is made at run time, and this process forms the basis for run-time polymorphism.

20 Although you can call a virtual function in the "normal" manner by using an object's name and the dot operator, it is only when access is through a base-class pointer (or reference) that run-time polymorphism is achieved. For example, assuming the preceding example, this is syntactically valid: Pure Virtual Functions: As the examples in the preceding section illustrate, when a virtual function is not redefined by a derived class, the version defined in the base class will be used. However, in many situations there can be no meaningful definition of a virtual function within a base class. For example, a base class may not be able to define an object sufficiently to allow a base-class virtual function to be created. Further, in some situations you will want to ensure that all derived classes override a virtual function. To handle these two cases, C++ supports the pure virtual function. A pure virtual function is a virtual function that has no definition within the base class. To declare a pure virtual function, use this general form: virtual type func-name(parameter-list) = 0; When a virtual function is made pure, any derived class must provide its own definition. If the derived class fails to override the pure virtual function, a compile-time error will result. The following program contains a simple example of a pure virtual function. The base class, number, contains an integer called val, the function setval(), and the pure virtual function show(). The derived classes hextype, dectype, and octtype inherit number and redefine show() so that it outputs the value of val in each respective number base (that is, hexadecimal, decimal, or octal). #include <iostream> using namespace std; class number protected: int val;

21 void setval(int i) val = i; // show() is a pure virtual function virtual void show() = 0; ; class hextype : public number void show() cout << hex << val << "\n"; ; class dectype : public number void show() cout << val << "\n"; ; class octtype : public number void show() cout << oct << val << "\n"; ; int main() dectype d; hextype h; octtype o; d.setval(20); d.show(); // displays 20 - decimal h.setval(20); h.show(); // displays 14 - hexadecimal o.setval(20); o.show(); // displays 24 - octal return 0; Although this example is quite simple, it illustrates how a base class may not be able to meaningfully define a virtual function. In this case, number simply provides the common interface for the derived types to use.

22 There is no reason to define show() inside number since the base of the number is undefined. Of course, you can always create a placeholder definition of a virtual function. However, making show() pure also ensures that all derived classes will indeed redefine it to meet their own needs. Keep in mind that when a virtual function is declared as pure, all derived classes must override it. If a derived class fails to do this, a compile-time error will result. Abstract Classes: A class that contains at least one pure virtual function is said to be abstract. Because an abstract class contains one or more functions for which there is no definition (that is, a pure virtual function), no objects of an abstract class may be created. Instead, an abstract class constitutes an incomplete type that is used as a foundation for derived classes. Although you cannot create objects of an abstract class, you can create pointers and references to an abstract class. This allows abstract classes to support run-time polymorphism, which relies upon base-class pointers and references to select the proper virtual function. Using Virtual Functions: One of the central aspects of object-oriented programming is the principle of "one interface, multiple methods." This means that a general class of actions can be defined, the interface to which is constant, with each derivation defining its own specific operations. In concrete C++ terms, a base class can be used to define the nature of the interface to a general class. Each derived class then implements the specific operations as they relate to the type of data used by the derived type. One of the most powerful and flexible ways to implement the "one interface, multiple methods" approach is to use virtual functions, abstract classes, and runtime polymorphism. Using these features, you create a class hierarchy that moves from general to specific (base to derived).

23 Following this philosophy, you define all common features and interfaces in a base class. In cases where certain actions can be implemented only by the derived class, use a virtual function. In essence, in the base class you create and define everything you can that relates to the general case. The derived class fills in the specific details. Following is a simple example that illustrates the value of the "one interface, multiple methods" philosophy. A class hierarchy is created that performs conversions from one system of units to another. (For example, liters to gallons.) The base class convert declares two variables, val1 and val2, which hold the initial and converted values, respectively. It also defines the functions getinit() and getconv(), which return the initial value and the converted value. These elements of convert are fixed and applicable to all derived classes that will inherit convert. However, the function that will actually perform the conversion, compute(), is a pure virtual function that must be defined by the classes derived from convert. The specific nature of compute() will be determined by what type of conversion is taking place. // Virtual function practical example. #include <iostream> using namespace std; class convert protected: double val1; // initial value double val2; // converted value convert(double i) val1 = i; double getconv() return val2; double getinit() return val1; virtual void compute() = 0;

24 ; // Liters to gallons. class l_to_g : public convert l_to_g(double i) : convert(i) void compute() val2 = val1 / ; ; // Fahrenheit to Celsius class f_to_c : public convert f_to_c(double i) : convert(i) void compute() val2 = (val1-32) / 1.8; ; int main() convert *p; // pointer to base class l_to_g lgob(4); f_to_c fcob(70); // use virtual function mechanism to convert p = &lgob; cout << p->getinit() << " liters is "; p->compute(); cout << p->getconv() << " gallons\n"; // l_to_g p = &fcob; cout << p->getinit() << " in Fahrenheit is "; p->compute(); cout << p->getconv() << " Celsius\n"; // f_to_c return 0; Run-Time Type Identification (RTTI): Run-time type information may be new to you because it is not found in nonpolymorphic languages, such as C. In nonpolymorphic languages there is no need for run-time type information because the type of each object is known at compile time (i.e., when the program is written).

25 However, in polymorphic languages such as C++, there can be situations in which the type of an object is unknown at compile time because the precise nature of that object is not determined until the program is executed. C++ implements polymorphism through the use of class hierarchies, virtual functions, and base-class pointers. Since base-class pointers may be used to point to objects of the base class or any object derived from that base, it is not always possible to know in advance what type of object will be pointed to by a base pointer at any given moment in time. This determination must be made at run time, using run-time type identification. To obtain an object's type, use typeid. You must include the header <typeinfo> in order to use typeid. Its most commonly used form is shown here: typeid(object) Here, object is the object whose type you will be obtaining. It may be of any type, including the built-in types and class types that you create. typeid returns a reference to an object of type type_info that describes the type of object. The type_info class defines the following public members: bool operator==(const type_info &ob); bool operator!=(const type_info &ob); bool before(const type_info &ob); const char *name( ); The overloaded == and!= provide for the comparison of types. The before() function returns true if the invoking object is before the object used as a parameter in collation order. (This function is mostly for internal use only. Its return value has nothing to do with inheritance or class hierarchies.) The name() function returns a pointer to the name of the type. Here is a simple example that uses typeid. // A simple example that uses typeid. #include <iostream> #include <typeinfo> using namespace std; class myclass1 //... ; class myclass2

26 //... ; int main() int i, j; float f; char *p; myclass1 ob1; myclass2 ob2; cout << "The type of i is: " << typeid(i).name(); cout << endl; cout << "The type of f is: " << typeid(f).name(); cout << endl; cout << "The type of p is: " << typeid(p).name(); cout << endl; cout << "The type of ob1 is: " << typeid(ob1).name(); cout << endl; cout << "The type of ob2 is: " << typeid(ob2).name(); cout << "\n\n"; if(typeid(i) == typeid(j)) cout << "The types of i and j are the same\n"; if(typeid(i)!= typeid(f)) cout << "The types of i and f are not the same\n"; if(typeid(ob1)!= typeid(ob2)) cout << "ob1 and ob2 are of differing types\n"; return 0; Output : The type of i is: int The type of f is: float The type of p is: char * The type of ob1 is: class myclass1 The type of ob2 is: class myclass2 The types of i and j are the same The types of i and f are not the same ob1 and ob2 are of differing types The most important use of typeid occurs when it is applied through a pointer of a polymorphic base class. In this case, it will automatically return the type of the actual object being pointed to, which may be a base-class object or an object derived from that base. (Remember, a base-class pointer can point to objects of the base class or of any class derived from that base.) Thus, using typeid, you can determine at run time the type of the object that is being pointed to by a base-class pointer. The following program demonstrates this principle.

27 // An example that uses typeid on a polymorphic class hierarchy. #include <iostream> #include <typeinfo> using namespace std; class Mammal virtual bool lays_eggs() return false; // Mammal is polymorphic //... ; class Cat: public Mammal //... ; class Platypus: public Mammal bool lays_eggs() return true; //... ; int main() Mammal *p, AnyMammal; Cat cat; Platypus platypus; p = &AnyMammal; cout << "p is pointing to an object of type "; cout << typeid(*p).name() << endl; p = &cat; cout << "p is pointing to an object of type "; cout << typeid(*p).name() << endl; p = &platypus; cout << "p is pointing to an object of type "; cout << typeid(*p).name() << endl; return 0; Output : p is pointing to an object of type class Mammal p is pointing to an object of type class Cat p is pointing to an object of type class Platypus

28 As explained, when typeid is applied to a base-class pointer of a polymorphic type, the type of object pointed to will be determined at run time, as shown by the output produced by the program. In all cases, when typeid is applied to a pointer of a nonpolymorphic class heirarchy, then the base type of the pointer is obtained. That is, no determination of what that pointer is actually pointing to is made. For example, comment out the virtual keyword before the function lays_eggs() in Mammal and then compile and run the program. You will see the following output. p is pointing to an object of type class Mammal p is pointing to an object of type class Mammal p is pointing to an object of type class Mammal Since Mammal is no longer a polymorphic class, the type of each object will be Mammal because that is the type of the pointer. Since typeid is commonly applied to a dereferenced pointer (i.e., one to which the * operator has been applied), a special exception has been created to handle the situation in which the pointer being dereferenced is null. In this case, typeid throws bad_typeid. References to an object of a polymorphic class hierarchy work the same as pointers. When typeid is applied to a reference to an object of a polymorphic class, it will return the type of the object actually being referred to, which may be of a derived type. The circumstance where you will most often make use of this feature is when objects are passed to functions by reference. For example, in the following program, the function WhatMammal() declares a reference parameter to objects of type Mammal. This means that WhatMammal() can be passed references to objects of type Mammal or any class derived from Mammal. When the typeid operator is applied to this parameter, it returns the actual type of the object being passed. // Use a reference with typeid. #include <iostream> #include <typeinfo> using namespace std; class Mammal

29 virtual bool lays_eggs() return false; // Mammal is polymorphic //... ; class Cat: public Mammal //... ; class Platypus: public Mammal bool lays_eggs() return true; //... ; // Demonstrate typeid with a reference parameter. void WhatMammal(Mammal &ob) cout << "ob is referencing an object of type "; cout << typeid(ob).name() << endl; int main() Mammal AnyMammal; Cat cat; Platypus platypus; WhatMammal(AnyMammal); WhatMammal(cat); WhatMammal(platypus); return 0; Output: ob is referencing an object of type class Mammal ob is referencing an object of type class Cat ob is referencing an object of type class Platypus There is a second form of typeid that takes a type name as its argument. This form is shown here: typeid(type-name) For example, the following statement is perfectly acceptable: cout << typeid(int).name();

30 The main use of this form of typeid is to obtain a type_info object that describes the specified type so that it can be used in a type comparison statement. For example, this form of WhatMammal() reports that cats don't like water: void WhatMammal(Mammal &ob) cout << "ob is referencing an object of type "; cout << typeid(ob).name() << endl; if(typeid(ob) == typeid(cat)) cout << "Cats don't like water.\n"; The Casting Operators: C++ defines five casting operators. The first is the traditional-style cast inherited from C. The remaining four were added a few years ago. They are dynamic_cast, const_cast, reinterpret_cast, and static_cast. These operators give you additional control over how casting takes place. dynamic_cast: Perhaps the most important of the new casting operators is dynamic_cast. The dynamic_cast performs a run-time cast that verifies the validity of a cast. If the cast is invalid at the time dynamic_cast is executed, then the cast fails. The general form of dynamic_cast is shown here: dynamic_cast<target-type> (expr) Here, target-type specifies the target type of the cast, and expr is the expression being cast into the new type. The target type must be a pointer or reference type, and the expression being cast must evaluate to a pointer or reference. Thus, dynamic_cast may be used to cast one type of pointer into another or one type of reference into another. The purpose of dynamic_cast is to perform casts on polymorphic types. For example, given two polymorphic classes Band D, with D derived from B, a dynamic_cast can always cast a D* pointer into a B* pointer. This is because a base pointer can always point to a derived object. But a dynamic_cast can cast a B* pointer into a D* pointer only if the object being pointed to actually is a D object. In general, dynamic_cast will succeed if the pointer (or reference) being

31 cast is a pointer (or reference) to either an object of the target type or an object derived from the target type. Otherwise, the cast will fail. If the cast fails, then dynamic_cast evaluates to null if the cast involves pointers. If a dynamic_cast on reference types fails, a bad_cast exception is thrown. Here is a simple example. Assume that Base is a polymorphic class and that Derived is derived from Base. Base *bp, b_ob; Derived *dp, d_ob; bp = &d_ob; // base pointer points to Derived object dp = dynamic_cast<derived *> (bp); // cast to derived pointer OK if(dp) cout << "Cast OK"; Here, the cast from the base pointer bp to the derived pointer dp works because bp is actually pointing to a Derived object. Thus, this fragment displays Cast OK. But in the next fragment, the cast fails because bp is pointing to a Base object and it is illegal to cast a base object into a derived object. bp = &b_ob; // base pointer points to Base object dp = dynamic_cast<derived *> (bp); // error if(!dp) cout << "Cast Fails"; Because the cast fails, this fragment displays Cast Fails. The following program demonstrates the various situations that dynamic_cast can handle. // Demonstrate dynamic_cast. #include <iostream> using namespace std; class Base virtual void f() cout << "Inside Base\n"; //... ; class Derived : public Base

32 void f() cout << "Inside Derived\n"; ; int main() Base *bp, b_ob; Derived *dp, d_ob; dp = dynamic_cast<derived *> (&d_ob); if(dp) cout << "Cast from Derived * to Derived * OK.\n"; dp->f(); else cout << "Error\n"; cout << endl; bp = dynamic_cast<base *> (&d_ob); if(bp) cout << "Cast from Derived * to Base * OK.\n"; bp->f(); else cout << "Error\n"; cout << endl; bp = dynamic_cast<base *> (&b_ob); if(bp) cout << "Cast from Base * to Base * OK.\n"; bp->f(); else cout << "Error\n"; cout << endl; dp = dynamic_cast<derived *> (&b_ob); if(dp) cout << "Error\n"; else cout << "Cast from Base * to Derived * not OK.\n"; cout << endl; bp = &d_ob; // bp points to Derived object dp = dynamic_cast<derived *> (bp); if(dp) cout << "Casting bp to a Derived * OK\n" << "because bp is really pointing\n" << "to a Derived object.\n"; dp->f(); else cout << "Error\n";

33 if(dp) else if(bp) else cout << endl; bp = &b_ob; // bp points to Base object dp = dynamic_cast<derived *> (bp); cout << "Error"; cout << "Now casting bp to a Derived *\n" << "is not OK because bp is really \n" << "pointing to a Base object.\n"; cout << endl; dp = &d_ob; // dp points to Derived object bp = dynamic_cast<base *> (dp); cout << "Casting dp to a Base * is OK.\n"; bp->f(); cout << "Error\n"; return 0; Output: Cast from Derived * to Derived * OK. Inside Derived Cast from Derived * to Base * OK. Inside Derived Cast from Base * to Base * OK. Inside Base Cast from Base * to Derived * not OK. Casting bp to a Derived * OK because bp is really pointing to a Derived object. Inside Derived Replacing typeid with dynamic_cast: The dynamic_cast operator can sometimes be used instead of typeid in certain cases. For example, again assume that Base is a polymorphic base class for Derived. The following fragment will assign dp the address of the object pointed to by bp if and only if the object really is a Derived object.

34 Base *bp; Derived *dp; //... if(typeid(*bp) == typeid(derived)) dp = (Derived *) bp; In this case, a traditional-style cast is used to actually perform the cast. This is safe because the if statement checks the legality of the cast using typeid before the cast actually occurs. However, a better way to accomplish this is to replace the typeid operators and if statement with this dynamic_cast. dp = dynamic_cast<derived *> (bp); Since dynamic_cast succeeds only if the object being cast is either an object of the target type or an object derived from the target type, after this statement executes dp will contain either a null or a pointer to an object of type Derived. Since dynamic_cast succeeds only if the cast is legal, it can simplify the logic in certain situations. The following program illustrates how a dynamic_cast can be used to replace typeid. It performs the same set of operations twice first with typeid, then using dynamic_cast. // Use dynamic_cast to replace typeid. #include <iostream> #include <typeinfo> using namespace std; class Base virtual void f() ; class Derived : public Base void derivedonly() cout << "Is a Derived Object.\n"; ; int main() Base *bp, b_ob; Derived *dp, d_ob; // ************************************ // use typeid

35 // ************************************ bp = &b_ob; if(typeid(*bp) == typeid(derived)) dp = (Derived *) bp; dp->derivedonly(); else cout << "Cast from Base to Derived failed.\n"; bp = &d_ob; if(typeid(*bp) == typeid(derived)) dp = (Derived *) bp; dp->derivedonly(); else cout << "Error, cast should work!\n"; // ************************************ // use dynamic_cast // ************************************ bp = &b_ob; dp = dynamic_cast<derived *> (bp); if(dp) dp->derivedonly(); else cout << "Cast from Base to Derived failed.\n"; bp = &d_ob; dp = dynamic_cast<derived *> (bp); if(dp) dp->derivedonly(); else cout << "Error, cast should work!\n"; return 0; As you can see, the use of dynamic_cast simplifies the logic required to cast a base pointer into a derived pointer. The output from the program is shown here: Cast from Base to Derived failed. Is a Derived Object. Cast from Base to Derived failed. Is a Derived Object. As you might have gathered all down and cross casting using dynamic_cast only generally makes sense if the objects in question are polymorphic - that is the base classes employ virtual functions that are overridden by their derivations to supply specific behaviours.

36 Hence RTTI is _only_ added to functions that contain at least one virtual function. If there are cases in which a class involved in RTTI has no virtual functions then I tend to make the destructor virtual to satisfy this requirement. Although not a requirement of the C++ standard the other requirement in practice for many compilers is that RTTI is enabled when compiling your code using a compiler switch. This is because RTTI adds overhead to the code in that some additional data is stored for each class (note: for each class not each object). So if you are not using dynamic_cast then it may make sense to turn off RTTI and save some space. The other C++ feature that you can often control in this way is exception handling as this also adds overhead in time and space to programs, however as exceptions are now used by the C++ standard library not using it at all and turning it off is not such an easy option In object-oriented programming, downcasting or type refinement is the act of casting a reference to a base class to one of its derived classes. Downcasting is the term used in C++ for casting a pointer or reference to a base class to a derived class. C++ provides a special explicit cast called dynamic_cast that performs this conversion. Downcasting is the opposite of the basic object-oriented rule, which states objects of a derived class, can always be assigned to variables of a base class. Since base class variables can only sometimes be assigned to variables of a derived class downcasting doesn't always work. Upcasting can be easy because you are moving up the hierarchy and classes can easily converge to a general class. There are several possibilities of a derived class. One has to find a safe way to downcast void myfunction(vehicle* v1) Car *c1 = dynamic_cast<car*>(v1); if(c1) // we can safely use c1

37 Casting from a base class to a derived class is often called a downcast because of the convention of drawing inheritance trees growing from the root down. Similarly, a cast from a derived class to a base is called an upcast. A cast that goes from a base to a sibling class is called a crosscast. Base 1 Base 2 Derived 2 Derived 1 Derived 3 Crosscast, from Base2 to Derived1 SUMMARY: The mechanism of deriving a new class from an old class is called inheritance. Inheritance provides the concept of reusability. The C++ classes can be reused using inheritance. The derived class inherits some or all of the properties of the base class. A derived class with only one base class is called single inheritance. A class can inherits properties from more than one class which is known as multiple inheritance. A class can be derived from another derived class which is known as multilevel inheritance. IMPORTANT QUESTIONS PART-A 1. What is meant by inheritance? 2. What is meant by single inheritance? 3. What is multiple inheritances? 4. What is hierarchical inheritance? 5. What is multilevel inheritance? 6. What is hybrid inheritance?

38 7. What is meant by Abstract base class? 8. Write short notes on virtual base class. 9. What are Friend functions? Write the syntax 10. Write some properties of friend functions. 11. What are the virtual functions? 12. Write some of the basic rules for virtual functions 13. What are pure virtual functions? Write the syntax. PART-B 1. Discuss briefly on friend functions. 2. Describe how the following features are supported by C++. a. Inheritance. b. Concurrency. c. Genericity. 3. Write a program to read words and print in reverse order.illustrate use of Keywords to dynamically allocate space for each of the strings that are read in. 4. What are the rules associated with virtual functions? 5. What are the different forms of inheritance supported in c++? Discuss on the visibility of base class members in privately and publicly inherited classes. 6. What are abstract classes? Give an example (with the program) to illustrate the use of abstract classes. 7. Write notes on RTTI and casting with sample program. 8. Write notes on Typing conversions and derived class with program.

UNIT III- INHERITANCE AND POLYMORPHISM

UNIT III- INHERITANCE AND POLYMORPHISM UNIT III- INHERITANCE AND POLYMORPHISM Objectives: To introduce Inheritance in C++ and to explain its importance. To make understand the different types of inheritance. To define typing conversion and

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

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

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

Divyakant Meva. Table 1. The C++ keywords

Divyakant Meva. Table 1. The C++ keywords Chapter 1 Identifiers In C/C++, the names of variables, functions, labels, and various other user-defined objects are called identifiers. These identifiers can vary from one to several characters. The

More information

mywbut.com Inheritance

mywbut.com Inheritance Inheritance 1 Inheritance is one of the cornerstones of OOP because it allows the creation of hierarchical classifications. Using inheritance, you can create a general class that defines traits common

More information

VIRTUAL FUNCTIONS Chapter 10

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

More information

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

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

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

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

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

C++ Casts and Run-Time Type Identification

C++ Casts and Run-Time Type Identification APPENDIX K C++ Casts and Run-Time Type Identification Introduction There are many times when a programmer needs to use type casts to tell the compiler to convert the type of an expression to another type.

More information

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University Polymorphism Miri Ben-Nissan (Kopel) 1 Shape Triangle Rectangle Circle int main( ) Shape* p = GetShape( ); p->draw( ); Shape* GetShape( ) choose randomly which shape to send back For example: Shape* p

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

These new operators are intended to remove some of the holes in the C type system introduced by the old C-style casts.

These new operators are intended to remove some of the holes in the C type system introduced by the old C-style casts. asting in C++: Bringing Safety and Smartness to Your Programs of 10 10/5/2009 1:20 PM By G. Bowden Wise The new C++ standard is full of powerful additions to the language: templates, run-time type identification

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

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

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both operators and functions can be overloaded

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

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

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

More information

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

Absolute C++ Walter Savitch

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

More information

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

Polymorphism. Zimmer CSCI 330

Polymorphism. Zimmer CSCI 330 Polymorphism Polymorphism - is the property of OOP that allows the run-time binding of a function's name to the code that implements the function. (Run-time binding to the starting address of the code.)

More information

15: Polymorphism & Virtual Functions

15: Polymorphism & Virtual Functions 15: Polymorphism & Virtual Functions 김동원 2003.02.19 Overview virtual function & constructors Destructors and virtual destructors Operator overloading Downcasting Thinking in C++ Page 1 virtual functions

More information

OOP. Unit:3.3 Inheritance

OOP. Unit:3.3 Inheritance Unit:3.3 Inheritance Inheritance is like a child inheriting the features of its parents. It is a technique of organizing information in a hierarchical (tree) form. Inheritance allows new classes to be

More information

W3101: Programming Languages C++ Ramana Isukapalli

W3101: Programming Languages C++ Ramana Isukapalli Lecture-6 Operator overloading Namespaces Standard template library vector List Map Set Casting in C++ Operator Overloading Operator overloading On two objects of the same class, can we perform typical

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

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p. Preface to the Second Edition p. iii Preface to the First Edition p. vi Brief Contents p. ix Introduction to C++ p. 1 A Review of Structures p. 1 The Need for Structures p. 1 Creating a New Data Type Using

More information

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

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Question No: 1 ( Marks: 2 ) Write a declaration statement for an array of 10

More information

RAJIV GANDHI COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF INFORMATION TECHNOLOGY OBJECT ORIENTED PROGRAMMING QUESTION BANK UNIT I 2 MARKS

RAJIV GANDHI COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF INFORMATION TECHNOLOGY OBJECT ORIENTED PROGRAMMING QUESTION BANK UNIT I 2 MARKS RAJIV GANDHI COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF INFORMATION TECHNOLOGY OBJECT ORIENTED PROGRAMMING YEAR/SEM:II & III UNIT I 1) Give the evolution diagram of OOPS concept. 2) Give some

More information

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

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

More information

C++_ MARKS 40 MIN

C++_ MARKS 40 MIN C++_16.9.2018 40 MARKS 40 MIN https://tinyurl.com/ya62ayzs 1) Declaration of a pointer more than once may cause A. Error B. Abort C. Trap D. Null 2Whice is not a correct variable type in C++? A. float

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

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

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

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed? QUIZ Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed? Or Foo(x), depending on how we want the initialization

More information

Dr. Md. Humayun Kabir CSE Department, BUET

Dr. Md. Humayun Kabir CSE Department, BUET C++ Type Casting Dr. Md. Humayun Kabir CSE Department, BUET C++ Type Casting Converting a value of a given type into another type is known as type-casting. ti Conversion can be implicit or explicit 2 C++

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

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

PIC 10A Objects/Classes

PIC 10A Objects/Classes PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous

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

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

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

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

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

TPF Users Group Spring 2005

TPF Users Group Spring 2005 TPF Users Group Spring 2005 Get Ready For Standard C++! Name : Edwin W. van de Grift Venue : Applications Development Subcommittee AIM Enterprise Platform Software IBM z/transaction Processing Facility

More information

Variables. Data Types.

Variables. Data Types. Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting

More information

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab. University of Technology Laser & Optoelectronics Engineering Department C++ Lab. Second week Variables Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable.

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 22 November 28, 2016 CPSC 427, Lecture 22 1/43 Exceptions (continued) Code Reuse Linear Containers Ordered Containers Multiple Inheritance

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

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

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

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

More information

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

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

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

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

Introduction to RTTI. Jonathan Hoyle Eastman Kodak 11/30/00

Introduction to RTTI. Jonathan Hoyle Eastman Kodak 11/30/00 Introduction to RTTI Jonathan Hoyle Eastman Kodak 11/30/00 Overview What is RTTI? typeid( ) function Polymorphism dynamic_cast< > operation RTTI Gotcha s Demo What is RTTI? Run-Time Type Identification

More information

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std; - 147 - Advanced Concepts: 21. Exceptions Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers.

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

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

04-24/26 Discussion Notes

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

More information

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

Basic Types, Variables, Literals, Constants

Basic Types, Variables, Literals, Constants Basic Types, Variables, Literals, Constants What is in a Word? A byte is the basic addressable unit of memory in RAM Typically it is 8 bits (octet) But some machines had 7, or 9, or... A word is the basic

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

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

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

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

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

More information

Sahaj Computer Solutions OOPS WITH C++

Sahaj Computer Solutions OOPS WITH C++ Chapter 6 1 Contents Introduction Types of Inheritances Defining the Derived Class Single Inheritance Making a private data inheritable Multilevel Inheritance Multiple Inheritance Ambiguity Resolution

More information

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017 OOP components For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Data Abstraction Information Hiding, ADTs Encapsulation Type Extensibility Operator Overloading

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

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED - Polymorphism - Virtual Functions - Abstract Classes - Virtual

More information

Programming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor

Programming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Programming C++ Lecture 5 Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Templates S Function and class templates you specify with a single code segment an entire

More information

Laboratorio di Tecnologie dell'informazione

Laboratorio di Tecnologie dell'informazione Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Const correctness What is const correctness? It is a semantic constraint, enforced

More information

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things. A Appendix Grammar There is no worse danger for a teacher than to teach words instead of things. Marc Block Introduction keywords lexical conventions programs expressions statements declarations declarators

More information

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini bertini@dsi.unifi.it http://www.dsi.unifi.it/~bertini/ Const correctness What is const correctness? It is a semantic constraint, enforced

More information

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

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

More information

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

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

More information

QUIZ. How could we disable the automatic creation of copyconstructors

QUIZ. How could we disable the automatic creation of copyconstructors QUIZ How could we disable the automatic creation of copyconstructors pre-c++11? What syntax feature did C++11 introduce to make the disabling clearer and more permanent? Give a code example. Ch. 14: Inheritance

More information

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Winter 2011 Lecture 08 - Inheritance continued School of Computer Science McGill University March 8, 2011 Last Time Single Inheritance Polymorphism: Static Binding vs Dynamic

More information

More Tutorial on C++:

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

More information

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

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

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types ME240 Computation for Mechanical Engineering Lecture 4 C++ Data Types Introduction In this lecture we will learn some fundamental elements of C++: Introduction Data Types Identifiers Variables Constants

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

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

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

C++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory. 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

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

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 Introduction 2 IS 0020 Program Design and Software Tools Exception Handling Lecture 12 November 23, 200 Exceptions Indicates problem occurred in program Not common An "exception" to a program that usually

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

Java: introduction to object-oriented features

Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

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

Where do we stand on inheritance?

Where do we stand on inheritance? In C++: Where do we stand on inheritance? Classes can be derived from other classes Basic Info about inheritance: To declare a derived class: class :public

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