1 / 68

Classes and Objects

Learn about classes and objects in C++. Understand how to define classes, create member functions, work with data members, and use constructors for object initialization.

oreynolds
Download Presentation

Classes and Objects

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Classes and Objects Class Definitions and Objects Member Functions Data Members Get and Set functions Constructors

  2. C++ Program Structure Typical C++ Programs consist of:– A function main One or more classes Each containing data members and member functions.

  3. C++ Gradebook Example “using”:– add the name to the current scope Introduction to Classes and Objects

  4. C++ Gradebook Example Beginning of class definition for classGradeBook Beginning of class body Access specifier public; makes members available to the public Member function displayMessagereturns nothing End of class body Use dot operator to call GradeBook’smember function Introduction to Classes and Objects

  5. C++ Gradebook Example Declaring an object of this classas an automatic variable of main I.e., allocated on The Stack Introduction to Classes and Objects

  6. A string • Represents a string of characters. • An object of C++ Standard Library class std::string • Defined in header file <string>. • Not a character array as in C. • Library function getline • Used to retrieve input until newline is encountered • Example • getline( cin, nameOfCourse ); • Inputs a line from standard input into string object nameOfCourse. • Defined in header file <iostream>.

  7. Data Members of a Class • Declared in the body of the class • May be public or private • Exist throughout the life of the object. • Stored in class object. • Each object has its own copy.

  8. Access-specifier • Makes any member accessible only to member functions of the class. • May be applied to data members and member functions

  9. The Class Constructor: • A class constructor is a special member function of a class that is executed whenever we create new objects of that class. • A constructor will have exact same name as the class and it does not have any return type at all, not even void. Constructors can be very useful for setting initial values for certain member variables.

  10. void Line::setLength( double len ) { length = len; } double Line::getLength( void ) { return length; } // Main function for the program int main( ) { Line line; // set line length line.setLength(6.0); cout << "Length of line : " << line.getLength() <<endl; return 0; } #include <iostream> class Line { public: void setLength( double len ); double getLength( void ); Line(); // This is the constructor private: double length; }; // Member functions definitions including constructor Line::Line(void) { cout << "Object is being created" << endl; }

  11. Output Object is being created Length of line : 6

  12. Destructor • A destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class. • A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc.

  13. void Line::setLength( double len ) { length = len; } double Line::getLength( void ) { return length; } // Main function for the program int main( ) { Line line; // set line length line.setLength(6.0); cout << "Length of line : " << line.getLength() <<endl; return 0; } #include <iostream> using namespace std; class Line { public: void setLength( double len ); double getLength( void ); Line(); // This is the constructor declaration ~Line(); // This is the destructor: declaration private: double length; }; // Member functions definitions including constructor Line::Line(void) { cout << "Object is being created" << endl; } Line::~Line(void) { cout << "Object is being deleted" << endl; } Introduction to Classes and Objects

  14. Output Object is being created Length of line : 6 Object is being deleted Introduction to Classes and Objects

  15. Constructor Example Constructor has same name as class and no return type Initialize data member Introduction to Classes and Objects

  16. Constructor Example Destructor need so this class objectcan free dynamically allocated memory

  17. Constructor Example Creating objects implicitly calls the constructor

  18. Public and Private Members setfunction modifiesprivatedata getfunction accesses privatedata

  19. Public and Private Members (continued) Useset and getfunctions, even within the class privatemembers accessible only to member functions of the class default constructor Accessingprivatedata outside class definition

  20. Public and Private Members (continued) Modifyingprivatedata outside class definition default setting from constructor is an empty string!!

  21. Class in a Separate Header File for Reusability • .cpp files for source-code implemenations • Class implementations • Main programs • Test programs • … • Header files • Separate files in which class definitions are placed. • Allow compiler to recognize the classes when used elsewhere. • Generally have .h filename extensions • Driver file • A program used to test software (such as classes). • Contains a main function so it can be executed.

  22. Operator Overloading, Friends, and References

  23. Learning Objectives • Basic Operator Overloading • Unary operators • As member functions • Friends and Automatic Type Conversion • Friend functions, friend classes • Constructors for automatic type conversion • References and More Overloading • << and >> • Operators: = , [], ++, --

  24. Operator Overloading Introduction • Operators +, -, %, ==, etc. • Really just functions! • Simply "called" with different syntax:x + 7 • "+" is binary operator with x & 7 as operands • We "like" this notation as humans • Think of it as:+(x, 7) • "+" is the function name • x, 7 are the arguments • Function "+" returns "sum" of it’s arguments

  25. Operator Overloading Perspective • Built-in operators • e.g., +, -, = , %, ==, /, * • Already work for C++ built-in types • In standard "binary" notation • We can overload them! • To work with OUR types! • To add "Chair types", or "Money types" • As appropriate for our needs • In "notation" we’re comfortable with • Always overload with similar "actions"!

  26. Overloading Basics • Overloading operators • VERY similar to overloading functions • Operator itself is "name" of function • Example Declaration:const Money operator +( const Money& amount1, const Money& amount2); • Overloads + for operands of type Money • Uses constant reference parameters for efficiency • Returned value is type Money • Allows addition of "Money" objects

  27. Overloaded "+" • Given previous example: • Note: overloaded "+" NOT member function • Definition is "more involved" than simple "add" • Requires issues of money type addition • Must handle negative/positive values • Operator overload definitions generallyvery simple • Just perform "addition" particular to "your" type

  28. Money "+" Definition: Operator Overloading • Definition of "+" operator for Money class:

  29. Overloaded "==" • Equality operator, == • Enables comparison of Money objects • Declaration:bool operator ==(const Money& amount1, const Money& amount2); • Returns bool type for true/false equality • Again, it’s a non-member function(like "+" overload)

  30. Overloaded "==" for Money:Operator Overloading • Definition of "==" operator for Money class:

  31. Constructors Returning Objects • Constructor a "void" function? • We "think" that way, but no • A "special" function • With special properties • CAN return a value! • Recall return statement in "+" overloadfor Money type: • return Money(finalDollars, finalCents); • Returns an "invocation" of Money class! • So constructor actually "returns" an object! • Called an "anonymous object"

  32. Returning by const Value • Consider "+" operator overload again:const Money operator +(const Money& amount1, const Money& amount2); • Returns a "constant object"? • Why? • Consider impact of returning "non-const"object to see…

  33. Overloading Unary Operators • C++ has unary operators: • Defined as taking one operand • e.g., - (negation) • x = -y; // Sets x equal to negative of y • Other unary operators: • ++, -- • Unary operators can also be overloaded

  34. Overload "-" for Money • Overloaded "-" function declaration • Placed outside class definition:const Money operator –(const Money& amount); • Notice: only one argument • Since only 1 operand (unary) • "-" operator is overloaded twice! • For two operands/arguments (binary) • For one operand/argument (unary) • Definitions must exist for both

  35. Overloaded "-" Definition • Overloaded "-" function definition:const Money operator –(const Money& amount){ return Money(-amount.getDollars(), -amount.getCents());} • Applies "-" unary operator to built-in type • Operation is "known" for built-in types • Returns anonymous object again

  36. Overloaded "-" Usage • Consider:Money amount1(10), amount2(6), amount3;amount3 = amount1 – amount2; • Calls binary "-" overload amount3.output(); //Displays $4.00amount3 = -amount1; • Calls unary "-" overload amount3.output() //Displays -$10.00

  37. Overloading as Member Functions • Previous examples: standalone functions • Defined outside a class • Can overload as "member operator" • Considered "member function" like others • When operator is member function: • Only ONE parameter, not two! • Calling object serves as 1st parameter

  38. Member Operator in Action • Money cost(1, 50), tax(0, 15), total;total = cost + tax; • If "+" overloaded as member operator: • Variable/object cost is calling object • Object tax is single argument • Think of as: total = cost.+(tax); • Declaration of "+" in class definition: • const Money operator +(const Money& amount); • Notice only ONE argument

  39. const Functions • When to make function const? • Constant functions not allowed to alter classmember data • Constant objects can ONLY call constantmember functions • Good style dictates: • Any member function that will NOT modify datashould be made const • Use keyword const after functiondeclaration and heading

  40. Overloading Operators: Which Method? • Object-Oriented-Programming • Principles suggest member operators • Many agree, to maintain "spirit" of OOP • Member operators more efficient • No need to call accessor & mutator functions • At least one significant disadvantage • (Later in chapter…)

  41. Overloading Function Application () • Function call operator, ( ) • Must be overloaded as member function • Allows use of class object like a function • Can overload for all possible numbers of arguments • Example:Aclass anObject;anObject(42); • If ( ) overloaded  calls overload

  42. Other Overloads • &&, ||, and comma operator • Predefined versions work for bool types • Recall: use "short-circuit evaluation" • When overloaded no longer uses short-circuit • Uses "complete evaluation" instead • Contrary to expectations • Generally should not overload these operators

  43. A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions. A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends. To declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend as follows: class Box { double width; public: double length; friend void printWidth( Box box ); void setWidth( double wid ); }; Introduction to Classes and Objects

  44. Example void Box::setWidth( double wid ) { width = wid; } // Note: printWidth() is not a member function of any class. void printWidth( Box box ) { /* Because printWidth() is a friend of Box, it can directly access any member of this class */ cout << "Width of box : " << box.width <<endl; } // Main function for the program int main( ) { Box box; // set box width without member function box.setWidth(10.0); // Use friend function to print the wdith. printWidth( box ); return 0; } When the above code is compiled and executed, it produces the following result: Output Width of box : 10 Introduction to Classes and Objects

  45. Example(continue) To declare all member functions of class ClassTwo as friends of class ClassOne, place a following declaration in the definition of class ClassOne: friend class ClassTwo; Consider the following program: #include <iostream> using namespace std; class Box { double width; public: friend void printWidth( Box box ); void setWidth( double wid ); }; // Member function definition Introduction to Classes and Objects

  46. Friend Functions • Nonmember functions • Recall: operator overloads as nonmembers • They access data through accessor and mutatorfunctions • Very inefficient (overhead of calls) • Friends can directly access private class data • No overhead, more efficient • So: best to make nonmember operatoroverloads friends!

  47. Friend Functions • Friend function of a class • Not a member function • Has direct access to private members • Just as member functions do • Use keyword friend in front of function declaration • Specified IN class definition • But they’re NOT member functions!

  48. Friend Function Uses • Operator Overloads • Most common use of friends • Improves efficiency • Avoids need to call accessor/mutatormember functions • Operator must have access anyway • Might as well give full access as friend • Friends can be any function

  49. Friend Function Purity • Friends not pure? • "Spirit" of OOP dictates all operators and functions be member functions • Many believe friends violate basic OOP principles • Advantageous? • For operators: very! • Allows automatic type conversion • Still encapsulates: friend is in class definition • Improves efficiency

  50. Friend Classes • Entire classes can be friends • Similar to function being friend to class • Example:class F is friend of class C • All class F member functions are friends of C • NOT reciprocated • Friendship granted, not taken • Syntax: friend class F • Goes inside class definition of "authorizing" class

More Related