Plab 2003 Lecture 41 C++ - Classes. Plab 2003 Lecture 42 Motivating Example Goal: Graphics package Handle drawing of different shapes Maintain list of.

Slides:



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

The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Portability and Safety Mahdi Milani Fard Dec, 2006 Java.
Object Oriented Programming Chapter 7 Programming Languages by Ravi Sethi.
. Virtual Classes & Polymorphism. Example (revisited) u We want to implement a graphics system u We plan to have lists of shape. Each shape should be.
Polymorphism From now on we will use g++!. Example (revisited) Goal: Graphics package Handle drawing of different shapes Maintain list of shapes.
. Plab – Tirgul 6 Classes. Point.h class Point { public: Point(int x, int y); ~Point(); int getX() const; int getY() const; private: int m_x, m_y; };
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java Programming Chapter 3 More about classes. Why?  To make classes easier to find and to use  to avoid naming conflicts  to control access  programmers.
. Classes. Logistics Test next week – do not be late! Last name: א-ט - Raschel Hall (Silverman Building) י-ת - Feldman Hall.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
1 Review: Two Programming Paradigms Structural (Procedural) Object-Oriented PROGRAM PROGRAM FUNCTION OBJECT Operations Data OBJECT Operations Data OBJECT.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Peter Juszczyk CS 492/493 - ISGS. // Is this C# or Java? class TestApp { static void Main() { int counter = 0; counter++; } } The answer is C# - In C#
Programming Languages and Paradigms Object-Oriented Programming.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
CSE 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Object Oriented Programming Elhanan Borenstein Lecture #4.
Distributed Systems (236351) Tutorial 1 - Getting Started with Visual Studio C#.NET.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
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.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
1 CSC241: Object Oriented Programming Lecture No 02.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
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.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Object-Oriented Programming (OOP) What we did was: (Procedural Programming) a logical procedure that takes input data, processes it, and produces output.
Classes, Interfaces and Packages
Variations on Inheritance Object-Oriented Programming Spring
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Introduction of Object Oriented Programming.
Data Structures Lecture 4: Classes in C++ Azhar Maqsood NUST Institute of Information Technology (NIIT)
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
Modern Programming Tools And Techniques-I
Classes C++ representation of an object
Structs (C,C++) Already seen in tirgul.
Structs (C,C++).
7.1 What Is An Object Object-oriented program - Description or simulation of application Object-oriented programming is done by adopting or extending an.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
A First C++ Class – a Circle
Review: Two Programming Paradigms
classes and objects review
Introduction to Classes
Object Oriented Programming
Chapter 5 Classes.
Introduction to Classes
CS212: Object Oriented Analysis and Design
Week 6 Object-Oriented Programming (2): Polymorphism
Chapter 9 Objects and Classes
Classes and Objects.
Introduction to Classes and Objects
Classes C++ representation of an object
Final and Abstract Classes
Structs (C) Already seen in tirgul.
Lecture 8 Object Oriented Programming (OOP)
SPL – PS3 C++ Classes.
Presentation transcript:

Plab 2003 Lecture 41 C++ - Classes

Plab 2003 Lecture 42 Motivating Example Goal: Graphics package Handle drawing of different shapes Maintain list of shapes

Plab 2003 Lecture 43 Solution #1 struct Shape { enum { RECTANGLE, CIRCLE, TRIANGLE } type; doublex, y; doubleheight, width; }; void draw( Shape const* shape ) { switch( shape->type ) { case RECTANGLE: … case CIRCLE: …

Plab 2003 Lecture 44 Solution #1 - Discussion Pros: Simple, direct Cons: Adding new shapes requires changing all procedures that deal with shape. Require fat interface in order to support all kinds of shapes. No type checking. Unsafe!

Plab 2003 Lecture 45 Solution #2 Allow to implement shape specific code struct Shape { doublex, y; doubleheight, width; void(*draw)( Shape const* ); }; void draw( Shape const* shape ) { (*shape->draw)(shape); }

Plab 2003 Lecture 46 Solution #2 Pros: Extendable Drawing method of each shape encapsulated Efficient Cons: Require fat interface in order to support all kinds of shapes. Still no type checking. Unsafe!

Plab 2003 Lecture 47 Solution #3 – C++ classes C++ Language provides tools that support object oriented programming.

Plab 2003 Lecture 48 Simple Class Definition class Counter { public: //function prototypes Counter(); // Constructor void increment(); // A method int value() const; // Another method private: int m_count; };

Plab 2003 Lecture 49 Class Implementation Counter::Counter() { //fully qualified name m_count = 0; } void Counter::increment(){ m_count++; } int Counter::value(){ return m_count; }

Plab 2003 Lecture 410 Using the class int main() { Counter cnt; // default constructor! printf("Initial value = %d\n", cnt.value() ); cnt.increment(); printf("New value = %d\n", cnt.value() ); }

Plab 2003 Lecture 411 Class Basics: Access control Declare which parts of the class are accessible outside the class class Counter { public: //designate a section! … // accessible from outside private: //designate a section! … // private };

Plab 2003 Lecture 412 Example class Counter { public: Counter(); int value()const; void increment(); int m_flag; private: int m_counter; }; int main() { Counter c; // legal int x = c.value(); int y = c.m_flag; // illegal c.m_counter = 2.0; }

Plab 2003 Lecture 413 Class Basics: Constructors Initialize the class object upon construction class Counter { public: Counter(); //default constructor Counter( int c ); //2 Counter( int c, int f ); //3 }; … Counter a; // Calls default constructor Counter b(0); // Calls 2 Counter c( 1, 2); // Calls 3

Plab 2003 Lecture 414 Default arguments in constructors/functions In C++ Counter::Counter( int c = 0, int f = 1) { } Note that now Counter has a default constructor! Counter::Counter( int c = 0, int f) //illegal { }

Plab 2003 Lecture 415 Destructors Ensure propose “cleanup” when the object is destructed Use for freeing memory, notifying related objects. free resources. Files, Sockets…

Plab 2003 Lecture 416 Class Basics: Destructors class Counter { public: Counter(); ~Counter(); // destructor private: char* message; }; Counter::Counter(){ message = (char*)malloc(1000); } Counter::~Counter(){ free(message); } int main() { Counter a; if( … ) { Counter b; … } … }

Plab 2003 Lecture 417 Class – Memory Management Representation of data structure list. C++ implementation of data structure Data members of IntList are protected using appropriate access control. Usage is more natural … IntList L; L.pushFront(6) if( !L.isEmpty() ) x = L.popBack();

Plab 2003 Lecture 418 Class – Memory Management Cont Consider this code main() { IntList L; … } What is the difference? Compare to main() { IntList* L = (IntList*)malloc( sizeof(IntList)); … free(L) }

Plab 2003 Lecture 419 IntList* L = (IntList*)malloc(sizeof(IntList)); Does not call constructor! Internal data members are not initialized free(L); Does not call destructor! Internal data members are not freed Class – Memory Management Cont

Plab 2003 Lecture 420 new & delete - Operators Special operators: IntList* L = new IntList; –allocate memory –call constructor delete L; –call destructor –free memory

Plab 2003 Lecture 421 New new ; Allocate an object of type Apply constructor to the new object Return a pointer to the new object Can be used with any type: int *i = new int; char** p = new (char *);

Plab 2003 Lecture 422 New & Constructors class Counter { public: Counter(); Counter( int c ); Counter( int c, int f); }; … Counter* cp; cp = new Counter; // Calls cp = new Counter(1); // Calls cp = new Counter(1, 2); // Calls

Plab 2003 Lecture 423 New & arrays To allocate arrays, use int n = 4; int* a = new int[10]; // array of 10 ints IntList* b = new IntList[n]; // array of n IntLists Objects in allocated array must have an default constructor!

Plab 2003 Lecture 424 Delete & array Special operation to delete arrays int* a = new int[10]; int* b = new int[10]; … delete [] a; // proper delete command delete b; // error, undefined behavior!

Plab 2003 Lecture 425 Member Initialization class Point { public: Point(int x, int y); ~Point(); int getX() const; int getY() const; private: int m_x, m_y; };

Plab 2003 Lecture 426 #include "Point.h“ class Circle { public: Circle(int x, int y, double r); ~Circle(); //... private: Point m_center; //... }; Member Initialization Cont

Plab 2003 Lecture 427 #include "Circle.h“ Circle::Circle(int x, int y, double r) : m_center(x,y) { //... } Circle::~Circle() { printf(“in ~Circle()"); } Member Initialization Cont Won’t compile without

Plab 2003 Lecture 428 Member Initialization Cont The same syntax also works for primitive types Point::Point(int x, int y) : m_x(x), m_y(y) { } safer than Point::Point(int x, int y) { m_x = x; m_y = y; }

Plab 2003 Lecture 429 Inheritance The main ideas are similar to what you already know from Java. C++ has no interfaces but it allows multiple inheritance

Plab 2003 Lecture 430 #include "Point.h“ class Circle : Point { public: Circle(int x, int y, double r); ~Circle(); //... #include "Circle.h“ Circle::Circle(int x, int y, double r) : Point(x,y) { //... } Circle::~Circle() { printf(“in ~Circle()"); } Member Initialization Won’t compile without

Plab 2003 Lecture 431 C-tor & D-tor order of execution Constructor of the base class is the 1 st to be executed. Why? Then the members are constructed. Finally, the constructor of the class itself is executed. Destruction is done in the opposite order.

Plab 2003 Lecture 432 protected Class members that should be accessible by subclasses are declared protected.

Plab 2003 Lecture 433 “this” pointer A (constant) pointer to the instance for which the member function was invoked. Example: class List { List* next; public: bool on(List*); //... }; bool List::on(List* p) { if (p==null) return false; for (List *q = this; q; q=q->next) if (q == p) return true; return false; }

Plab 2003 Lecture 434 inline functions A hint to a compiler to put function’s code inline, rather than perform a regular function call. Objective: improve performance of small, frequently used functions.

Plab 2003 Lecture 435 inline functions Cont Example: allocateNode() function in data structures like Linked List or Binary Tree. A member function defined in class definition (i.e. the header file) is automatically considered to be inline. An inline function defined in.cpp file is not recognized in other source files.

Plab 2003 Lecture 436 Static class members These are class members class X { private: static int instances; public: X() { instances++; } ~X(); { instances--; } static int getInstances() const { return instances; } };

Plab 2003 Lecture 437 Static class members Example of using a static function: X x1; //... X x2; //... printf(“%d\n”, X::getInstances()); Somewhere (but only in one place!) the instances variable should be defined: //C++ use qualified names int X::instances = 0; In Java declaration and defintion were in the same place