C++ Structures: Classes In C++, the concept of structure has been generalized in an object-oriented sense: –classes are types representing groups of similar.

Slides:



Advertisements
Similar presentations
Lesson 13 Introduction to Classes CS1 Lesson Introduction to Classes1.
Advertisements

Starting Out with C++: Early Objects 5th Edition
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
1 Review: Two Programming Paradigms Structural (Procedural) Object-Oriented PROGRAM PROGRAM FUNCTION OBJECT Operations Data OBJECT Operations Data OBJECT.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
Pointer Data Type and Pointer Variables
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Chapter 9 Defining New Types. Objectives Explore the use of member functions when creating a struct. Introduce some of the concepts behind object-oriented.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Procedural and Object-Oriented Programming 13.1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Learners Support Publications Classes and Objects.
Programming Languages by Ravi Sethi Chapter 6: Groupings of Data and Operations.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 4 – August 30, 2001.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
CSC241 Object-Oriented Programming (OOP) Lecture No. 6.
CSC241 Object-Oriented Programming (OOP) Lecture No. 4.
Structured Data and Classes Chapter 7. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
1 CSC241: Object Oriented Programming Lecture No 02.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
CSC241 Object-Oriented Programming (OOP) Lecture No. 5.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Structs and Classes Structs A struct can be used to define a data structure type as follows: struct Complex { double real, imag;} // specifying a Complex.
Classes - Part II (revisited) n Constant objects and member functions n Definition Form of Member Functions n friend functions and friend classes n Constructors.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Introduction to Classes in C++ Instructor - Andrew S. O’Fallon CptS 122 Washington State University.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
1 Classes struct Public and Private Parts of a struct Class Scope of a Class Overloading Member Functions Class in a Class Static Members of Classes this.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Review: Two Programming Paradigms
Introduction to Classes
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
CS212: Object Oriented Analysis and Design
Introduction to Classes
Classes and Objects.
C++ Constructor Insanity CSE 333 Summer 2018
Java Programming Language
CS410 – Software Engineering Lecture #5: C++ Basics III
C++ Structs and Classes
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

C++ Structures: Classes In C++, the concept of structure has been generalized in an object-oriented sense: –classes are types representing groups of similar instances –each instance has certain fields that define it (instance variables) –instances also have functions that can be applied to them (represented as function fields) -- called methods –the programmer can limit access to parts of the class (to only those functions that need to know about the internals) Readings: , , 7.8,

Outline Classes in C++ access modifiers: private, public, protected struct versus class class methods defined defined separately inlining static instance variables accessors mutators managers default ctor, dtor, copy ctor, other ctors

A Motivating Example You declare a simple structure: struct Robot { float locX; float locY; float facing; }; Robot r1; What if you never want locX or locY to be negative? Someone unaware of your restriction could set: r1.locX = -5; and you have a problem!

General Class Definition in C++ class ClassName { access_modifier1: field11_definition; field12_definition; … access_modifer2: field21_definition; field22_definition; … }; ClassName is a new type (just as if declared as struct with typedef in C) Possible access modifiers: public private protected Fields following a modifier are of that access until the next modifier is indicated Fields can be variables (as in C structures) or functions

A Simple Class class Robot { public: float getX() { return locX; } float getY() { return locY; } float getFacing() { return facing; } void setFacing(float f) { facing = f; } void setLocation(float x, float y); private: float locX; float locY; float facing; };

private Access Modifier Fields marked as private can only be accessed by functions that are part of that class In the Robot class, locX, locY, and facing are private float fields, these fields can only be accessed by functions that are in class Robot (getX, getY, getFacing, setFacing, setLocation) Example: void useRobot() { Robot r1; r1.locX = -5; // Error

public Access Modifier Fields marked as public can be accessed by anyone In the Robot class, the methods getX, getY, etc. are public –these functions can be called by anyone Example: void useRobot() { Robot r1; r1.setLocation(-5,-5); // Legal to call

struct versus class In C++ struct and class can be used interchangeably to create a class with one exception What if we forget to put an access modifier before the first field? struct Robot { OR class Robot { float locX; float locX; In a class, until an access modifer is supplied, the fields are assumed to be private In a struct, the fields are assumed to be public

What about protected ? C++ allows users to create classes based on other classes: –a FordCar class based on a general Car class –idea: the general Car class has fields (variables and functions that describe all cars) –the FordCar class then uses the fields from the general Car class and adds fields specific to FordCars –done with inheritance –public fields are inherited (as public) –private fields are not inherited –protected fields are like private, but can be inherited

Class Methods Functions associated with a class are declared in one of two ways: ReturnType FuncName(params) { code } function is both declared and defined (code provided) ReturnType FuncName(params); function is merely declared, we must still define the body of the function separately To call a method we use the. form: classinstance.FuncName(args); FuncName is a field just like any other field in the structured variable classinstance

Defined Methods class Robot { public: float getX() { return locX; } }; Robot r1; The function getX is defined as part of class Robot To call this method: cout << r1.getX() << endl; // prints r1’s locX Why define the method this way? –Implicitly inline

Inline Functions In an inline function, the C++ compiler does not make a function call, instead the code of the function is used in place of the function call (and appropriate argument substitutions made) Why? –Inline functions don’t have the overhead of other functions –Things like accessing/changing fields of a class instance should be fast –Including the definition of a function is an implicit request to make a function inline

Inline Requests Not all requests to make a function inline are honored –generally C++ examines the complexity of the function and the use of parameters in the function –should only request inline definition for short functions Can also explicitly request to make class methods and other functions inline (add inline keyword before return type in function declaration and definition)

Aside: A Global Inline Function Use inline before return type: inline char upcase(char ch) { if ((ch >= ‘a’) && (ch <= ‘z’)) return (ch + (‘A’ - ‘a’)); else return ch; } cin >> option; if (upcase(option) == ‘Y’)...

Defining Methods Separately For methods that are declared but not defined in the class we need to provide a separate definition To define the method, you define it as any other function, except that the name of the function is ClassName::FuncName :: is the scope resolution operator, it allows us to refer to parts of a class or structure

A Simple Class class Robot { public: void setLocation(float x, float y); private: float locX; float locY; float facing; }; void Robot::setLocation(float x, float y) { if ((x < 0.0) || (y < 0.0)) cout << “Illegal location!!” << endl; else { locX = x; locY = y; }

Explicitly Requesting Inline class Robot { public: inline void setLocation(float x, float y); }; inline void Robot::setLocation(float x, float y) { if ((x < 0.0) || (y < 0.0)) cout << “Illegal location!!” << endl; else { locX = x; locY = y; }

Referring to Class Fields void Robot::setLocation(float x, float y) { if ((x < 0.0) || (y < 0.0)) cout << “Illegal location!!” << endl; else { locX = x; locY = y; } What are locX and locY in setLocation?? –Since a class function is always called on a class instance, locX, locY are those fields of that instance –Example: Robot r1; Robot r2; r1.setLocation(5,5); // locX is from r1 r2.setLocation(3,3); // locY is from r2

Types of Class Methods Generally we group class methods into three broad categories: accessors - allow us to access the fields of a class instance (examples: getX, getY, getFacing), accessors do not change the fields of a class instance mutators - allow us to change the fields of a class instance (examples: setLocation, setFacing), mutators do change the fields of a class instance manager functions - specific functions (constructors, destructors) that deal with initializing and destroying class instances (more in a bit)

Accessors and Mutators Why do we bother with accessors and mutators? –Why provide getX()?? Why not just make the locX field publicly available? –By restricting access using accessors and mutators we make it possible to change the underlying details regarding a class without changing how people who use that class interact with the class –Example: what if I changed the robot representation so that we no longer store locX and locY, instead we use polar coordinates (distance and angle to location)? If locX is a publicly available field that people have been accessing it, removing it will affect their code If users interact using only accessors and mutators then we can change things without affecting their code

Rewritten Robot Class class Robot { public: float getX() { return dist * cos(ang); } float getY() { return dist * sin(ang); } void setLocation(float x, float y); private: float dist; float ang; }; void Robot::setLocation(float x, float y) { if ((x < 0.0) || (y < 0.0)) cout << “Illegal location!!” << endl; else { dist = sqrt(x * x + y * y); ang = atan2(y,x); }

Object-Oriented Idea Declare implementation-specific fields of class to be private Provide public accessor and mutator methods that allow other users to connect to the fields of the class –often provide an accessor and mutator for each instance variable that lets you get the current value of that variable and set the current value of that variable –to change implementation, make sure accessors and mutators still provide users what they expect

Static Instance Variables C++ classes may also contain, static instance fields -- a single field shared by all members of a class Often used when declaring class constants (since you generally only need one copy of a constant) To make a field static, add the static keyword in front of the field –can refer to the field like any other field (but remember, everybody shares one copy) –static variables are also considered to be global, you can refer to them without an instance –static fields can be initialized (unlike other fields)

Static Fields Example class Robot { public: static int numRobots = 0; static const float minX = 0.0; static const float maxX = 100.0; void initializeRobot() { numRobots++; } void setLocation(float x, float y); } void Robot::setLocation(float x, float y) { if ((x maxX)) … }

Static Fields as Global Variables One can examine public static fields of a class outside of that class using the form: ClassName::StaticFieldName Example: void main() { Robot r1, r2; r1.initializeRobot(); r2.initializeRobot(); cout << Robot::numRobots << “ robots.\n”;

The Need for Manager Functions To make the previous program work we have to explicitly call the routine initializeRobot, wouldn’t it be nice to have a routine that is automatically used to initialize an instance -- C++ does C++ provides for the definition of manager functions to deal with certain situations: constructors (ctor) - used to set up new instances default - called for a basic instance copy - called when a copy of an instance is made (assignment) other - for other construction situations destructors (dtor) - used when an instance is removed

When Managers Called void main() { Robot r1; // default ctor (on r1) Robot r2; // default ctor (on r2) Robot* r3ptr; r3ptr = new Robot; // default ctor on // Robot object r3ptr points to r2 = r1; // copy ctor delete r3ptr; // dtor } // dtor (on r1 and r2) when main ends

The Default Constructor (ctor) A default constructor has no arguments, it is called when a new instance is created –C++ provides a default ctor that initializes all fields to 0 To write your own, add following to your class: class MyClass { public: … MyClass() { // repeat class name, no code here // return type }

Example Default ctor class Robot { public: static int numRobots = 0; Robot() { numRobots++; locX = 0.0; locY = 0.0; facing = / 2; } private: float locX; float locY; float facing; }

Destructor (dtor) A destructor is normally not critical, but if your class allocates space on the heap, it is useful to deallocate that space before the object is destroyed –C++ provides a default dtor that does nothing –can only have one dtor To write your own, add following to your class: class MyClass { public: … ~MyClass() { code here }

Example dtor class Robot { public: char *robotName; Robot() { robotName = 0; } void setRobotName(char *name) { robotName = new char[strlen(name)+1]; strcpy(robotName,name); } ~Robot() { delete [] robotName; }

The Copy ctor A copy constructor is used when we need a special method for making a copy of an instance –example, if one instance has a pointer to heap-allocated space, important to allocate its own copy (otherwise, both point to the same thing) To write your own, add following to your class: class MyClass { public: … MyClass(const MyClass& obj) { code here }

Example Copy ctor class Robot { public: char *robotName; void setRobotName(char *name) { robotName = new char[strlen(name)+1]; strcpy(robotName,name); } Robot(const Robot& obj) { robotName = new char[strlen(obj.robotName)+1]; strcpy(robotName,obj.robotName); }

Other ctors It is often useful to provide constructors that allow the user to provide arguments in order to initialize arguments Form is similar to the copy ctor, except parameters are chosen by programmer: class MyClass { public; … MyClass(parameters) { code here }

Example ctor class Robot { public: Robot(float x, float y, float face) { locX = x; locY = y; facing = face; } calling: Robot r1(5.0,5.0,1.5); Robot r2(5.0,10.0,0.0); Robot* rptr; rptr = new Robot(10.0,5.0,-1.5);

A Combination ctor Can combine a ctor that requires arguments with the default ctor using default values: class Robot { public: Robot(float x = 0.0, float y = 0.0, float face = ) { locX = x; locY = y; facing = face; } calling: Robot r1; // ctor called with default args Robot r2(); // ctor called with default args Robot r3(5.0); // ctor called with x = 5.0 Robot r4(5.0,5.0; // ctor called with x,y = 5.0 …

Hiding the Default ctor Sometimes we want to make sure that the user gives initial values for some fields, and we don’t want them to use the default ctor To accomplish this we declare an appropriate ctor to be used in creating instances of the class in the public area, then we put the default ctor in the private area (where it cannot be called)

Example ctor class Robot { public: Robot(float x, float y, float face) { locX = x; locY = y; facing = face; } private: Robot() {} } calling: Robot r1(5.0,5.0,1.5); Robot r2; // ERROR, attempts to call default ctor