Distributed Real-Time Control Systems. Lecture 14 Intro to C++ Part III
|
|
- Sydney Lyons
- 5 years ago
- Views:
Transcription
1 Distributed Real-Time Control Systems Lecture 14 Intro to C++ Part III 1
2 Class Hierarchies The human brain is very efficient in finding common properties to different entities and classify them according to their properties or behaviour. Example: Mammals summarizes a large set of properties common to a class of animals (have dorsal spine, warm blood, feed from mother s milk in infanthood, etc.). This way, many efforts are saved in the classification and attribute assignment to different animals. How can we do this in C++? 2
3 Designing a Database System Imagine a factory of wooden blocks for kids wants to store their products in a database and be able to display their mass (weight) when queried. Initially the factory produces cylinders and cubes but wants a system that can incorporate new shapes. Cylinder Cube Other?... 3
4 The Cylinder Class FILE simple_cylinder.h #ifndef SIMPLE_CYLINDER_H #define SIMPLE_CYLINDER_H #include <iostream> //need std::cout using namespace std; constexpr double PI {3.1415; //needed to compute the area of the base class SimpleCylinder { float _r, _h, _d; // private: radius, height and density, resp. public: SimpleCylinder (float r, float h, float d) // constructor definition (inline) : _r {r, _h {h, _d {d { // initialization of member variables cout << Creating SimpleCylinder << endl; ~SimpleCylinder() { // destructor definition (inline) std::cout << Destroying SimpleCylinder << endl; float CalcMass() { //member function (inline) return PI*_r*_r*_h*_d; ; #endif //SIMPLE_CYLINDER_H 4
5 Sidenote: Const and Constexpr Two ways to define constants: Compile time constant expressions (constexpr) Expression that can be computed at compile time. Use when initializations are time consuming : initialization at compile time are done once, rather than every time the program runs. Run time constants (const) A constant that must be initialized at run time (possibly not known at compile time). Use when need non-modifiable variables to be initialized with run-time data. Const s or Constexpr s are preferred to aliases (#define ) because they have explicit type checking. What is the problem with the following code? #define LENGTH 3... cout << LENGTH/2 << endl; EXAMPLES: const int dmv = 17; //dmv is named constant int var = 17; //var is not a constant constexpr double square(double x) { return x x; //constexpr function constexpr double max1=4 square(dmv); //OK. 4*square(dmv) is a constexpr constexpr double max2= 4 square(var); // error: var is not a constant expression const double max3 = 4 square(var); // OK, may be evaluated at run time 5
6 The Cube Class FILE simple_cube.h #ifndef SIMPLE_CUBE_H #define SIMPLE_CUBE_H #include <iostream> //need std::cout using namespace std; class SimpleCube{ float _s, _d; // private: side lenght and material density, resp. public: SimpleCube (float s, float d) // constructor definition (inline) : _s {s, _d{d { // initialization of member variables cout << Creating SimpleCube\n << endl; ~SimpleCube() { // destructor definition (inline) std::cout << Destroying SimpleCube << endl; float CalcMass() { //member function (inline) return _s*_s*_s*_d; ; #endif //SIMPLE_CUBE_H 6
7 Using Cubes and Cylinders FILE simple_blocks.cpp #include <iostream> //need std::cout using namespace std; #include simple_cube.h #include simple_cylinder.h int main() { SimpleCylinder obj1 {2.0,1.0,0.9; SimpleCube obj2 {3.0,0.9; float m1 = obj1.calcmass(); float m2 = obj2.calcmass(); float M = m1+m2; cout << Total Mass << M << endl; Encapsulation: Instead of explicitly computing the mass, our code just asks the class to do the job for us. The client code does not need to know how its mass is computed. The client code does not need to care about how the cylinder class stores data internally. In the future, the class developer can change the class implementation (e.g. to increase efficiency) without breaking the client code. Compile with: g++ -std=c++11 I. simple_blocks.cpp o simple_blocks 7
8 Problems with this approach To add a new object type, we have to rewrite it from scratch. If we want to add a price field to all the blocks, we have to change all classes. Cannot have a collection of arbitrary blocks because their types may differ. 8
9 The Hierarchy Object oriented programming help us think about hierarchies of objects, from the more general to the more specific classes. Having a Solid class representing the common things among all blocks, solves the problems mentioned in the previous slide. How? More general - Superclass Solid Cube Sphere More specific - Subclass 9
10 Inheritance Definition (Inheritance): Inheritance is the mechanism that allows one class A get the properties of another class B. In this case we say that A inherits from B. Objects from class A can access the attributes and methods from class B without having to redefine them. The following definition introduces two terms that deal with the concept of inheritance between classes. Solid (B) Cube (A) Inherit-from Definition (Superclass/Subclass): Case class A inherits from class B, then B is called a Superclass of A. A is denoted the subclass of B. 10
11 The Superclass Also called base class. All solids have density. Let us also add a Constructor and Destructor; Note 1: The density variable (float _d) is protected. This means clients cannot access this variable but derived classes can. Note 2: A constructor is defined. This deletes the default constructor. Since the provided constructor demandsan argument (the solid density) and does not provide a default value, it is not possible to create an empty Solid object. #ifndef SOLID1_H #define SOLID1_H #include <iostream> using namespace std; FILE solid1.h class Solid1 { protected: //must be used by subclasses float _d; public: Solid1( float d ) : _d {d { cout << Creating Solid1 << endl; ~Solid1() { cout << Destroying Solid1 << endl; ; #endif // SOLID1_H 11
12 The Subclasses Also called derived classes FILE cylinder1.h #ifndef CYLINDER1_H #define CYLINDER1_H #include solid1.h constexpr double PI {3.1415; class Cylinder1 : public Solid1 { float _r, _h; public: Cylinder1 (float r, float h, float d) : _r {r, _h {h, Solid1 {d { cout<< Creating Cylinder1 <<endl; ~Cylinder1() { cout << DestroyingCylinder1 <<endl; float CalcMass(){return PI*_r*_r*_h*_d; ; #endif //CYLINDER1_H #ifndef CUBE1_H #define CUBE1_H #include solid1.h FILE cube1.h class Cube1 : public Solid1 { float _s; public: Cube1 (float s, float d) : _s {s, Solid1{d { cout << Creating Cube1 <<endl; ~Cube1() { cout << Destroying Cube1 << endl; float CalcMass(){return _s*_s*_s*_d; ; #endif //CUBE1_H 12
13 Access Protection Inheritance class Cube : public Solid { /* members of Solid maintain the protection level in Cube*/ ; class Cube : protected Solid { /* public members in Solid become protected in Cube, others remain */ ; class Cube : private Solid { /* all members of Solid become private in Cube */ ; It is saidthat class Cube inherits from Solid. Cube can access all members of Solid independently of their protection level. Access public protected private members of the same class members of derived classes not members yes yes yes yes yes no yes no no 13
14 Base Class Initialization Note the base class is initialized in the constructor of the derived classusing member initializer lists. FILE cylinder.h FILE cube.h... Cylinder (float r, float h, float d) : _r {r, _h {h, //member variable init Solid {d //base class init { std::cout << Creating Cylinder\n ; Cube (float s, float d) : _s {s, //member variable init Solid{d //base class init { stc::cout << Creating Cube\n ;... 14
15 Construction and Destruction of Derived Objects Constructors are invoked in order from the base classes to the derived classes. Destructors are invoked from the derived classes to the base classes. Objects are destroyed in the inverse order of their creation. What is the output of the following code? #include cube1.h #include cylinder1.h int main() { Cube1 obj1 {3.0, 0.9; Cylinder1 obj2 {2.0, 1.0, 0.9; Output: Creating Solid1 Creating Cube1 Creating Solid1 Creating Cylinder1 Destroying Cylinder1 Destroying Solid1 Destroying Cube1 Destroying Solid1 FILE blocks1.cpp 15
16 Friend Classes and Functions The friend qualifier allows access to protected or private fields to other classes or functions. Only functions or classes declared friend can use private class attributes Let us define a function SameVol that tests if a Cube and a Cylinder have the same volume. This function must access private data of the cylinder and cube objects, so it must be declared friend in the Cylinder and Cube classes. // The friend function bool SameVol(Cube a, Cylinder b) { return a._s*a_s*a._s == PI*b._r*b._r*b._h; class Cube { friend bool SameVol(Cube, Cylinder); ; class Cylinder { friend bool SameVol(Cube, Cylinder); ; 16
17 References to Objects The reference to an object is a C++ feature. (Not available in C). It can be seen as a constant pointer that is automatically dereferenced. int i =3; int *p = &i; int &j = i; Symbol Type Mem Addr Value i, j int p int * We say that j is a reference to i. This means to give variable i a second name: j (alias). References must be initialized at construction (like consts). 17
18 Reference vs Value Arguments #include <iostream> using namespace std; void symm(int & j) { //REF ARG j = -1 * j; int main() { int i = 3; symm( i ); cout << result: << i; #include <iostream> using namespace std; void symm(int j) { //VALUE ARG j = -1 * j; int main() { int i = 3; symm( i ); cout << result: << i; result: -3 result: 3 18
19 Efficiency Issues Passing objects to functions by reference is much more efficient whendealing withlarge objects. Passing values to functions by value implies a copy of the argument (clone) to thecalled function. obj obj clone main func main func 19
20 Operator Overloading Operators are like functions. They can also be overloaded. We can redefine what the following operators do when applied to objects of our classes: + - * / = < > += -= *= /= << >> <<= >>= ==!= <= >= % & ^! ~ &= ^= = && %= [] () ->* -> new delete new[] delete[], 20
21 Operators are functions When we write It is the same as writing: MyClass a, b;... a+b; MyClass a, b;... a.operator+(b); operator+() is a function. 21
22 Example: Overloaded Operator for Cubes FILE cube1a.h Let us redefine the == operator in the class Cube to test if two cubes have the same shape and density. If we need the same functionality for Cylinders, we need to overide the == operator for Cylinders. Could we override the base class operator == instead? Yes, butthis will require abstract classes and virtual functions next lecture. #ifndef CUBE1A_H #define CUBE1A_H #include solid1.h class Cube1a : public Solid1 { float _s; public: Cube1a (float s, float d) : _s {s, Solid1{d { cout << Creating Cube1a <<endl; ~Cube1a() { cout << Destroying Cube1a << endl; float CalcMass(){return _s*_s*_s*_d; bool operator==(cube1a &c) { return (_s==c._s) && (_d==c._d); ; #endif //CUBE1A_H 22
23 Example: Testing Overloaded Operator for Cubes FILE blocks1a.h What is the output of the following code? Note that the method just created does not distinguish clones from the object itself. How can we do this? #include "cube1a.h int main() { Cube1a c1 {3.0, 0.9; Cube1a c2 {3.0, 0.9; Cube1a c3 {3.0, 1.0; cout << (c1==c1) << " " << (c1==c2) << " " << (c1==c3) << endl; Output: Creating Solid1 Creating Cube Destroying Cube1 Destroying Solid1 23
24 The this pointer FILE cube1a.h The keyword this represents a pointer to the object whose member function is being executed - it is a pointer to the object itself. One of its uses can be to check if a parameter passed to a member function is the object itself Let us overload the boolean operator && to provide this functionality. #ifndef CUBE1A_H #define CUBE1A_H #include solid1.h class Cube1a : public Solid1 { float _s; public: Cube1a (float s, float d) : _s {s, Solid1{d { cout << Creating Cube1a <<endl; ~Cube1a() { cout << Destroying Cube1a\n ; float CalcMass(){return _s*_s*_s*_d; bool operator==(cube1a &c) { return (_s==c._s) && (_d==c._d); bool operator&&(cube1a &c) { return this == &c; ; #endif //CUBE1A_H 24
25 Example FILE blocks1a.h Try the following code. What is the output now? #include "cube1a.h int main() { Cube1a c1 {3.0, 0.9; Cube1a c2 {3.0, 0.9; Cube1a c3 {3.0, 1.0; cout << (c1&&c1) << " " << (c1&&c2) << " " << (c1&&c3) << endl; Output: Creating Solid1 Creating Cube Destroying Cube1 Destroying Solid1 25
26 Assignment Operator When we write MyClass a, b;... b = a; It is the same as writing: MyClass a, b;... b.operator=(a); operator=() is called the assignment operator. The compiler provides a default assignment operator for all classes. The default assignment operator just copies the values of the member variables of the right and argument to the left hand object. If the intended behavior is different, one has to override the assignment operator. 26
27 Assignment Operator Let us define an assignment operator to our Cube class. The assignment operator returns a reference to the current object. Consider the assignment c2=c1: The purpose is to assign the properties of c1 to c2. We are invoking a member function of c2 with argument c1. Variable _s refers to c2 and c._s refers to c1. The invocation of base the class (Solid) assignment operator is not automatic, must be done explicitly. FILE cube1b.h #ifndef CUBE1B_H #define CUBE1B_H #include solid1.h class Cube1b : public Solid1 { float _s; public: Cube1b (float s, float d): _s {s, Solid1{d { cout << Creating Cube1b <<endl; ~Cube1b() { cout << Destroying Cube1b\n ; float CalcMass(){return _s*_s*_s*_d; Cube1b& operator= (const Cube1b & c ) { if ( this == &c) return (*this) ; Solid::operator=(c); //base class assignment _s = c._s; cout << Cube1b assignment << endl; return (*this); ; #endif //CUBE1B_H 27
28 Cascading Operators Why returning *this (reference to the object itself)? After assigning the values, our objective is complete. However we should also support operations like: c3 = c2 = c1 ó c3 = (c2 = c1) ó c3.operator=( c2.operator=(c1) ) This means: assign c1 to c2, then assign c2 to c3. What happens in this case: The assignment operator of c2 is called with a parameter of type reference to c1. The member variables of c1 are assigned to c2 and a reference to c2 is returned. The assignment operator of c3 is called with the reference to c2. Then the member variables of c2 are assigned to c3. 28
29 The copy constructor Cube c1 {1.0,1.0; Cube c2 {2.0,2.0; c2 = c1; Code 1 Code 2 Cube c1 {1.0,1.0 Cube c2 {c1; What are the differences? The result is quite similar but what happens is substantially different. In the left, the compiler invokes: 1. Constructor of c1 with float arguments 2. Constructor of c2 with float arguments 3. The assignment operator= of object c2 with argument c1. In the right, c2 is constructed with argument c1. This requires a special constructor: the Copy Constructor. The compiler provides a default copy constructor for all classes. The default copy constructor just initializes the values of object to construct with the values of the member variables of the object in the argument. 29
30 Overriding Copy Constructor for Cubes class Cube : public Solid { public: // Copy constructor Cube (const Cube & c) : Solid {c //init base class { _s = c._s; ; The copy constructor does not return a value. The argument is const because it should not be changed. The compiler always create a default copy constructor that copies each member variable (including for base class). Define your own copy constructor if behaviour different from default is needed. In this case you must also implement the initialization of the base classes. 30
31 Overriding Copy Constructor for Cubes The copy constructor does not return a value. The argument is const because it should not be changed. The compiler always create a default copy constructor that copies each member variable (including for base class). Define your own copy constructor if behaviour different from default is needed. In this case you must also implement the initialization of the base classes. FILE cube1b.h #ifndef CUBE1B_H #define CUBE1B_H #include solid1.h class Cube1b : public Solid1 { float _s; public: Cube1b (float s, float d): _s {s, Solid1{d { cout << Creating Cube1b <<endl; ~Cube1b() {cout << Destroying Cube1b\n ; float CalcMass(){return _s*_s*_s*_d; Cube1b& operator= (const Cube1b & c ) { if ( this == &c) return (*this) ; Solid::operator=(c); _s = c._s; cout << Cube1b assignment << endl; return (*this); Cube1b(const Cube1b & c ) : Solid1{c._d //base class initialization {_s = c._s; cout << Cube1b copy constructor << endl; ; #endif //CUBE1B_H 31
32 Automatic Use Copy Constructor The copy constructor is automatically invoked in: object initialization. passing and returning value arguments in functions. Compiler optimizations may circumvent some constructors (E.g. return value optimization). FILE blocks1b.h #include "cube1b.h Cube1b func(cube1b c) { return Cube1b {c; int main() { Cube1b c1 {1.0,1.0; Cube1b c2 {c1; Cube1b c3 = c1; c3 = c2; Cube1b c4 = func(c1) Output: Creating Solid1 Creating Cube1b Creating Solid1 Cube1b copy constructor Creating Solid1 Cube1b copy constructor Cube1b assignment Creating Solid1 Cube1b copy constructor Creating Solid1 Cube1b copy constructor Destroying c1 {1.0,1.0 c2 {c1 Cube1b c3 = c1 c3 = c2 func(c1) Cube1b c4 =... 32
33 Private Constructors and Deleted Functions Sometimes objects should not be cloned. E.g. when holding unique resources in the system. To prevent object cloning, the copy constructor and the assignment operator should be made private. Cloning can only be done by member functions. Alternativelly, they can be marked as deleted. In this case their cloning is impossible Other member functions can be deleted, e.g. to prevent implicit type conversion in constructors. // class with private clone operations class A { private: A (const A &); A& operator = (const A & );... ; // class with deleted clone operations class B { A (const A &) = delete; A& operator = (const A & ) = delete; ; //class with deleted contructor for int class C { public: C (double); //can initialize from double C (int) = deleted; //but not from int 33
Distributed Real-Time Control Systems. Chapter 13 C++ Class Hierarchies
Distributed Real-Time Control Systems Chapter 13 C++ Class Hierarchies 1 Class Hierarchies The human brain is very efficient in finding common properties to different entities and classify them according
More informationDistributed Real- Time Control Systems 13/14
Distributed Real- Time Control Systems 13/14 Lecture 10 C++ Programming Operators and more A. Bernardino, C. Silvestre, IST- ACSDC 1 References From C programming we know that int i =3; int *p; p = &i;
More informationDistributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes
Distributed Real-Time Control Systems Lecture 17 C++ Programming Intro to C++ Objects and Classes 1 Bibliography Classical References Covers C++ 11 2 What is C++? A computer language with object oriented
More informationG52CPP C++ Programming Lecture 13
G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and
More informationCS304 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 informationPolymorphism 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 informationShort 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 informationCS201 - 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 informationModern 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 informationIntro 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 informationAN 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 informationObject Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year
Object Oriented Programming Assistant Lecture Omar Al Khayat 2 nd Year Syllabus Overview of C++ Program Principles of object oriented programming including classes Introduction to Object-Oriented Paradigm:Structures
More informationPaytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value
Paytm Programming Sample paper: 1) A copy constructor is called a. when an object is returned by value b. when an object is passed by value as an argument c. when compiler generates a temporary object
More informationInheritance, 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 informationVIRTUAL 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 informationFast 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 informationCS304 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 informationLecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology
Lecture 8: Object-Oriented Programming (OOP) 1 Introduction to C++ 2 Overview Additional features compared to C: Object-oriented programming (OOP) Generic programming (template) Many other small changes
More informationCS250 Final Review Questions
CS250 Final Review Questions The following is a list of review questions that you can use to study for the final. I would first make sure you review all previous exams and make sure you fully understand
More informationOBJECT 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 informationWhat is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1
Polymorphism Part 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid adult
More informationCSE 303: Concepts and Tools for Software Development
CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects
More informationFunction Overloading
Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures
More informationFinancial computing with C++
Financial Computing with C++, Lecture 4 - p1/19 Financial computing with C++ LG Gyurkó University of Oxford Michaelmas Term 2015 Financial Computing with C++, Lecture 4 - p2/19 Outline General properties
More information6.096 Introduction to C++ January (IAP) 2009
MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture
More informationReference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that
Reference Parameters There are two ways to pass arguments to functions: pass-by-value and pass-by-reference. pass-by-value A copy of the argument s value is made and passed to the called function. Changes
More informationOutline 2017/03/17. (sections from
Outline 2017/03/17 clarifications I/O basic namespaces and structures (recall) Object Oriented programming (8.1) Classes (8.2 8.6) public, protected and private Constructors and destructors Getters and
More informationData 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 informationChapter 5 Object-Oriented Programming
Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares
More informationLecture 7. Log into Linux New documents posted to course webpage
Lecture 7 Log into Linux New documents posted to course webpage Coding style guideline; part of project grade is following this Homework 4, due on Monday; this is a written assignment Project 1, due next
More informationInstantiation 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 informationCMSC 132: Object-Oriented Programming II
CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation
More informationInterview 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 information3.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 informationOutline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O
Outline EDAF30 Programming in C++ 2. Introduction. More on function calls and types. Sven Gestegård Robertz Computer Science, LTH 2018 1 Function calls and parameter passing 2 Pointers, arrays, and references
More informationC++ Important Questions with Answers
1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children
More informationProgramming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor
Programming C++ Lecture 3 Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Inheritance S Software reuse inherit a class s data and behaviors and enhance with new capabilities.
More informationPOLYMORPHISM 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 informationPOLYMORPHISM 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 informationObject-Oriented Programming
- oriented - iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 56 Overview - oriented 1 2 -oriented 3 4 5 6 7 8 Static and friend elements 9 Summary 2 / 56 I - oriented was initially created by Bjarne
More informationMake Classes Useful Again
Make Classes Useful Again CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 11 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona
More informationIntroduction 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 informationThe 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 informationCE221 Programming in C++ Part 1 Introduction
CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab
More informationAdvanced Systems Programming
Advanced Systems Programming Introduction to C++ Martin Küttler September 19, 2017 1 / 18 About this presentation This presentation is not about learning programming or every C++ feature. It is a short
More informationCSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many
More informationHomework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine
Homework 6 Yuji Shimojo CMSC 330 Instructor: Prof. Reginald Y. Haseltine July 21, 2013 Question 1 What is the output of the following C++ program? #include #include using namespace
More informationIntermediate Programming, Spring 2017*
600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general
More informationAbstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles
Abstract Data Types (ADTs) CS 247: Software Engineering Principles ADT Design An abstract data type (ADT) is a user-defined type that bundles together: the range of values that variables of that type can
More informationInheritance and Polymorphism
Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg
More informationObject-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 informationMidterm Exam 5 April 20, 2015
Midterm Exam 5 April 20, 2015 Name: Section 1: Multiple Choice Questions (24 pts total, 3 pts each) Q1: Which of the following is not a kind of inheritance in C++? a. public. b. private. c. static. d.
More informationCSCE 110 PROGRAMMING FUNDAMENTALS
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table
More informationExtending Classes (contd.) (Chapter 15) Questions:
Extending Classes (contd.) (Chapter 15) Questions: 1 Virtual Functions in C++ Employee /\ / \ ---- Manager 2 Case 1: class Employee { string firstname, lastname; //... Employee( string fnam, string lnam
More informationLecture-5. Miscellaneous topics Templates. W3101: Programming Languages C++ Ramana Isukapalli
Lecture-5 Miscellaneous topics Templates W3101: Programming Languages C++ Miscellaneous topics Miscellaneous topics const member functions, const arguments Function overloading and function overriding
More informationCS
CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and
More informationC++ (Non for C Programmer) (BT307) 40 Hours
C++ (Non for C Programmer) (BT307) 40 Hours Overview C++ is undoubtedly one of the most widely used programming language for implementing object-oriented systems. The C++ language is based on the popular
More informationArgument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.
Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar
More informationCS 247: Software Engineering Principles. ADT Design
CS 247: Software Engineering Principles ADT Design Readings: Eckel, Vol. 1 Ch. 7 Function Overloading & Default Arguments Ch. 12 Operator Overloading U Waterloo CS247 (Spring 2017) p.1/17 Abstract Data
More informationCPSC 427: Object-Oriented Programming
CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 7 September 21, 2016 CPSC 427, Lecture 7 1/21 Brackets Example (continued) Storage Management CPSC 427, Lecture 7 2/21 Brackets Example
More informationCOMP322 - Introduction to C++
COMP322 - Introduction to C++ Winter 2011 Lecture 2 - Language Basics Milena Scaccia School of Computer Science McGill University January 11, 2011 Course Web Tools Announcements, Lecture Notes, Assignments
More informationCSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010
CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)
More informationcs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.
cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... today: language basics: identifiers, data types, operators, type conversions, branching and looping, program structure
More informationC How to Program, 6/e, 7/e
C How to Program, 6/e, 7/e prepared by SENEM KUMOVA METİN modified by UFUK ÇELİKKAN and ILKER KORKMAZ The textbook s contents are also used 1992-2010 by Pearson Education, Inc. All Rights Reserved. Two
More informationIntroduction 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 informationPIC 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 informationComputer Programming Inheritance 10 th Lecture
Computer Programming Inheritance 10 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2015 Eom, Hyeonsang All Rights Reserved 순서 Inheritance
More informationexplicit class and default definitions revision of SC22/WG21/N1582 =
Doc No: SC22/WG21/ N1702 04-0142 Project: JTC1.22.32 Date: Wednesday, September 08, 2004 Author: Francis Glassborow & Lois Goldthwaite email: francis@robinton.demon.co.uk explicit class and default definitions
More informationComp-304 : Object-Oriented Design What does it mean to be Object Oriented?
Comp-304 : Object-Oriented Design What does it mean to be Object Oriented? What does it mean to be OO? What are the characteristics of Object Oriented programs (later: OO design)? What does Object Oriented
More informationChapter 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 informationCS 376b Computer Vision
CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves
More informationCS3157: 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 informationObject Oriented Design
Object Oriented Design Lecture 3: Introduction to C++ (Continue) Examples using declarations that eliminate the need to repeat the std:: prefix 1 Examples using namespace std; enables a program to use
More informationCOMP322 - Introduction to C++ Lecture 02 - Basics of C++
COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.
More informationCS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE
CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate
More informationC++ 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 informationOutline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor
Outline EDAF50 C++ Programming 4. Classes Sven Gestegård Robertz Computer Science, LTH 2018 1 Classes the pointer this const for objects and members Copying objects friend inline 4. Classes 2/1 User-dened
More informationObject-Oriented Programming in C++
Object-Oriented Programming in C++ Pre-Lecture 9: Advanced topics Prof Niels Walet (Niels.Walet@manchester.ac.uk) Room 7.07, Schuster Building March 24, 2015 Prelecture 9 Outline This prelecture largely
More informationGraphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub
Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java
More informationprivate: // can only be used by the member functions of MyType and friends of MyType };
CSCI 3110 Inheritance (1) 1. Inheritance a relationship among classes whereby a class derives properties from a previously defined class. Inheritance provides a means of deriving a new class from existing
More informationCAAM 420 Fall 2012 Lecture 29. Duncan Eddy
CAAM 420 Fall 2012 Lecture 29 Duncan Eddy November 7, 2012 Table of Contents 1 Templating in C++ 3 1.1 Motivation.............................................. 3 1.2 Templating Functions........................................
More informationADTs in C++ In C++, member functions can be defined as part of a struct
In C++, member functions can be defined as part of a struct ADTs in C++ struct Complex { ; void Complex::init(double r, double i) { im = i; int main () { Complex c1, c2; c1.init(3.0, 2.0); c2.init(4.0,
More informationLab 2: ADT Design & Implementation
Lab 2: ADT Design & Implementation By Dr. Yingwu Zhu, Seattle University 1. Goals In this lab, you are required to use a dynamic array to design and implement an ADT SortedList that maintains a sorted
More informationData 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 informationCSc 328, Spring 2004 Final Examination May 12, 2004
Name: CSc 328, Spring 2004 Final Examination May 12, 2004 READ THIS FIRST Fill in your name above. Do not turn this page until you are told to begin. Books, and photocopies of pages from books MAY NOT
More informationC++_ 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 informationSoftware Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example
Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell
More informationC++ Modern and Lucid C++ for Professional Programmers
Informatik C++ Modern and Lucid C++ for Professional Programmers part 13 Prof. Peter Sommerlad Institutsleiter IFS Institute for Software Rapperswil, HS 2015 Inheritance and dynamic Polymorphism base classes,
More informationthe gamedesigninitiative at cornell university Lecture 7 C++ Overview
Lecture 7 Lecture 7 So You Think You Know C++ Most of you are experienced Java programmers Both in 2110 and several upper-level courses If you saw C++, was likely in a systems course Java was based on
More informationWeek 7. Statically-typed OO languages: C++ Closer look at subtyping
C++ & Subtyping Week 7 Statically-typed OO languages: C++ Closer look at subtyping Why talk about C++? C++ is an OO extension of C Efficiency and flexibility from C OO program organization from Simula
More informationFunctions and Recursion
Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function
More informationTHE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.
Constructor and Destructor Member Functions Constructor: - Constructor function gets invoked automatically when an object of a class is constructed (declared). Destructor:- A destructor is a automatically
More informationInheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.
Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods
More informationInheritance and Polymorphism
Inheritance and Polymorphism 1 Inheritance extending a clock to an alarm clock deriving a class 2 Polymorphism virtual functions and polymorphism abstract classes MCS 360 Lecture 8 Introduction to Data
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract
More informationObject-Oriented Design (OOD) and C++
Chapter 2 Object-Oriented Design (OOD) and C++ At a Glance Instructor s Manual Table of Contents Chapter Overview Chapter Objectives Instructor Notes Quick Quizzes Discussion Questions Projects to Assign
More informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 12 Thomas Wies New York University Review Last lecture Modules Outline Classes Encapsulation and Inheritance Initialization and Finalization Dynamic
More informationRecharge (int, int, int); //constructor declared void disply();
Constructor and destructors in C++ Constructor Constructor is a special member function of the class which is invoked automatically when new object is created. The purpose of constructor is to initialize
More informationAssumptions. History
Assumptions A Brief Introduction to Java for C++ Programmers: Part 1 ENGI 5895: Software Design Faculty of Engineering & Applied Science Memorial University of Newfoundland You already know C++ You understand
More informationSRM 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