Object Oriented Programming COP3330 / CGS5409

Size: px
Start display at page:

Download "Object Oriented Programming COP3330 / CGS5409"

Transcription

1 Object Oriented Programming COP3330 / CGS5409

2 Classes & Objects DDU Design Constructors Member Functions & Data Friends and member functions Const modifier Destructors

3 Object -- an encapsulation of data along with functions that act upon that data. An object consists of: Name -- the variable name we give it Member data -- the data that describes the object Member functions -- behavior aspects of the object (functions related to the object itself)

4 Class -- a blueprint for objects. They are user-defined types that describes what a certain type of object will look like. Class description consists of: Declaration Definition. Usually these pieces are split into separate files.

5 An object is a single instance of a class. Many objects can be created from the same class type.

6 General outline for OOP: Declare Define Use

7 Declare - A declaration gives an interface: A variable declaration gives the type. A function declaration tells how to use it, without bothering with how it works. A class declaration shows what an object will look like and what its available functions are.

8 Define - A definition usually consists of the implementation details. A function definition is the code that makes a function work (the function body). A class definition consists definitions of its members.

9 Use - The use of an item, through its interface. The user of an executable program uses the graphic interface, keyboard, and mouse. The user of a function is a programmer, who makes calls to the function (without needing to know the implementation details). The user of a class is also a programmer, who uses the class by creating objects and calling the available functions for those objects.

10 The concept of interface is a very important one in object-oriented programming. The interface is what the user sees. (often leave the implementation details hidden) Goal: clear interface for the user (not necessarily the end user of a program -- could be a programmer, i.e. the user of a class).

11 We can declare members of a class to be public or private. public - can be accessed from inside or outside of the object. private - can only be used by the object itself.

12 What should be public? Kept private? No set rules on what belongs where Standard practices: Protect member data of a class by making it private Functions internal to program (will not ever be called by a class user) should also be private

13 Reasons for data hiding: Makes interface simpler for user. Principle of least privilege (need-to-know) More secure. Less chance for misuse (accidental or malicious). Class implementation easy to change without affecting other modules that use it.

14 class <classname> { public: (public member data and functions go here) private: (private member data and functions go here) };

15 // declaration of a class of Circle objects class Circle { public: void SetCenter(double x, double y); void SetRadius(double r); void Draw(); double AreaOf(); private: double radius; double center_x; double center_y; };

16 // declaration for class of TimeType objects class TimeType { public: void Set(int, int, int); // set the time void Increment(); // increment the timer void Display(); // output the time // accessor functions int GetHours(); int GetMinutes(); int GetSeconds(); private: int hours; int minutes; int seconds; };

17 A constructor is a special member function of a class whose purpose is usually to initialize the members of an object. A constructor is easy to recognize: It has the same name as the class It has no return type

18 // declaration of a class of Circle objects class Circle { public: Circle(); // this is a CONSTRUCTOR Circle(double r); // also a CONSTRUCTOR void SetCenter(double x, double y); void SetRadius(double r); void Draw(); double AreaOf(); private: double radius; double center_x; double center_y; };

19 A constructor is a function, and you can define it to do anything you want. However, you do not explicitly call the constructor function. It is automatically called when you declare an object. Example: Look at the following declaration. Circles circ1; This declaration creates an object named circ1. This line of code also causes the Circles constructor function to be run for the circ1 object.

20 This fraction example contains the two following constructors: Fraction(); // default constructor Fraction(int n, int d = 1); // constructor with parameters The term default constructor will always refer to a constructor with no parameters. When we declared objects in the simple fraction example, its default constructor was used because no parameters were passed. Fraction f1, f2; // f1 and f2 are now Fraction objects

21 To utilize a constructor with parameters, we can pass arguments in when the object is declared. Examples: Fraction f1(2,3); // passes 2 and 3 as parameters int x = 4, y = 8; Fraction f2(x,y); // passes values stored in x and y Notice, also, that this constructor has a default value on the second parameter, which makes it an optional parameter. If only one argument is passed in, the second parameter takes the default value, 1. Fraction f3(6); // initializes a fraction to 6/1

22 Member functions have CLASS scope Member functions have full access to all public AND private data & functions. PRIVATE DATA DOES NOT NEED TO BE PASSED TO FUNCTION!

23 // circle.h class Circle { public: bool setradius(int r); bool setradius2(int radius); int getradius(); private: int radius; }

24 // circle.h class Circle { public: bool setradius(int r); // parameter required since user supplied value must be input bool setradius2(int radius); int getradius(); private: int radius; }

25 // circle.h class Circle { public: bool setradius(int r); bool setradius2(int radius); // radius is a local variable for setradius2() and NOT the class member variable radius!!! Declaration of such a parameter over shadows the private radius, so we have to use this->radius to access the class radius now int getradius(); private: int radius; }

26 // circle.h class Circle { public: bool setradius(int r); bool setradius2(int radius); int getradius(); // No parameters necessary! Function has full access to private variable radius private: int radius; }

27 Suppose we want to compare two Fraction objects: Fraction f1(1,2); Fraction f2(2,4); if ( Equals(f1, f2) ) // compare two objects cout << "The fractions are equal";

28 Equivalently, we can define the prototype: bool Equals(Fraction x, Fraction y); Important notes: Function takes TWO Fraction objects as parameters Therefore, CANNOT be a member function!

29 bool Equals(Fraction x, Fraction y) { if (x.getnumerator() * y.getdenominator() == y.getnumerator() * x.getdenominator() ) return true; else return false; } What s wrong with this implementation?

30 Problem: Multiple internal calls to functions GetNumerator() and GetDenominator() Not the most efficient implementation!

31 bool Equals(Fraction x, Fraction y) { if (x.numerator * y.denominator == y.numerator * x.denominator ) return true; else return false; } No access to other objects' private data NOT A LEGAL CALL!

32 Grant full access to an outside entity All member functions and variables, even those declared as private To grant friend status, declaration of the "friend" is made inside the class definition block, with the keyword friend in front of it

33 class Fraction { friend bool Equals(Fraction x, Fraction y); friend Fraction Add(Fraction x, Fraction y); public: Fraction(); Fraction(int n, int d=1); void Input(); void Show(); int GetNumerator(); int GetDenominator(); bool SetValue(int n, int d); double Evaluate(); private: int numerator; int denominator; };

34 #include <iostream> #include "frac.h" using namespace std; // friend functions bool Equals(Fraction x, Fraction y) { return (x.numerator * y.denominator == y.numerator * x.denominator); } Fraction Add(Fraction x, Fraction y) { int num = x.numerator*y.denominator + y.numerator*x.denominator; int denom = x.denominator * y.denominator; Fraction answer(num, denom); return answer; } // member functions Fraction::Fraction() { numerator = 0; denominator = 1; } Fraction::Fraction(int n, int d) { if (SetValue(n,d) == false) SetValue(0,1); }

35 Another option is to use a member One of the objects must be the calling object Example: The Equals() function could have been set up as a member function, which would mean this kind of call: if ( f1.equals(f2) ) cout << "The fractions are equal";

36 This is a member function for the calling object. The other object is passed as a parameter. This would be the corresponding definition: bool Fraction::Equals(Fraction f) { if (numerator * f.denominator == f.numerator * denominator ) return true; else return false; }

37 Different programmers may have different preferences. Here's a comparison of the calls, side-by-side: f3 = f1.add(f2); // call to member version f3 = Add(f1, f2); // call non-member version Also note that the member function version is not necessarily equivalent to the friend function: Fraction Add(Fraction f); friend Fraction Add(Fraction f1, Fraction f2);

38 Recall how some of the built-in types allow automatic type conversions, like this: int x = 5; double y = 4.5, z = 1.2; y = x; // legal, via automatic conversion z = x + y; // legal, using automatic // conversion

39 Automatic type conversions can also be set up for classes, via a conversion constructor A conversion constructor is a constructor with one parameter By default, the compiler will use such a constructor to enact automatic type conversions from the parameter type to the class type. Example: Fraction(int n); // can be used to convert int to // Fraction

40 Constructors can be invoked explicitly to create Fraction objects. Treat the constructor call as if it is returning an object of the constructed type. The conversion constructor will be invoked automatically when type conversion is needed: Fraction f1, f2; // create fraction objects f1 = Fraction(4); // explicit call to constructor. //Fraction 4 created and assigned to f1 f2 = 10; // implicit call to conversion constructor // equivalent to: f2 = Fraction(10); f1 = Add(f2, 5); // uses conversion constructor

41 Const can be used in a variety of places. And everywhere it is applied in code, it: Expresses an intent on the part of the programmer, which the compiler enforces (i.e. something is not allowed to change, within some scope) Expresses the intent more clearly to a user (in this case, another portion of code -- i.e. maybe another programmer)

42 Pass-by-value vs. Pass-by-reference works the same on objects as it does with built-in types. If an object is passed by value, a copy is made of the object. If an object is passed by reference (without const), no copy is made Objects can be passed by const reference, as well. This way, no copy is made (less overhead), but the object cannot be changed through the reference. Since objects are sometimes large, this is often desirable

43 This example used pass-by-value parameters: friend Fraction Add(Fraction f1, Fraction f2); We definitely don't want to change the original fractions that were sent in. But to save overhead, we could use const reference parameters: friend Fraction Add(const Fraction& f1, const Fraction& f2); Since the parameters are const, R-values can be sent in (just like with pass-by-value).

44 Another use of const is at the end of a member function prototype, like this: void Func(int x) const; // const member function This application of const means that the function may not change the calling object itself. This can only be done to member functions of a class. (not stand-alone functions). This means that the member function will not change the member data of that object. If we have an object y, and then this function is called, the object y will remain in the same state (before and after the function call): Yadda y; y.func(5); // object y // function will not change data of y

45 When using this feature, the word const must go on the declaration and on the definition (if the definition is separate) For good class design, it should be used whenever appropriate. This means on any member functions that should not alter the member data of the calling object: Constructors -- their job is to initialize the object (i.e. set the member data), so these would NOT be const functions Mutators -- usually Set functions. Their job is to change member data, so these would also NOT be const Accessors -- a pure accessor function's job is to retrieve data from inside the class. These would typically be const member functions Functions for printing -- Show() or Display() functions would be good candidates for const, if their only purpose was to print existing data

46 Declaring primitive type variables as const is easy. Remember that they must be initialized on the same line: const int SIZE = 10; const double PI = ;

47 Objects can also be declared as const. The constructor will always run to initialize the object, but after that, the object's state (i.e. internal data) cannot be changed const Fraction ZERO; // this fraction is fixed const Fraction FIXED(3,4); // this fraction is // fixed at 3/4 To ensure that a const object cannot be changed, the compiler enforced the following rule: A const object may only call const member functions

48 So, using the Fraction class example with const member functions, the following calls are legal: FIXED.Show(); // calling const functions cout << FIXED.Evaluate(); int n = ZERO.GetNumerator(); int d = ZERO.GetDenominator(); The following calls would be illegal and would cause compiler errors: FIXED.SetValue(5,7); ZERO.Input();

49 Member data of a class can also be declared const. This is a little tricky, because of certain syntax rules. Remember, when a variable is declared with const in a normal block of code, it must be initialized on the same line: const int SIZE = 10;

50 However, it is NOT legal to initialize the member data variables on their declaration lines in a class definition block: class Thing { public: Thing(); // intialize member data here // functions private: int x; // just declare here int y = 0; // this would be ILLEGAL! cannot // initialize here const int Z = 10; // would also be ILLEGAL }

51 But a const declaration cannot be split up into a regular code block. This attempt at a constructor definition would also NOT work, if Z were const: Thing::Thing() { x = 0; y = 0; Z = 10; }

52 Solution: When we have lines like this, which involve declaring and initializing in one step and cannot be split up in normal code, we handle it with a special section of a function called the initialization list. Format: returntype functionname(parameterlist) : initialiation_list { // function body }

53 Const member initialization example Thing::Thing() : LIMIT(10) // initialization //of const member { height = 0; weight = 0; cout << SIZE; }

54 In addition to the special Constructor function, classes also have a special function called a destructor. The destructor looks like the default constructor (constructor with no parameters), but with a ~ in front. Destructors cannot have parameters, so there can only be one destructor for a class. Example: ~Fraction();

55 Like the constructor, this function is called automatically (not explicitly) A constructor is called automatically when an object is created. A destructor is called automatically right before an object is deallocated by the system (usually when it goes out of scope).

56 The destructor's typical job is to do any clean-up tasks (usually involving memory allocation) that are needed, before an object is deallocated. However, like a constructor, a destructor is a function and can do other things, if desired.

57

Protection Levels and Constructors The 'const' Keyword

Protection Levels and Constructors The 'const' Keyword Protection Levels and Constructors The 'const' Keyword Review: const Keyword Generally, the keyword const is applied to an identifier (variable) by a programmer to express an intent that the identifier

More information

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay Classes - 2 Data Processing Course, I. Hrivnacova, IPN Orsay OOP, Classes Reminder Requirements for a Class Class Development Constructor Access Control Modifiers Getters, Setters Keyword this const Member

More information

Object Oriented Modeling

Object Oriented Modeling Object Oriented Modeling Object oriented modeling is a method that models the characteristics of real or abstract objects from application domain using classes and objects. Objects Software objects are

More information

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

Abstract 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 information

CS 247: Software Engineering Principles. ADT Design

CS 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 information

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. Chapter 9 Objects and Classes 1 Objectives Classes & Objects ( 9.2). UML ( 9.2). Constructors ( 9.3). How to declare a class & create an object ( 9.4). Separate a class declaration from a class implementation

More information

Classes and Objects. CGS 3416 Spring 2018

Classes and Objects. CGS 3416 Spring 2018 Classes and Objects CGS 3416 Spring 2018 Classes and Objects An object is an encapsulation of data along with functions that act upon that data. It attempts to mirror the real world, where objects have

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

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

Lecture 7. Log into Linux New documents posted to course webpage

Lecture 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 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

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

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

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

Object-Oriented Programming Concepts

Object-Oriented Programming Concepts Object-Oriented Programming Concepts Real world objects include things like your car, TV etc. These objects share two characteristics: they all have state and they all have behavior. Software objects are

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

ADTs & Classes. An introduction

ADTs & Classes. An introduction ADTs & Classes An introduction Quick review of OOP Object: combination of: data structures (describe object attributes) functions (describe object behaviors) Class: C++ mechanism used to represent an object

More information

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved Chapter 8 Operator Overloading, Friends, and References Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives Basic Operator Overloading Unary operators As member functions Friends

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

An Introduction to C++

An Introduction to C++ An Introduction to C++ Introduction to C++ C++ classes C++ class details To create a complex type in C In the.h file Define structs to store data Declare function prototypes The.h file serves as the interface

More information

Abstract Data Types. Development and Implementation. Well-defined representations that allow objects to be created and used in an intuitive manner

Abstract Data Types. Development and Implementation. Well-defined representations that allow objects to be created and used in an intuitive manner Abstract Data Types Development and Implementation JPC and JWD 2002 McGraw-Hill, Inc. Our Goal Well-defined representations that allow objects to be created and used in an intuitive manner User should

More information

CPSC 427a: Object-Oriented Programming

CPSC 427a: Object-Oriented Programming CPSC 427a: Object-Oriented Programming Michael J. Fischer Lecture 5 September 15, 2011 CPSC 427a, Lecture 5 1/35 Functions and Methods Parameters Choosing Parameter Types The Implicit Argument Simple Variables

More information

Implementing an ADT with a Class

Implementing an ADT with a Class Implementing an ADT with a Class the header file contains the class definition the source code file normally contains the class s method definitions when using Visual C++ 2012, the source code and the

More information

Initializing and Finalizing Objects

Initializing and Finalizing Objects 4 Initializing and Finalizing Objects 147 Content Initializing and Finalizing Objects 4 Constructors Default Constructor Copy Constructor Destructor 148 Initializing Objects: Constructors Initializing

More information

Data Structures and Other Objects Using C++

Data Structures and Other Objects Using C++ Inheritance Chapter 14 discuss Derived classes, Inheritance, and Polymorphism Inheritance Basics Inheritance Details Data Structures and Other Objects Using C++ Polymorphism Virtual Functions Inheritance

More information

Abstraction in Software Development

Abstraction in Software Development Abstract Data Types Programmer-created data types that specify values that can be stored (type of data) operations that can be done on the values The user of an abstract data type (ADT) does not need to

More information

Lecture 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) 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 information

COMP322 - Introduction to C++ Lecture 07 - Introduction to C++ classes

COMP322 - Introduction to C++ Lecture 07 - Introduction to C++ classes COMP322 - Introduction to C++ Lecture 07 - Introduction to C++ classes Dan Pomerantz School of Computer Science 27 February 2012 Why classes? A class can be thought of as an abstract data type, from which

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

Determine a word is a palindrome? bool ispalindrome(string word, int front, int back) { Search if a number is in an array

Determine a word is a palindrome? bool ispalindrome(string word, int front, int back) { Search if a number is in an array Recursion review Thinking recursion: if I know the solution of the problem of size N-, can I use that to solve the problem of size N. Writing recursive routines: Decide the prototype Can formulate both

More information

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

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING THROUGH C++ Practical: OOPS THROUGH C++ Subject Code: 1618407 PROGRAM NO.1 Programming exercise on executing a Basic C++

More information

10.1 Class Definition. User-Defined Classes. Counter.h. User Defined Types. Counter.h. Counter.h. int, float, char are built into C+ Declare and use

10.1 Class Definition. User-Defined Classes. Counter.h. User Defined Types. Counter.h. Counter.h. int, float, char are built into C+ Declare and use 10.1 Class Definition User-Defined Classes Chapter 10 int, float, char are built into C+ Declare and use int x = 5; Create user defined data types+ Extensive use throughout remainder of course Counter

More information

SFU CMPT Topic: Classes

SFU CMPT Topic: Classes SFU CMPT-212 2008-1 1 Topic: Classes SFU CMPT-212 2008-1 Topic: Classes Ján Maňuch E-mail: jmanuch@sfu.ca Friday 15 th February, 2008 SFU CMPT-212 2008-1 2 Topic: Classes Encapsulation Using global variables

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

Fundamental Concepts and Definitions

Fundamental Concepts and Definitions Fundamental Concepts and Definitions Identifier / Symbol / Name These terms are synonymous: they refer to the name given to a programming component. Classes, variables, functions, and methods are the most

More information

Object Oriented Programming in C#

Object Oriented Programming in C# Introduction to Object Oriented Programming in C# Class and Object 1 You will be able to: Objectives 1. Write a simple class definition in C#. 2. Control access to the methods and data in a class. 3. Create

More information

Paytm 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 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 information

1 of 8 3/28/2010 8:03 AM C++ Special Topics Home Class Info Links Lectures Newsgroup Assignmen This is a short review of special topics in C++ especially helpful for various assignments. These notes are

More information

Fundamentals of Programming. Lecture 19 Hamed Rasifard

Fundamentals of Programming. Lecture 19 Hamed Rasifard Fundamentals of Programming Lecture 19 Hamed Rasifard 1 Outline C++ Object-Oriented Programming Class 2 C++ C++ began as an expanded version of C. C++ improves on many of C s features and provides object-oriented-programming

More information

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer September 26, 2016 OOPP / C++ Lecture 4... 1/33 Global vs. Class Static Parameters Move Semantics OOPP / C++ Lecture 4... 2/33 Global Functions

More information

System Design and Programming II

System Design and Programming II System Design and Programming II CSCI 194 Section 01 CRN: 10968 Fall 2017 David L. Sylvester, Sr., Assistant Professor Chapter 13 Introduction to Classes Procedural and Object-Oriented Programming Procedural

More information

Defining Classes and Methods

Defining Classes and Methods Defining Classes and Methods Chapter 5 Modified by James O Reilly Class and Method Definitions OOP- Object Oriented Programming Big Ideas: Group data and related functions (methods) into Objects (Encapsulation)

More information

Friends and Overloaded Operators

Friends and Overloaded Operators Friend Function Friends and Overloaded Operators Class operations are typically implemented as member functions Some operations are better implemented as ordinary (nonmember) functions CSC 330 OO Software

More information

Module 7 b. -Namespaces -Exceptions handling

Module 7 b. -Namespaces -Exceptions handling Module 7 b -Namespaces -Exceptions handling C++ Namespace Often, a solution to a problem will have groups of related classes and other declarations, such as functions, types, and constants. C++provides

More information

Friends and Overloaded Operators

Friends and Overloaded Operators Friends and Overloaded Operators Friend Function Class operations are typically implemented as member functions Some operations are better implemented as ordinary (nonmember) functions CSC 330 OO Software

More information

Object-Oriented Programming

Object-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 information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

Circle all of the following which would make sense as the function prototype.

Circle all of the following which would make sense as the function prototype. Student ID: Lab Section: This test is closed book, closed notes. Points for each question are shown inside [ ] brackets at the beginning of each question. You should assume that, for all quoted program

More information

EL2310 Scientific Programming

EL2310 Scientific Programming (pronobis@kth.se) Overview Overview Wrap Up Introduction to Object Oriented Paradigm More on and Members Operator Overloading Last time Intro to C++ Differences between C and C++ Intro to OOP Today Object

More information

Object Oriented Programming COP3330 / CGS5409

Object Oriented Programming COP3330 / CGS5409 Object Oriented Programming COP3330 / CGS5409 C++ Automatics Copy constructor () Assignment operator = Shallow copy vs. Deep copy DMA Review c-strings vs. concept of string class Constructor Destructor

More information

Constructor - example

Constructor - example Constructors A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is same as the class name. The constructor is invoked whenever

More information

Lecture 13: more class, C++ memory management

Lecture 13: more class, C++ memory management CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 13:

More information

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3 Programming in C main Level 2 Level 2 Level 2 Level 3 Level 3 1 Programmer-Defined Functions Modularize with building blocks of programs Divide and Conquer Construct a program from smaller pieces or components

More information

Ch 8. Operator Overloading, Friends, and References

Ch 8. Operator Overloading, Friends, and References 2014-1 Ch 8. Operator Overloading, Friends, and References May 28, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel

More information

Lecture #1. Introduction to Classes and Objects

Lecture #1. Introduction to Classes and Objects Lecture #1 Introduction to Classes and Objects Topics 1. Abstract Data Types 2. Object-Oriented Programming 3. Introduction to Classes 4. Introduction to Objects 5. Defining Member Functions 6. Constructors

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

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University C++ Review CptS 223 Advanced Data Structures Larry Holder School of Electrical Engineering and Computer Science Washington State University 1 Purpose of Review Review some basic C++ Familiarize us with

More information

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

Recharge (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 information

Review. What is const member data? By what mechanism is const enforced? How do we initialize it? How do we initialize it?

Review. What is const member data? By what mechanism is const enforced? How do we initialize it? How do we initialize it? Review Describe pass-by-value and pass-by-reference Why do we use pass-by-reference? What does the term calling object refer to? What is a const member function? What is a const object? How do we initialize

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

Classes. C++ Object Oriented Programming Pei-yih Ting NTOU CS

Classes. C++ Object Oriented Programming Pei-yih Ting NTOU CS Classes C++ Object Oriented Programming Pei-yih Ting NTOU CS 1 Encapsulation Access Specifiers Default Access Private Data Public vs. Private Functions Object State Scope Inline Member Functions Constant

More information

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil More About Classes Gaddis Ch. 14, 13.3 CS 2308 :: Fall 2015 Molly O'Neil Pointers to Objects Just like pointers to structures, we can define pointers to objects Time t1(12, 20, true); Time *tptr; tptr

More information

Copying Data. Contents. Steven J. Zeil. November 13, Destructors 2

Copying Data. Contents. Steven J. Zeil. November 13, Destructors 2 Steven J. Zeil November 13, 2013 Contents 1 Destructors 2 2 Copy Constructors 11 2.1 Where Do We Use a Copy Constructor? 12 2.2 Compiler-Generated Copy Constructors............................................

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

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. Assistant Lecture Omar Al Khayat 2 nd Year

Object 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 information

7.1 Optional Parameters

7.1 Optional Parameters Chapter 7: C++ Bells and Whistles A number of C++ features are introduced in this chapter: default parameters, const class members, and operator extensions. 7.1 Optional Parameters Purpose and Rules. Default

More information

Object-Oriented Programming, Iouliia Skliarova

Object-Oriented Programming, Iouliia Skliarova Object-Oriented Programming, Iouliia Skliarova CBook a = CBook("C++", 2014); CBook b = CBook("Physics", 1960); a.display(); b.display(); void CBook::Display() cout

More information

Encapsulation in C++

Encapsulation in C++ pm_jat@daiict.ac.in In abstract sense, it is all about information hiding Informally, you can call it as packaging of data and function together in a single entity called class such that you get implementation

More information

Class 15. Object-Oriented Development from Structs to Classes. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Class 15. Object-Oriented Development from Structs to Classes. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski) Class 15 Object-Oriented Development from Structs to Classes The difference between structs and classes A class in C++ is basically the same thing as a struct The following are exactly equivalent struct

More information

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370 Part VII Object-Oriented Programming Philip Blakely (LSC) C++ Introduction 194 / 370 OOP Outline 24 Object-Oriented Programming 25 Member functions 26 Constructors 27 Destructors 28 More constructors Philip

More information

A <Basic> C++ Course

A <Basic> C++ Course A C++ Course 5 Constructors / destructors operator overloading Julien DeAntoni adapted from Jean-Paul Rigault courses 1 2 This Week A little reminder Constructor / destructor 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

A <Basic> C++ Course

A <Basic> C++ Course A C++ Course 5 Constructors / destructors operator overloading Julien Deantoni adapted from Jean-Paul Rigault courses This Week A little reminder Constructor / destructor Operator overloading Programmation

More information

Module Operator Overloading and Type Conversion. Table of Contents

Module Operator Overloading and Type Conversion. Table of Contents 1 Module - 33 Operator Overloading and Type Conversion Table of Contents 1. Introduction 2. Operator Overloading 3. this pointer 4. Overloading Unary Operators 5. Overloading Binary Operators 6. Overloading

More information

Next week s homework. Classes: Member functions. Member functions: Methods. Objects : Reminder. Objects : Reminder 3/6/2017

Next week s homework. Classes: Member functions. Member functions: Methods. Objects : Reminder. Objects : Reminder 3/6/2017 Next week s homework Classes: Methods, Constructors, Destructors and Assignment Read Chapter 7 Your next quiz will be on Chapter 7 of the textbook For : COP 3330. Object oriented Programming (Using C++)

More information

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction CS106L Spring 2009 Handout #21 May 12, 2009 static Introduction Most of the time, you'll design classes so that any two instances of that class are independent. That is, if you have two objects one and

More information

C++ Classes, Constructor & Object Oriented Programming

C++ Classes, Constructor & Object Oriented Programming C++ Classes, Constructor & Object Oriented Programming Object Oriented Programming Programmer thinks about and defines the attributes and behavior of objects. Often the objects are modeled after real-world

More information

Object Oriented Programming(OOP).

Object Oriented Programming(OOP). Object Oriented Programming(OOP). OOP terminology: Class : A class is a way to bind data and its associated function together. It allows the data to be hidden. class Crectangle Data members length; breadth;

More information

What will this print?

What will this print? class UselessObject{ What will this print? int evennumber; int oddnumber; public int getsum(){ int evennumber = 5; return evennumber + oddnumber; public static void main(string[] args){ UselessObject a

More information

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE? 1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity

More information

Comments are almost like C++

Comments are almost like C++ UMBC CMSC 331 Java Comments are almost like C++ The javadoc program generates HTML API documentation from the javadoc style comments in your code. /* This kind of comment can span multiple lines */ //

More information

PIC 10A. Lecture 17: Classes III, overloading

PIC 10A. Lecture 17: Classes III, overloading PIC 10A Lecture 17: Classes III, overloading Function overloading Having multiple constructors with same name is example of something called function overloading. You are allowed to have functions with

More information

Defining Classes and Methods. Objectives. Objectives 6/27/2014. Chapter 5

Defining Classes and Methods. Objectives. Objectives 6/27/2014. Chapter 5 Defining Classes and Methods Chapter 5 Objectives Describe concepts of class, class object Create class objects Define a Java class, its methods Describe use of parameters in a method Use modifiers public,

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

More class design with C++ Starting Savitch Chap. 11

More class design with C++ Starting Savitch Chap. 11 More class design with C++ Starting Savitch Chap. 11 Member or non-member function? l Class operations are typically implemented as member functions Declared inside class definition Can directly access

More information

Function Overloading

Function 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 information

PIC 10A. Lecture 15: User Defined Classes

PIC 10A. Lecture 15: User Defined Classes PIC 10A Lecture 15: User Defined Classes Intro to classes We have already had some practice with classes. Employee Time Point Line Recall that a class is like a souped up variable that can store data,

More information

Object Reference and Memory Allocation. Questions:

Object Reference and Memory Allocation. Questions: Object Reference and Memory Allocation Questions: 1 1. What is the difference between the following declarations? const T* p; T* const p = new T(..constructor args..); 2 2. Is the following C++ syntax

More information

Chapter 15: Object Oriented Programming

Chapter 15: Object Oriented Programming Chapter 15: Object Oriented Programming Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey How do Software Developers use OOP? Defining classes to create objects UML diagrams to

More information

Structures. Lecture 15 COP 3014 Spring April 16, 2018

Structures. Lecture 15 COP 3014 Spring April 16, 2018 Structures Lecture 15 COP 3014 Spring 2018 April 16, 2018 Motivation We have plenty of simple types for storing single items like numbers, characters. But is this really enough for storing more complex

More information

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

Review. Modules. CS 151 Review #6. Sample Program 6.1a: Review Modules A key element of structured (well organized and documented) programs is their modularity: the breaking of code into small units. These units, or modules, that do not return a value are called

More information

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation COMP-202 Unit 8: Defining Your Own Classes CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation Defining Our Own Classes (1) So far, we have been creating

More information

Chapter 6 Structures and Classes. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Chapter 6 Structures and Classes. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo Chapter 6 Structures and Classes 1 Learning Objectives Structures Structure types Structures as function arguments Initializing structures Classes Defining, member functions Public and private members

More information

Classes and Objects. Class scope: - private members are only accessible by the class methods.

Classes and Objects. Class scope: - private members are only accessible by the class methods. Class Declaration Classes and Objects class class-tag //data members & function members ; Information hiding in C++: Private Used to hide class member data and methods (implementation details). Public

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Objectives To review the concepts and terminology of object-oriented programming To discuss some features of objectoriented design 1-2 Review: Objects In Java and other Object-Oriented

More information

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018 Pointer Basics Lecture 13 COP 3014 Spring 2018 March 28, 2018 What is a Pointer? A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory

More information

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Classes Chapter 4 Classes and Objects Data Hiding and Encapsulation Function in a Class Using Objects Static Class members Classes Class represents a group of Similar objects A class is a way to bind the

More information