The C++ Language C++ Features

Total Page:16

File Type:pdf, Size:1020Kb

The C++ Language C++ Features The C++ Language C++ Features Classes Bjarne Stroupstrup, the language’s creator, explains User-defined types The C++ Language C++ was designed to provide Simula’s facilities for Operator overloading program organization together with C’s efficiency and COMS W4995-02 Attach different meaning to expressions such as a + b flexibility for systems programming. References Prof. Stephen A. Edwards Pass-by-reference function arguments Fall 2002 Columbia University Virtual Functions Department of Computer Science Dispatched depending on type at run time Templates Macro-like polymorphism for containers (e.g., arrays) Exceptions More elegant error handling Implementing Classes Operator Overloading Complex Number Type class Complex { Simple without virtual functions. For manipulating user-defined double re, im; “numeric” types C++ Equivalent C public: class Stack { struct Stack { complex(double); // used, e.g., in c1 + 2.3 complex c1(1, 5.3), c2(5); // Create objects char s[SIZE]; char s[SIZE]; complex(double, double); int sp; int sp; complex c3 = c1 + c2; // + means complex plus public: }; c3 = c3 + 2.3; // 2.3 promoted to a complex number // Here, & means pass-by-reference: reduces copying Stack(); complex& operator+=(const complex&); void push(char); void St_Stack(Stack*); }; char pop(); void St_push(Stack*,char); }; char St_pop(Stack*); References Function Overloading Const Designed to avoid copying in overloaded operators Overloaded operators a particular Access control over variables, Especially efficient when code is inlined. case of function/method overloading arguments, and objects. A mechanism for calling functions pass-by-reference General: select specific method/operator based on name, const double pi = 3.14159265; // Compile-time constant C only has pass-by-value: fakable with explicit pointer use number, and type of arguments. int foo(const char* a) { // Constant argument void bad swap(int x, int y) { Return type not part of overloading *a = 'a'; // Illegal: a is const int tmp = x; x = y; y = tmp; void foo(int); } } void foo(int, int); // OK void foo(char *); // OK class bar { // “object not modified” int foo(char *); void swap(int &x, int &y) { // BAD int get field() const { return field; } int tmp = x; x = y; y = tmp; }; } Templates Template Stack Class Using a Template template <class T> class Stack { Macro-preprocessor-like way of providing polymorphism. T s[SIZE]; // T is a type argument Stack<char> cs; // Creates code specialized for char Polymorphism: Using the same code for different types int sp; cs.push('a'); public: char c = cs.pop(); Mostly intended for containiner classes (vectors of Stack() { sp = 0; } integers, doubles, etc.) void push(T v) { if (sp == SIZE) error("overflow"); Stack<double*> dps; // Creates version for double* Standard Template Library has templates for strings, lists, s[sp++] = v; double d; vectors, hash tables, trees, etc. } dps.push(&d); T pop() { if (sp == () error("underflow"); return s[--sp]; } }; Implementing Inheritance Virtual Functions Virtual Functions class Shape { Simple: Add new fields to end of the object The Trick: Add a “virtual table” pointer to each object. virtual void draw(); // Invoked by object’s class struct A { Fields in base class always at same offset in derived class }; // not its compile-time type. A’s Vtbl B’s Vtbl class Line : public Shape { int x; Consequence: Derived classes can never remove fields void draw(); virtual void Foo(); A::Foo B::Foo C++ Equivalent C }; virtual void Bar(); A::Bar A::Bar class Arc : public Shape { class Shape { struct Shape { }; void draw(); a1 B::Baz double x, y; double x, y; }; struct B : A { vptr }; }; int y; Shape *s[10]; virtual void Foo(); x b1 s[0] = new Line; class Box : Shape { struct Box { virtual void Baz(); vptr s[1] = new Arc; a2 double h, w; double x, y; }; s[0]->draw(); // Invoke Line::draw() vptr x }; double h, w; s[1]->draw(); // Invoke Arc::draw() x y }; A a1, a2; B b1; Virtual Functions Virtual Functions Multiple Inheritance struct A { struct A { Rocket Science, int x; int x; and nearly as dangerous B’s Vtbl B’s Vtbl virtual void Foo(); virtual void Foo(); Inherit from two or more classes virtual void Bar() B::Foo virtual void Bar(); B::Foo { do something(); } A::Bar }; A::Bar class Window { ... }; }; B::Baz struct B : A { B::Baz class Border { ... }; struct B : A { int y; int y; virtual void Foo() class BWindow : public Window, virtual void Foo(); *a { something else(); } *a public Border { virtual void Baz(); vptr virtual void Baz(); vptr . }; x }; x . A *a = new B; A *a = new B; }; y y a->Bar(); a->Foo(); Multiple Inheritance Ambiguities Resolving Ambiguities Explicitly Duplicate Base Classes class Window { class Window { void draw(); }; A class may be inherited more than once void draw(); class Drawable { ... }; }; class Border { void draw(); }; class Window : public Drawable { ... }; class Border : public Drawable { ... }; class Border { class BWindow : public Window, class BWindow : public Window, public void draw(); // OK public Border { Border { ... }; }; void draw() { Window::draw(); } }; class BWindow : public Window, BWindow gets two copies of the Drawable base class. public Border { }; BWindow bw; bw.draw(); // OK BWindow bw; bw.draw(); // Compile-time error: ambiguous Virtual Base Classes Implementing Multiple Inheritance Implementation using Offsets struct A { int x; virtual void f(); } Virtual base classes are inherited at most once A virtual function expects a pointer to its object struct B { int y; virtual void f(); class Drawable { ... }; struct A { int x; virtual void f(); } virtual void g(); } class Window : public virtual Drawable { struct B { int y; virtual void f(); } struct C : A, B { int z; void f(); } ... }; struct C : A, B { int z; void f(); } B *b = new C; class Border : public virtual Drawable { b->f(); // Call C::f() ... }; B *obj = new C; “this” expected by C::f()! x class BWindow : public Window, public b->f(); // Calls C::f() B* obj! y C’s Virtual Tbl Border { ... }; this! vptr z &C::f 0 adjust from offset x b! vptr B in C’s V. Tbl BWindow gets two copies of the Drawable base class “obj” is, by definition, a pointer to a B, not a C. Pointer y &C::f −2 must be adjusted depending on the actual type of the z &B::g 0 object. At least two ways to do this. Implementation using Thunks Offsets vs. Thunks Exceptions struct A { int x; virtual void f(); } A high-level replacement struct B { int y; virtual void f(); Offsets Thunks for C’s setjmp/longjmp. virtual void g(); } struct Except { }; struct C : A, B { int z; void f(); } Offsets to virtual tables Helper functions B *b = new C; Can be implemented in C Needs “extra” semantics void baz() { throw Except; } b->f(); // Call C::f() All virtual functions cost more Only multiply-inherited functions cost void bar() { baz(); } Tricky Very Tricky void void foo() { C vtbl C::f in B(void *this) try { this! vptr &C::f x { bar(); } catch (Except e) { b! vptr this = this - 2; B in C’s vtbl y printf("oops"); &C::f in B goto C::f; z } &B::g } } One Way to Implement Exceptions Implementing Exceptions Cleverly Standard Template Library try { push(Ex, Handler); Real question is the nearest handler for a given PC. I/O Facilities throw Ex; throw(Ex); Lines Action iostream, fstream pop(); 1 void foo() { 1–2 Reraise Garbage-collected String class goto Exit; 2 3. look in table } catch (Ex e) { Handler: 3 try { 3–5 H1 Containers foo(); foo(); 4 bar(); 5 } catch (Ex1 e) { H1: a(); } 6–9 Reraise } Exit: 6 vector, list, queue, stack, map, set 7 } 2. H2 doesn’t handle Ex1, reraise 10–12 H2 Numerical push() adds a handler to a stack 8 void bar() { 9 1. look in table 13–14 Reraise complex, valarray pop() removes a handler 10 try { 11 throw Ex1(); General algorithms throw() finds first matching handler 12 } catch (Ex2 e) { H2: b(); } 13 search, sort 14 } Problem: imposes overhead even with no exceptions C++ I/O C++ I/O C++ String Class C’s printing facility is clever but not type safe. Easily extended to print user-defined types Provides automatic garbage collection, usually by char *s; int d; double g; ostream & reference counting. printf("%s %d %g", s, d, g); operator <<(ostream &o, MyType &m) { o << "An Object of MyType"; string s1, s2; return o; s1 = "Hello"; Hard for compiler to typecheck argument types against } s2 = "There"; format string. s1 += " goodbye"; C++ overloads the << and >> operators. This is type safe. Input overloads the >> operator s1 = ""; // Frees memory holding “Hello goodbye” cout << 's' << ' ' << d << ' ' << g; int read integer; cin >> read integer; C++ STL Containers Iterators Associative Containers Vector: dynamically growing and shrinking array of Mechanism for stepping through containers Keys must be totally ordered elements. vector<int> v; Implemented with trees—O(log n) for ( vector<int>::iterator i = v.begin(); vector<int> v; Set of objects i != v.end() ; i++ ) { v.push back(3); // vector can behave as a stack int entry = *i; set<int, less<int> > s; v.push back(2); } s.insert(5); int j = v[0]; // operator[] defined for vector set<int, less<int> >::iterator i = s.find(3); · · · " " v.begin() v.end() Map: Associative array map<int, char*> m; m[3] = "example"; C++ In Embedded Systems C++ Features With No Impact Inexpensive C++ Features Dangers of using C++: Classes Default arguments No or bad compiler for your particular processor • Fancy way to describe functions and structs • Compiler adds code at call site to set default Increased code size • Equivalent to writing object-oriented C code arguments Slower program execution Single inheritance •
Recommended publications
  • Improving Virtual Function Call Target Prediction Via Dependence-Based Pre-Computation
    Improving Virtual Function Call Target Prediction via Dependence-Based Pre-Computation Amir Roth, Andreas Moshovos and Gurindar S. Sohi Computer Sciences Department University of Wisconsin-Madison 1210 W Dayton Street, Madison, WI 53706 {amir, moshovos, sohi}@cs.wisc.edu Abstract In this initial work, we concentrate on pre-computing virtual function call (v-call) targets. The v-call mecha- We introduce dependence-based pre-computation as a nism enables code reuse by allowing a single static func- complement to history-based target prediction schemes. tion call to transparently invoke one of multiple function We present pre-computation in the context of virtual implementations based on run-time type information. function calls (v-calls), a class of control transfers that As shown in Table 1, v-calls are currently used in is becoming increasingly important and has resisted object-oriented programs with frequencies ranging from conventional prediction. Our proposed technique 1 in 200 to 1000 instructions (4 to 20 times fewer than dynamically identifies the sequence of operations that direct calls and 30 to 150 times fewer than conditional computes a v-call’s target. When the first instruction in branches). V-call importance will increase as object-ori- such a sequence is encountered, a small execution ented languages and methodologies gain popularity. For engine speculatively and aggressively pre-executes the now, v-calls make an ideal illustration vehicle for pre- rest. The pre-computed target is stored and subse- computation techniques since their targets are both diffi- quently used when a prediction needs to be made. We cult to predict and easy to pre-compute.
    [Show full text]
  • Valloy – Virtual Functions Meet a Relational Language
    VAlloy – Virtual Functions Meet a Relational Language Darko Marinov and Sarfraz Khurshid MIT Laboratory for Computer Science 200 Technology Square Cambridge, MA 02139 USA {marinov,khurshid}@lcs.mit.edu Abstract. We propose VAlloy, a veneer onto the first order, relational language Alloy. Alloy is suitable for modeling structural properties of object-oriented software. However, Alloy lacks support for dynamic dis- patch, i.e., function invocation based on actual parameter types. VAlloy introduces virtual functions in Alloy, which enables intuitive modeling of inheritance. Models in VAlloy are automatically translated into Alloy and can be automatically checked using the existing Alloy Analyzer. We illustrate the use of VAlloy by modeling object equality, such as in Java. We also give specifications for a part of the Java Collections Framework. 1 Introduction Object-oriented design and object-oriented programming have become predom- inant software methodologies. An essential feature of object-oriented languages is inheritance. It allows a (sub)class to inherit variables and methods from su- perclasses. Some languages, such as Java, only support single inheritance for classes. Subclasses can override some methods, changing the behavior inherited from superclasses. We use C++ term virtual functions to refer to methods that can be overridden. Virtual functions are dynamically dispatched—the actual function to invoke is selected based on the dynamic types of parameters. Java only supports single dynamic dispatch, i.e., the function is selected based only on the type of the receiver object. Alloy [9] is a first order, declarative language based on relations. Alloy is suitable for specifying structural properties of software. Alloy specifications can be analyzed automatically using the Alloy Analyzer (AA) [8].
    [Show full text]
  • Inheritance & Polymorphism
    6.088 Intro to C/C++ Day 5: Inheritance & Polymorphism Eunsuk Kang & JeanYang In the last lecture... Objects: Characteristics & responsibilities Declaring and defining classes in C++ Fields, methods, constructors, destructors Creating & deleting objects on stack/heap Representation invariant Today’s topics Inheritance Polymorphism Abstract base classes Inheritance Types A class defines a set of objects, or a type people at MIT Types within a type Some objects are distinct from others in some ways MIT professors MIT students people at MIT Subtype MIT professor and student are subtypes of MIT people MIT professors MIT students people at MIT Type hierarchy MIT Person extends extends Student Professor What characteristics/behaviors do people at MIT have in common? Type hierarchy MIT Person extends extends Student Professor What characteristics/behaviors do people at MIT have in common? �name, ID, address �change address, display profile Type hierarchy MIT Person extends extends Student Professor What things are special about students? �course number, classes taken, year �add a class taken, change course Type hierarchy MIT Person extends extends Student Professor What things are special about professors? �course number, classes taught, rank (assistant, etc.) �add a class taught, promote Inheritance A subtype inherits characteristics and behaviors of its base type. e.g. Each MIT student has Characteristics: Behaviors: name display profile ID change address address add a class taken course number change course classes taken year Base type: MITPerson
    [Show full text]
  • CSE 307: Principles of Programming Languages Classes and Inheritance
    OOP Introduction Type & Subtype Inheritance Overloading and Overriding CSE 307: Principles of Programming Languages Classes and Inheritance R. Sekar 1 / 52 OOP Introduction Type & Subtype Inheritance Overloading and Overriding Topics 1. OOP Introduction 3. Inheritance 2. Type & Subtype 4. Overloading and Overriding 2 / 52 OOP Introduction Type & Subtype Inheritance Overloading and Overriding Section 1 OOP Introduction 3 / 52 OOP Introduction Type & Subtype Inheritance Overloading and Overriding OOP (Object Oriented Programming) So far the languages that we encountered treat data and computation separately. In OOP, the data and computation are combined into an “object”. 4 / 52 OOP Introduction Type & Subtype Inheritance Overloading and Overriding Benefits of OOP more convenient: collects related information together, rather than distributing it. Example: C++ iostream class collects all I/O related operations together into one central place. Contrast with C I/O library, which consists of many distinct functions such as getchar, printf, scanf, sscanf, etc. centralizes and regulates access to data. If there is an error that corrupts object data, we need to look for the error only within its class Contrast with C programs, where access/modification code is distributed throughout the program 5 / 52 OOP Introduction Type & Subtype Inheritance Overloading and Overriding Benefits of OOP (Continued) Promotes reuse. by separating interface from implementation. We can replace the implementation of an object without changing client code. Contrast with C, where the implementation of a data structure such as a linked list is integrated into the client code by permitting extension of new objects via inheritance. Inheritance allows a new class to reuse the features of an existing class.
    [Show full text]
  • Inheritance | Data Abstraction Z Information Hiding, Adts | Encapsulation | Type Extensibility for : COP 3330
    OOP components Inheritance | Data Abstraction z Information Hiding, ADTs | Encapsulation | Type Extensibility For : COP 3330. z Operator Overloading Object oriented Programming (Using C++) | Inheritance http://www.compgeom.com/~piyush/teach/3330 z Code Reuse | Polymorphism Piyush Kumar “Is a” Vs “Has a” Another Example UML Vehicle Inheritance class Car : public Vehicle { public: Considered an “Is a” class relationship // ... Car }; e.g.: An HourlyEmployee “is a” Employee A Convertible “is a” Automobile We state the above relationship in several ways: * Car is "a kind of a" Vehicle A class contains objects of another class * Car is "derived from" Vehicle as it’s member data * Car is "a specialized" Vehicle * Car is the "subclass" of Vehicle Considered a “Has a” class relationship * Vehicle is the "base class" of Car * Vehicle is the "superclass" of Car (this not as common in the C++ community) e.g.: One class “has a” object of another class as it’s data Virtual Functions Virtual Destructor rule | Virtual means “overridable” | If a class has one virtual function, you | Runtime system automatically invokes want to have a virtual destructor. the proper member function. | A virtual destructor causes the compiler to use dynamic binding when calling the destructor. | Costs 10% to 20% extra overhead compared to calling a non-virtual | Constructors: Can not be virtual. You function call. should think of them as static member functions that create objects. 1 Pure virtual member Pure virtual. functions. | A pure virtual member function is a | Specified by writing =0 after the member function that the base class function parameter list. forces derived classes to provide.
    [Show full text]
  • Virtual Function in C++
    BCA SEMESTER-II Object Oriented Programming using C++ Paper Code: BCA CC203 Unit :4 Virtual Function in C++ By: Ms. Nimisha Manan Assistant Professor Dept. of Computer Science Patna Women’s College Virtual Function When the same function name is defined in the base class as well as the derived class , then the function in the base class is declared as Virtual Function. Thus a Virtual function can be defined as “ A special member function that is declared within a base class and redefined by a derived class is known as virtual function”. To declare a virtual function, in the base class precede the function prototype with the keyword virtual. Syntax for defining a virtual function is as follows:- virtual return_type function_name(arguments) { ------ } Through virtual function, functions of the base class can be overridden by the functions of the derived class. With the help of virtual function, runtime polymorphism or dynamic polymorphism which is also known as late binding is implemented on that function. A function call is resolved at runtime in late binding and so compiler determines the type of object at runtime. Late binding allows binding between the function call and the appropriate virtual function (to be called) to be done at the time of execution of the program. A class that declares or inherits a virtual function is called a polymorphic class. For Example: Virtual void show() { Cout<<”This is a virtual function”; } Implementation of Dynamic Polymorphism through Virtual Function Dynamic Polymorphism is implemented through virtual function by using a single pointer to the base class that points to all the objects of derived class classes.
    [Show full text]
  • Polymorphism
    Polymorphism A closer look at types.... Chap 8 polymorphism º comes from Greek meaning ‘many forms’ In programming: Def: A function or operator is polymorphic if it has at least two possible types. Polymorphism i) OverloaDing Def: An overloaDeD function name or operator is one that has at least two Definitions, all of Different types. Example: In Java the ‘+’ operator is overloaDeD. String s = “abc” + “def”; +: String * String ® String int i = 3 + 5; +: int * int ® int Polymorphism Example: Java allows user DefineD polymorphism with overloaDeD function names. bool f (char a, char b) { return a == b; f : char * char ® bool } bool f (int a, int b) { f : int * int ® bool return a == b; } Note: ML Does not allow function overloaDing Polymorphism ii) Parameter Coercion Def: An implicit type conversion is calleD a coercion. Coercions usually exploit the type-subtype relationship because a wiDening type conversion from subtype to supertype is always DeemeD safe ® a compiler can insert these automatically ® type coercions. Example: type coercion in Java Double x; x = 2; the value 2 is coerceD from int to Double by the compiler Polymorphism Parameter coercion is an implicit type conversion on parameters. Parameter coercion makes writing programs easier – one function can be applieD to many subtypes. Example: Java voiD f (Double a) { ... } int Ì double float Ì double short Ì double all legal types that can be passeD to function ‘f’. byte Ì double char Ì double Note: ML Does not perform type coercion (ML has no notion of subtype). Polymorphism iii) Parametric Polymorphism Def: A function exhibits parametric polymorphism if it has a type that contains one or more type variables.
    [Show full text]
  • All Your Base Transactions Belong to Us
    All Your Base Transactions Belong to Us Jeff Vance, Alex Melikian Verilab, Inc Austin, TX, USA www.verilab.com ABSTRACT Combining diverse transaction classes into an integrated testbench, while common practice, typically produces a cumbersome and inadequate setup for system-level verification. UVM sequence item classes from different VIPs typically have different conventions for storing, printing, constraining, comparing, and covering behavior. Additionally, these classes focus on generic bus aspects and lack context for system coverage. This paper solves these problems using the mixin design pattern to supplement all transaction classes with a common set of metadata and functions. A mixin solution can be applied to any project with minimal effort to achieve better visibility of system-wide dataflow. This setup enables significantly faster debug time, higher quality bug reports, and increases the efficiency of the verification team. Combining a mixin with an interface class results in a powerful and extensible tool for verification. We show how to define more accurate transaction coverage with extensible covergroups that are reusable with different transaction types. Scoreboard complexity is reduced with virtual mixin utility methods, and stimulus is managed with shared constraints for all interface traffic. Finally, we show this solution can be retrofitted to any legacy UVM testbench using standard factory overrides. SNUG 2019 Table of Contents 1. Introduction ...........................................................................................................................................................................
    [Show full text]
  • C/C++ Program Design CS205 Week 10
    C/C++ Program Design CS205 Week 10 Prof. Shiqi Yu (于仕琪) <[email protected]> Prof. Feng (郑锋) <[email protected]> Operators for cv::Mat Function overloading More convenient to code as follows Mat add(Mat A, Mat B); Mat A, B; Mat add(Mat A, float b); float a, b; Mat add(float a, Mat B); //… Mat C = A + B; Mat mul(Mat A, Mat B); Mat D = A * B; Mat mul(Mat A, float b); Mat E = a * A; Mat mul(float a, Mat B); ... operators for cv::Mat #include <iostream> #include <opencv2/opencv.hpp> using namespace std; int main() { float a[6]={1.0f, 1.0f, 1.0f, 2.0f, 2.0f, 2.0f}; float b[6]={1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f}; cv::Mat A(2, 3, CV_32FC1, a); cv::Mat B(3, 2, CV_32FC1, b); cv::Mat C = A * B; cout << "Matrix C = " << endl << C << endl; return 0; } The slides are based on the book <Stephen Prata, C++ Primer Plus, 6th Edition, Addison-Wesley Professional, 2011> Operator Overloading Overloading • Function overloading Ø Let you use multiple functions sharing the same name Ø Relationship to others: üDefault arguments üFunction templates • * operator (An operator overloading example) Ø Applied to an address, yield the value stored at that address Ø Applied two numbers, yield the product of the values Operator Function • Operator function Ø Keyword: operator for C++ Ø To overload an operator, you use a special function Ø Function header has the form: üoperator+() overloads the + operator üoperator*() overloads the * operator üoperator[]() overloads the [] operator Ø The compiler, recognizing the operands as belonging to the class, replaces the
    [Show full text]
  • Importance of Virtual Function, Function Call Binding, Virtual Functions, Implementing Late Binding, Need for Virtual Functions
    Object Oriented Programming Using C++ Unit 7th Semester 4th Importance of virtual function, function call binding, virtual functions, implementing late binding, need for virtual functions, abstract base classes and pure virtual functions, virtual destructors _______________________________________________________________________________ Importance of virtual function: A virtual function is a member function that is declared within a base class and redefined by a derived class. To create virtual function, precede the function’s declaration in the base class with the keyword virtual. When a class containing virtual function is inherited, the derived class redefines the virtual function to suit its own needs. Virtual Functions are used to support "Run time Polymorphism". You can make a function virtual by preceding its declaration within the class by keyword 'virtual'. When a Base Class has a virtual member function, any class that inherits from the Base Class can redefine the function with exactly the same prototype i.e. only functionality can be redefined, not the interface of the function. A Base class pointer can be used to point to Base Class Object as well as Derived Class Object. When the virtual function is called by using a Base Class Pointer, the Compiler decides at Runtime which version of the function i.e. Base Class version or the overridden Derived Class version is to be called. This is called Run time Polymorphism. What is Virtual Function? A virtual function is a member function within the base class that we redefine in a derived class. It is declared using the virtual keyword. When a class containing virtual function is inherited, the derived class redefines the virtual function to suit its own needs.
    [Show full text]
  • CHAPTER-3 Function Overloading SHORT ANSWER QUESTIONS 1
    CHAPTER-3 Function Overloading SHORT ANSWER QUESTIONS 1. How does the compiler interpret more than one definitions having same name? What steps does it follow to distinguish these? Ans. The compiler will follow the following steps to interpret more than one definitions having same name: (i) if the signatures of subsequent functions match the previous function’s, then the second is treated as a re- declaration of the first. (ii) if the signature of the two functions match exactly but the return type differ, the second declaration is treated as an erroneous re-declaration of the first and is flagged at compile time as an error. (iii) if the signature of the two functions differ in either the number or type of their arguments, the two functions are considered to be overloaded. 2. Discuss how the best match is found when a call to an overloaded function is encountered? Give example(s) to support your answer. Ans. In order to find the best possible match, the compiler follows the following steps: 1. Search for an exact match is performed. If an exact match is found, the function is invoked. For example, 2. If an exact match is not found, a match trough promotion is searched for. Promotion means conversion of integer types char, short, enumeration and int into int or unsigned int and conversion of float into double. 3. If first two steps fail then a match through application of C++ standard conversion rules is searched for. 4. If all the above mentioned steps fail, a match through application of user-defined conversions and built-in conversion is searched for.
    [Show full text]
  • Examination 2016 OBJECT ORIENTED PROGRAMMING (2015 Pattern) Nov / Dec 2016 Time : 2 Hours Maximum Marks : 50
    S.E Computer (First Semester) Examination 2016 OBJECT ORIENTED PROGRAMMING (2015 Pattern) Nov / Dec 2016 Time : 2 Hours Maximum Marks : 50 Q.1 a) Difference Between Procedure Oriented Programming (POP) & Object Oriented Programming (OOP) 4M Procedure Oriented Programming Object Oriented Programming In POP, program is divided into small In OOP, program is divided into parts Divided Into parts called functions. called objects. In POP,Importance is not given to data In OOP, Importance is given to the data Importance but to functions as well as sequence of rather than procedures or functions actions to be done. because it works as a real world. Approach POP follows Top Down approach. OOP follows Bottom Up approach. Access OOP has access specifiers named POP does not have any access specifier. Specifiers Public, Private, Protected, etc. In OOP, objects can move and In POP, Data can move freely from Data Moving communicate with each other through function to function in the system. member functions. To add new data and function in POP is OOP provides an easy way to add new Expansion not so easy. data and function. In OOP, data can not move easily from In POP, Most function uses Global data function to function,it can be kept public Data Access for sharing that can be accessed freely or private so we can control the access from function to function in the system. of data. POP does not have any proper way for OOP provides Data Hiding so provides Data Hiding hiding data so it is less secure. more security. In OOP, overloading is possible in the Overloading In POP, Overloading is not possible.
    [Show full text]