Classes and Objects in Programming

Classes and Objects in Programming
Slide Note
Embed
Share

Classes in programming serve as blueprints for creating objects, defining their behaviors and properties. Objects, in turn, represent entities that encapsulate state and behavior. This paradigm, known as object-oriented programming (OOP), enables interactions between objects to execute program logic efficiently. Through examples in C++, the concept of classes and objects is demonstrated, emphasizing their role in managing complexity and facilitating code reusability.

  • Classes
  • Objects
  • Programming
  • OOP
  • C++

Uploaded on Feb 21, 2025 | 2 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Classes and Objects Classes and Objects "A class is where we teach an object how to behave." --Rich Pattis

  2. C++ Classes C++ Classes Classes are programmer-defined types Classes help us manage complexity, since they: tie together related data and operations decompose an application into objects and their interactions can be re-used in different applications Example: string class data: sequences of characters operations: length(), append(), insert(), etc. general description or blueprint of a collection of objects and operations that I can invoke on those objects string myDogsName = "Charlie"; // a string object, a instance of string class Call string member functions on the object: myDogsName.append(" Boy");

  3. Calendar Program Calendar Program Want to write program that manipulates dates Calendar application, program that stores birthdays, etc. No C++ type that represents dates What is today's date? 10 30 What is your birthday: 11 3 It is 4 days until your next birthday. So: write a Date class so that each object represents a date like October 30. What data and operations should a Date object have?

  4. Date Date client code client code #include<iostream> #include "Date.h" int main() { Date today(10, 30); Date halloween(10, 31); cout << "Today is: " << today.toString() << ", the month is: " << today.getMonth() << endl; }

  5. Classes and Objects Classes and Objects class: a blueprint or template for a new type of objects object: an entity in your program that combines state and behavior object-oriented programming (OOP): programs that perform their behavior as interactions between objects

  6. Blueprint analogy Blueprint analogy iPod blueprint state: current song volume battery life behavior: power on/off change station/song change volume choose random song creates iPod #1 iPod #2 iPod #3 state: song = "1,000,000 Miles" volume = 17 battery life = 2.5 hrs behavior: power on/off change station/song change volume choose random song state: song = "Letting You" volume = 9 battery life = 3.41 hrs behavior: power on/off change station/song change volume choose random song state: song = "Discipline" volume = 24 battery life = 1.8 hrs behavior: power on/off change station/song change volume choose random song

  7. Abstraction Abstraction abstraction: A distancing between ideas and details. We can use objects without knowing how they work. Objects provide abstraction in programming. abstraction in an iPod: You understand its external behavior (buttons, screen). You don't understand its inner details, and you don't need to, in order to use an iPod.

  8. Class Design Class Design We will implement a Date class, i.e., a type of objects named Date Each Date object will contain month, day variables called fields or member variables Each Date object will contain behavior called member functions or methods Client programs will use the Date objects. To create a new class, think about the objects that will be created of this new class type: what information to store about the object what behavior the object has

  9. In a Class In a Class instance variables or fields: the state/data of an object each object has its own copy of each field private: not accessible outside the class also known as instance variables member functions: the behavior of an object also called methods methods can operate on the data in the object constructor: special method called when object is created initializes the state of the new object, often using the constructor's arguments has the same name as the class

  10. Client, Class and Object Client, Class and Object Use class to construct new objects Client Program int main() {... Class - uses class and objects - defines data in each object -how to construct new objects send/receive messages to/from objects by calling member functions constructs Object -member functions (behavior) fun1() fun2() -member variables (data) object object

  11. C++ Date Class C++ Date Class int Date::daysInMonth() const { if(month == 4 || month == 9 || month == 6 || month == 11){ return 30; } else if(month == 2) return 28; else return 31; } void Date::nextDay() { day++; if(day > daysInMonth()) { day = 1; month++; if(month > 12) month = 1; } } #include "Date.h" Date::Date(int m, int d) { month = m; day = d; } int Date::getMonth() const { return month; } int Date::getDay() const { return day; }

  12. Interface and Implementation Interface and Implementation C++ classes: interface: declaration of functions, classes, members, etc. implementation: definitions how the things in interface are implemented Separated into two types of files header ClassName.h file contains the interface source ClassName.cpp file contains definitions the implementation For class Date, write Date.h and Date.cpp In Date.cpp: #include "Date.h" No main function in either file

  13. .h File .h File // yourClass.h #ifndef _classname_h #define _classname_h Possibly multiple .cpp files will include the header file. This prevents the contents getting declared twice. class declaration #endif

  14. Class Declaration Class Declaration class ClassName { public: ClassName(parameter-list); // constructor type name1(parameter-list); // member functions type name2(parameter-list); private: type name; // member variables type name; };

  15. Date.h Date.h #ifndef _date_h #define _date_h #include<string> class Date { public: Date(int m, int d); // constructor int daysInMonth()const; int getMonth()const; int getDay()const; void nextDay(); std::string toString(); private: int month; int day; }; // must have ; #endif

  16. Encapsulation Encapsulation encapsulation: hiding implementation details of class from clients protects data from manipulation by client Ex: client cannot change month field in Date object to 20 Class data fields should be declared private access permitted only through member functions code outside class cannot access them private: type fieldName;

  17. Member Definitions (.cpp file) Member Definitions (.cpp file) ClassName.cpp: contains function definitions for member functions that were declared in header file #include "ClassName.h" type ClassName::functionName(parameter-list) { // function stuff } Not any old function part of my class

  18. Implementation, cont'd Implementation, cont'd #include "Date.h" Date::Date(int m, int d) { month = m; day = d; } // write getMonth() function here... ...

  19. Date Class Date Class int Date::getMonth() { // in Date.cpp return month; } today month day 10 30 // client code Date today; Date halloween; ... int mo = today.getMonth(); halloween.getMonth(); int Date::getMonth() { return month; } halloween month day 10 31 int Date::getMonth() { return month; }

  20. Client Code Client Code #include<iostream> #include "Date.h" using namespace std; int main() { Date date1(10, 30); Date date2(10, 31); Date examDate(12, 15); cout << "date1 is: " << date1.getMonth() << "/" << date1.getDay() << endl; }

  21. Operator Overloading Operator Overloading Overload the behavior of operators in C++ + - ++ * & ! % > Don't overuse can produce confusing code Declare operator in .h file, implement in .cpp type operator op(parameter-list); // .h type operator or(parameter-list) { // .cpp statements; }

  22. Operator Overloading Operator Overloading In Date.cpp bool operator ==(const Date& d1, const Date& d2) { return d1.getMonth() == d2.getMonth() && d1.getDay() == d2.getDay(); } Exercise: Overload < for Dates: if a Date comes earlier in the year, it's less than another Date Exercise: Overload <= and != for Date class

  23. Point Class Point Class Represents points in 2D space The class is a blueprint that describes how to create objects We will define a type called Point Each object has its own data/state and methods State of a Point object (i.e., member variables)? Behavior of a Point object (i.e., member functions)?

  24. Point Class: a new type Point Class: a new type Represents any point in 2D space State of a Point object: x and y fields Behavior of a Point object: accessors that return the value of each field compute distance of Point object to the origin (0, 0) mutators that change the value of a field update the Point object's location (change x and y fields)

  25. Point.h Point.h #ifndef _POINT_H #define _POINT_H class Point { private: int x; int y; public: Point(int x, int y); int getX(); int getY(); double distance(Point& p); void setLocation(int x, int y); }; #endif // accessor/getter

  26. Point.cpp Point.cpp #include "Point.h" parameter Point::Point(int x, int y) { this->x = x; this->y = y; } // fill in the rest this is a pointer to the current object (has type const Point *) can be used to distinguish between member variables and parameters with the same name

  27. implicit parameter implicit parameter implicit parameter: the object on which a member function is called date1.getMonth(); object called date1 is the implicit parameter Member function refers to that object's member variables Acts like each object has its own copy of the member functions this: pointer to the object on which member function is called this month;

  28. Class Terminology Class Terminology accessor methods (aka getters): methods that return value of an instance variable naming convention: getInstanceVariable() Ex: For Date class: getMonth(), getDay() mutator methods (aka setters): methods that modify the value of an instance variable naming convention: setInstanceVariable() Ex: For Date class: setMonth(), setDay() Do these defeat the purpose of making instance variables private? friend: Designate a function as a friend of a class then it can access the private instance variables directly friend bool operator ==(const Date &d1, const Date & d2); bool operator ==(const Date& d1, const Date& d2) { return d1.month == d2.month && d1.day == d2.day; } // in Date.h // in Date.cpp

  29. Exercise Exercise Modify the class so that a Point can be constructed with no parameters, in which case it's initialized to represent (0, 0) Write a translate member function that shifts the position of a Point by specified values in x and y direction Overload the == operator for Point

  30. Constructors Constructors initialization list: a different way to initialize member variables Class::Class(parameter-list) : field(param), ..., field(param) { //statements } Date::Date(int m, int d) : month(m), day(d) { ... } default constructor: if no constructors provided, a default no-arg constructor is automatically provided sets all fields to 0 for their type (0, 0.0, NULL, false...) Multiple constructors: can't call each other

  31. malloc vs. new malloc vs. new Use to allocate memory for: malloc: any primitive type new: arrays, structs, objects What happens when memory runs out? malloc: returns NULL new: throws an exception How to deallocate: malloc: free new: delete (or delete [] for arrays)

  32. Arrays Arrays Allocated on stack: type name[size]; Allocated on heap: type* name = new type[size]; Example: int* numbers = new int[5]; for(int i = 0; i < 5; i++) { numbers[i] = 2 * i; } ... delete [] numbers;

  33. Creating Instances/Objects Creating Instances/Objects Creating an object on runtime stack: type name(parameter-list); Date date1(9, 11); cout << date1.getMonth(); Creating object on heap: type* name = new type(parameter-list); Date* date2 = new Date(10, 30); cout << date2 getMonth(); delete date2; // free memory

  34. Objects: Stack or Heap? Objects: Stack or Heap? Heap: if it needs to exist after function returns to allocate a bunch of objects new: allocates memory for new object, calls class constructor, returns pointer to new object call delete on anything you allocate with new Stack: semantics a bit simpler a stack-allocated object is copied when you pass it as an argument foo(date1); return it return date1; assign one object to another d = date1;

  35. Object Parameters Object Parameters Usually don't want to copy objects when they are passed: double Point::distance(Point p) { int dx = x - p.getX(); int dy = y p.getY(); return sqrt(dx*dx + dy*dy); } Every time distance is called, argument copied into parameter Slow & wastes memory Can't modify argument

  36. Object Reference Parameter Object Reference Parameter Pass a reference or pointer to object instead double Point::distance(Point& p) { int dx = x - p.getX(); int dy = y p.getY(); return sqrt(dx*dx + dy*dy); } Now parameter and argument reference same memory Better to make parameter const distance method guarantees it doesn't modify p double Point::distance(const Point& p) {... Clients know which methods modify arguments

  37. const method const method If method does not modify the object it's invoked on, make it const double Point::distance(Point& p) const { int dx = x - p.getX(); int dy = y p.getY(); return sqrt(dx*dx + dy*dy); } Placing const after parameter list indicates that method does not modify object it's called on

  38. Oy, const and pointers Oy, const and pointers ( (aka C++, why do you hate me?) aka C++, why do you hate me?) const Point *p p points to a const Point (a Point with state that cannot be changed) p can be reassigned to point to another const Point Point * const p p is a constant pointer p can't be reassigned to point at another object the Point's state can be changed const Point * const p p is a constant pointer that points to a constant Point cannot reassign p to point at a different object cannot modify the Point's state

  39. Exercise: BankAccount Class Exercise: BankAccount Class State? name of account holder, balance Behavior? accessor methods, withdraw, deposit Constructors: two argument constructor, one argument constructor (which takes name and sets balance to 0) Overload: ==, !=

  40. Exceptions Exceptions exception: an error represented as an object C handles errors by returning error codes C++ can represent errors as exceptions that are thrown/caught Throwing exception: Syntax: throw expression; Generates an exception that will crash the program, unless there is matching code to handle the error (i.e., "catch" the exception) // pre: balance is non-negative BankAccount::BankAccount(string name, double balance) { if(balance < 0) { throw "Illegal negative balance"; } this name = name; this balance = balance; }

  41. Exceptions Exceptions catching an exception with a try/catch block: try { if(n < 0) throw n; double answer = sqrt(n); cout << answer << endl; } catch (double d) { cout << "Cannot take sqrt of " << d << endl; }

More Related Content