Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ Classes How to Create and Use Them. 2 Overview Terminology File Topology Designing Classes Functions in Classes (methods)  Constructor  Accessors/Modifiers.

Similar presentations


Presentation on theme: "C++ Classes How to Create and Use Them. 2 Overview Terminology File Topology Designing Classes Functions in Classes (methods)  Constructor  Accessors/Modifiers."— Presentation transcript:

1 C++ Classes How to Create and Use Them

2 2 Overview Terminology File Topology Designing Classes Functions in Classes (methods)  Constructor  Accessors/Modifiers  Miscellaneous The Driver and Object instantiation

3 3 Terminology Now in OO land (Object-Oriented) – Real C++ programming! A class is just a combination of data and functions It creates a new data type! A class is a generic description Create several instances of this class (objects) Each instance has their own variables (they don’t share) Functions are now called methods or behaviors (and rarely member functions)

4 4 File Topology (separate files for everything) Description of a cat Description of a dog Description of a person Cat.cppDog.cpp Person.cpp Driver.cpp This is where we create instances of dog and cats and then tell them what to do. It’s the controlling algorithm

5 5 A couple of rules Classes usually begin with an upper-case letter The name of the file that you put the class in should be called the.cpp  Especially if it’s a public class (later) Example:  If we are creating a dog, we should name the class Dog and put it into a file named Dog.cpp  Remember, C++ is case-sensitive!

6 6 The Smallest Class Has template: class { }; Example: you’re told to create class X Solution: class X { }; Remember, this should go in a separate file named X.cpp (not x.cpp)

7 7 A “real life” example The CDog  Attributes (characteristics) rabid or not rabid (bool) weight (int or float) name (char [ ])  Behaviors growl eat

8 8 Step 1: The Skeleton class CDog { // attributes will go here – name, weight, rabid // behaviors will go here – growl, eat };

9 9 Step 2: The attributes (we’ll discuss public later) class CDog { public: boolean rabid; int weight; char name[255]; // Behaviors go here };

10 10 Step 3: The Constructor This is a special function  Used to give initial values to ALL attributes  Is activated when someone creates a new instance of the class The name of this function MUST be the same name as the class

11 11 Step 3: Designing the Constructor Constructors will vary, depending on design Ask questions:  Are all CDogs born either rabid or non-rabid? (yes – they are all born non-rabid)  Are all CDogs born with the same weight? (no – they are born with different weights)  Are all CDogs born with the same name? (no – they all have different names) If ever “no”, then you need information passed in as parameters.

12 12 Step 3: The Constructor class CDog { public: boolean rabidOrNot; int weight; char name [255]; // Constructor CDog::CDog (int x, String y) { rabid = false; weight = x; strcpy (name, y); } // Behaviors go here }; Notice that every CDog we create will be born non-rabid. The weight and name will depend on the values of the parameters

13 13 The Driver We’re talking about a whole new file! The Driver contains main() It’s the controlling algorithm Steps:  Type in the skeleton  Create a couple of instances of classes  Start telling them what to do

14 14 Step 1: Type in the Skeleton #include void main ( ) { // Create your instances here! }

15 15 Step 2: Declare A CDog Pointer #include void main ( ) { CDog* c1; } // null means “dead” null c1

16 16 The new operator new  Brings instances “to life”  Calls the class’ constructor  Opens up enough space in memory to fit an instance of that class Format: * ; = new ( );

17 17 Step 3: Bring c1 to Life #include void main ( ) { CDog* c1; c1 = new CDog (14, “Bob”); } new calls the CDog’s constructor CDog::CDog (int x, char y[ ]) { rabid = false; weight = x; strcpy (name, y); } null c1

18 18 Opens Space new calls the CDog’s constructor CDog::CDog (int x, char y[ ]) { rabid = false; weight = x; strcpy (name, y); } null c1 #include void main ( ) { CDog* c1; c1 = new CDog (14, “Bob”); }

19 19 #include void main ( ) { CDog* c1; c1 = new CDog (14, “Bob”); } Data Passing CDog::CDog (int x, char y[ ]) { rabid = false; weight = x; strcpy (name, y); } null c1 // This is over in CDog.cpp

20 20 Data Passing null c1 rabid:false weight:14 name:”bob” CDog::CDog (int x, char y[ ]) { rabid = false; weight = x; strcpy (name, y); } // This is over in CDog.cpp #include void main ( ) { CDog* c1; c1 = new CDog (14, “Bob”); }

21 21 #include void main ( ) { CDog* c1; c1 = new CDog (14, “Bob”); CDog c2 (7, “Ethel”); } Declare a 2 nd CDog null c1 rabid:false weight:14 name:”bob” CDog::CDog (int x, char y[ ]) { rabid = false; weight = x; strcpy (name, y); } // This is over in CDog.cpp

22 22 #include void main ( ) { CDog* c1; c1 = new CDog (14, “Bob”); CDog c2 (7, “Ethel”); } Opens Space null c1 rabid:false weight:14 name:”bob” CDog::CDog (int x, char y[ ]) { rabid = false; weight = x; strcpy (name, y); } // This is over in CDog.cpp c2

23 23 #include void main ( ) { CDog* c1; c1 = new CDog (14, “Bob”); CDog c2 (7, “Ethel”); } Data Passing null c1 rabid:false weight:14 name:”bob” CDog::CDog (int x, char y[ ]) { rabid = false; weight = x; strcpy (name, y); } // This is over in CDog.cpp c2

24 24 #include void main ( ) { CDog* c1; c1 = new CDog (14, “Bob”); CDog c2 (7, “Ethel”); } Copy Values to Memory null c1 rabid:false weight:14 name:”bob” CDog::CDog (int x, char y[ ]) { rabid = false; weight = x; strcpy (name, y); } // This is over in CDog.cpp c2 rabid:false weight:7 name:”Ethel”

25 25 Back to CDog class CDog { public: boolean rabidOrNot; int weight; char name [255]; // Constructor CDog::CDog (int x, char y[ ]) { rabid = false; weight = x; strcpy (name, y); } // Behaviors we still need to eat and growl };

26 26 Miscellaneous Methods Follow the pattern void CDog::eat ( ) { cout << name << “ is now eating” << endl; weight++; } void CDog::growl ( ) { cout << “Grrrr” << endl; }

27 27 Add Methods class CDog { public: boolean rabidOrNot; int weight; char name [255]; // Constructor CDog::CDog (int x, char y[ ]) { rabid = false; weight = x; strcpy (name, y); } void CDog::eat ( ) { cout << name << “ is now eating” << endl; weight++; } void CDog::growl ( ) { cout << “Grrrr” << endl; } };

28 28 The “.” and “->” operators “Dot” operator used for non-pointers to:  Get to an instances attributes  Get to an instances methods  Basically get inside the instance Format:. Arrow operator used for pointers Format: ->

29 29 Using the “.” and “->” Operators #include void main ( ) { CDog* c1; c1 = new CDog (14, “Bob”); CDog c2 (7, “Ethel”); c2.bark( ); c1->growl( ); }

30 30 Accessors and Modifiers Accessors  A method that returns the value of an attribute  Will have non-void return type  Has return statement inside Modifiers  A method that changes the value of an attribute  Change is based off of a parameter value  Has a void return type Have one accessor and one modifier per attribute

31 31 Accessors and Modifiers Accessor for the rabid attribute bool CDog::getRabid ( ) { return rabid; } Modifier for the rabid attribute void CDog::setRabid (bool myBoolean) { rabid = myBoolean; } Put these inside of the CDog class

32 32 Using accessors and modifiers #include void main ( ) { CDog* c1; c1 = new CDog (14, “Bob”); CDog c2 (7, “Ethel”); c1->setRabid (1); // prints 1 for true cout getRabid( ) << endl; }

33 33 Make a Separate Header File (for the generic description) class CDog { public: int weight; bool rabid; char name [ ]; CDog (int x, char y[ ]); bool getRabid ( ); void setRabid (bool x); char [ ] getName ( ); void setName (char z[ ]); int getWeight ( ); void setWeight (int x); void bark( ); void growl( ); };

34 34 Our Final CDog.cpp #include // Constructor CDog::CDog (int x, char y[ ]) { rabid = false; weight = x; strcpy(name, y); } void CDog::eat ( ) { cout << name << “ is eating”; } void CDog::growl ( ) { cout << “Grrrr”; } bool CDog::getRabid ( ) { return rabid; } void CDog::setRabid (bool x) { rabid = x; } int CDog::getWeight ( ) { return weight; } void CDog::setWeight (int y) { weight = y; } char[ ] CDog::getName ( ) { return name; } void setName (char z[ ]) { name = z; } Cdog.hCdog.cpp

35 35 Summary of Class Concepts A class is a generic description which may have many instances When creating classes 1.Sketch the skeleton 2.Fill in the attributes 3.Make the constructor 4.Make the accessors/modifiers/miscellaneous Classes go in separate files The “.” and “->” operators tell the instances which method to run

36 Inheritance and Objects

37 37 Inheritance Inheritance allows one class to take on the properties of another Superclass-subclass relationship Sometimes called parent-child relationship Use the : to express this relationship Subclass will “inherit” certain attributes and methods Benefit: good design, reuse of code

38 38 Class Hierarchy Mammal Land-Mammal int weight int numLegs Dog boolean rabid Chihuahua giveBirth( ) SheepDog Question: how many attributes does Dog have?

39 39 Things to Note Land-Mammal is a superclass to Dog, but a subclass to Mammal Dog has three attributes  weight, numLegs and rabid  Two from inheritance, one it declared itself

40 40 An Example (CDog.h – just review) #include class CDog { public: int weight; char name [255]; bool rabid; CDog(int x); void growl( ); };

41 41 CDog.cpp (still review) #include "CDog.h" CDog::CDog(int x) { weight = x; rabid = false; strcpy (name, "bob"); cout << "A CDog was made" << endl; } void CDog::growl( ) { cout << “Grrrr" << endl; }

42 42 Poodle: The evil subclass Since a poodle is a type of CDog, how can we make class Poodle without re-writing a lot of code? Does a poodle necessarily growl the same way a CDog growls?

43 43 Class Poodle (both header and cpp file) #include "CDog.h“ class CPoodle:public CDog { public: CPoodle(int x); }; CPoodle::CPoodle(int x) : CDog (x){ cout << "A poodle was made" << endl; } Here’s where we inherit from CDog

44 44 What’s going on here? CPoodle::CPoodle(int x) : CDog (x){ cout << "A poodle was made" << endl; } Normal Constructor Stuff The super class’s constructor is always called*; in this case, we call the constructor which takes an int. *Note: if you don’t explicitly call the super constructor, it looks for a no-arguments constructor in the super class (which we don’t have)

45 45 What just happened? We created a poodle that has all the attributes and all the methods that a CDog has Problem: CPoodle* myPoodle = new CPoodle (3); myPoodle->growl ( ); // prints GRRRR Poodles don’t go GRRRR, they “yip”

46 46 Overriding methods When you override a method, you give new functionality to the class In this case, we need to override the growl method for the poodle Simply redefine the method

47 47 A Better Poodle (if there is such a thing) #include "CDog.h" class CPoodle:public CDog { public: CPoodle(int x); void growl(); }; CPoodle::CPoodle(int x) : CDog (x){ cout << "A poodle was made" << endl; } void CPoodle::growl( ) { cout << "Yip!" << endl; } Now when we tell the poodle to growl, it will print “Yip”

48 48 Access Keywords: public, private (and protected) We can restrict access to attributes and methods inside a class using public and private public – means “everyone can see it” private – means “only that class can see it”

49 49 Bad Example (won’t compile) class X { private: int myInt; // Constructor… } void main ( ) { X* myX = new X ( ); myX->myInt = 42; // Not Allowed! }

50 50 Working Example class X { public: int myInt; // Constructor… } void main ( ) { X* myX = new X ( ); myX->myInt = 42; // Allowed! }

51 51 Why private? Security: Keeps other classes from changing attributes at random Design: forces other classes to use accessors and modifiers to get to the information Encapsulation: the class is complete to itself

52 52 Memory Trace Dog *d1, *d2; d1 = new Dog (5, “bob”); d2 = new Dog (5, “bob”); d1 = d2; null

53 53 Memory Trace (declare the variables; they are dead) Dog *d1, *d2; d1 = new Dog (5, “bob”); d2 = new Dog (5, “bob”); d1 = d2; null d1 d2

54 54 Memory Trace (bring d1 to life) Dog *d1, *d2; d1 = new Dog (5, “bob”); d2 = new Dog (5, “bob”); d1 = d2; // Remember, new opens up // space and calls the class // constructor null d1 d2

55 55 Memory Trace (bring d1 to life) Dog *d1, *d2; d1 = new Dog (5, “bob”); d2 = new Dog (5, “bob”); d1 = d2; // Remember, new opens up // space and calls the class // constructor null d1 d2

56 56 Memory Trace (bring d1 to life) Dog *d1, *d2; d1 = new Dog (5, “bob”); d2 = new Dog (5, “bob”); d1 = d2; // Remember, new opens up // space and calls the class // constructor null d1 d2 rabid=false weight=5 name=“bob”

57 57 Memory Trace (bring d2 to life) Dog *d1, *d2; d1 = new Dog (5, “bob”); d2 = new Dog (5, “bob”); d1 = d2; // Remember, new opens up // space and calls the class // constructor null d1 d2 rabid=false weight=5 name=“bob”

58 58 Memory Trace (bring d2 to life) Dog *d1, *d2; d1 = new Dog (5, “bob”); d2 = new Dog (5, “bob”); d1 = d2; // Remember, new opens up // space and calls the class // constructor null d1 d2 rabid=false weight=5 name=“bob” rabid=false weight=5 name=“bob”

59 59 Memory Trace (comparison) d1 and d2 do NOT occupy the same space in memory, so they are NOT == Example: d1 == d2 evaluates to false null d1 d2 rabid=false weight=5 name=“bob” rabid=false weight=5 name=“bob”

60 60 Memory Trace (have d1 point to d2) Dog *d1, *d2; d1 = new Dog (5, “bob”); d2 = new Dog (5, “bob”); d1 = d2; null d1 d2 rabid=false weight=5 name=“bob” rabid=false weight=5 name=“bob”

61 61 Memory Trace (have j1 point to j2) Dog *d1, *d2; d1 = new Dog (5, “bob”); d2 = new Dog (5, “bob”); d1 = d2; null d1 d2 rabid=false weight=5 name=“bob” rabid=false weight=5 name=“bob”

62 62 Memory Trace (have j1 point to j2) Now, d1 and d2 are == But no one is pointing to this Because no one is pointing to it, we can no longer reference it. We call this piece of memory garbage. We killed it! null d1 d2 rabid=false weight=5 name=“bob” rabid=false weight=5 name=“bob”

63 63 Freeing up Memory Necessary to get rid of unused memory Rule: never set to null Use the delete ( ) operator Takes in a pointer to an object Usage (from previous example): delete (d1);

64 64 Summary of Inheritance Benefits of inheritance  Allows for reuse of code  Good design Use : to achieve this Override methods in subclasses == tests for same object in memory

65 C++ Classes Object Oriented Programming

66 66 Object Oriented Programming Programmer thinks about and defines the attributes and behavior of objects. Often the objects are modeled after real-world entities. Very different approach than function-based programming (like C).

67 67 Reasons for OOP Abstraction Encapsulation Information hiding Inheritance Polymorphism Software Engineering Issues

68 68 Class: Object Types A C++ class is an object type. When you create the definition of a class you are defining the attributes and behavior of a new type. Attributes are data members. Behavior is defined by methods.

69 69 Creating an object Defining a class does not result in creation of an object. Declaring a variable of a class type creates an object. You can have many variables of the same type (class).  Instantiation

70 70 Information Hiding The interface to a class is the list of public data members and methods. The interface defines the behavior of the class to the outside world (to other classes and functions that may access variables of your class type). The implementation of your class doesn't matter outside the class – only the interface.

71 71 Information Hiding (cont.) You can change the implementation and nobody cares! (as long as the interface is the same). You can use other peoples classes without fear! Wars will end, poverty and illness will be vanquished from earth!

72 72 Inheritance It is possible to extend existing classes without seeing them. Add whatever new behavior you want. Example:  You have a class that represents a "student".  Create a new class that is a "good student". Most of the behavior and attributes are the same, but a few are different – specialized.

73 73 Polymorphism The ability of different objects to respond to the same message in different ways. Example: Tell an int to print itself: cout << i; Now tell a double: cout << x; Now tell the Poly: cout << poly;

74 74 Private vs. Public Public data members and methods can be accessed outside the class directly. The public stuff is the interface. Private members and methods are for internal use only. We will also see Protected.

75 75 Special Member Functions Constructors: called when a new object is created (instantiated).  can be many constructors, each can take different arguments. Destructor: called when an object is eliminated  only one, has no arguments.

76 76 Accessing Data Members Data members are available within each method (as if they were local variables). Public data members can be accessed by other functions using the member access operator "." (just like struct).

77 77 Accessing class methods Within other class methods, a method can be called just like a function. Outside the class, public methods can be called only when referencing an object of the class.

78 78 What happens here? class foo { int i;// # elements in the array int a[10];// array 10 at most // sum the elements int sum(void) { int i, x=0; for (i=0;i<i;i++) x+=a[i]; return(x); }... which i is it ?

79 79 Class Scope Operator :: You can solve the previous problem using the "::" operator classname::membername. for (i=0;i<foo::i;i++) x+=a[i];

80 80 Method names and :: Sometimes we put just a prototype for a member function within the class definition. The actual definition of the method is outside the class. You have to use :: to do this.

81 81 Example class foo {... int sum(void); }; int foo::sum(void) { int sum=0; for (int i=0;i<foo::i;i++) { sum += a[i]; } return(sum); }

82 82 Classes and Files The relationship between C++ class definitions and files depends on the compiler. In general you can put class definitions anywhere! Visual C++ wants one class per file. Most people do this:  class definition is in classname.h  any methods defined outside of the class definition are in classname.cpp

83 83 static methods A static method is a class method that can be called without having an object. Must use the :: operator to identify the method. Method can't access non-static data members! (they don't exist unless we have an object).

84 84 Static Data Members It is possible to have a single variable that is shared by all instances of a class (all the objects).  declare the variable as static. Data members that are static must be declared and initialize outside of the class.  at global or file scope.

85 85 Static data member example class foo { private: static int cnt; public: foo() { foocount++; cout << "there are now " << cnt << " foo objects << endl; }...

86 86 A Problem Class definitions usually in a ".h" file. Can be included by many other ".cpp" files, all part of the same program. Can't declare and initialize a static data member in the ".h" file.

87 87 Solution class foo{ static int cnt; … }; int foo::cnt=1; foo.h foo.cpp #include "foo.h"... #include "foo.h"... int main() {... f1.cpp f2.cpp

88 88 Operator Overloading We can define what some C++ operators mean when applied to user defined objects. vector example (ivec.h) defines operators: ostream << istream >> + - [] = ==

89 89 Operator Overloading Restrictions You can't:  define a completely new operator  redefine the meaning of operators on built-in data types (like int or double ).  Change operator precedence or associatively.

90 90 Inheritance You can create a new class that inherits from an existing class. You can add new members and methods. You can replace methods. The new class is a specialization of the existing class.

91 91 Terminology The existing class is called the base class. The new class is called the derived class. Objects of the derived class are also objects of the base class.

92 92 Inheritance Example Base class is shape, represents the abstract notion of a shape. Derived classes:  rectangle  circle  triangle. An object that is a circle is also a shape!

93 93 Protected Class members/methods We've already seen private and public. Protected means derived classes have access to data members and methods, but otherwise the members/methods are private.

94 94 Public/Private/Protected Inheritance Usually use public inheritance. Private and Protected inheritance change what members/methods can be accessed outside of the class.

95 95 Polymorphism You can treat derived class objects as objects of the base class. The problem is that when doing this we don't get access to the derived class methods!

96 96 Virtual Functions A virtual function is a method in a base class that can be overridden by a derived class method. For example, we would like each object to "know" which print() method to use. Declare the base class print method virtual, and this happens!

97 97 The End Next Lecture Chapter 12: Multi-dimensional Arrays Program – 2, Due Thurs 7/7 Program 2 will require for you to create and use a class.


Download ppt "C++ Classes How to Create and Use Them. 2 Overview Terminology File Topology Designing Classes Functions in Classes (methods)  Constructor  Accessors/Modifiers."

Similar presentations


Ads by Google