Presentation is loading. Please wait.

Presentation is loading. Please wait.

Classes. What is a class? Data and the functions (methods) that operate on that data – collectively called members –Example: bank account class Provide.

Similar presentations


Presentation on theme: "Classes. What is a class? Data and the functions (methods) that operate on that data – collectively called members –Example: bank account class Provide."— Presentation transcript:

1 Classes

2 What is a class? Data and the functions (methods) that operate on that data – collectively called members –Example: bank account class Provide structure for organizing programs –Almost like an advanced struct

3 Object-Oriented Design Method for designing computer programs Consider “objects” interacting in the program –Example: a zoo The behavior of each kind of object is defined in a class

4 Syntax class classname { private: … public: … } private only accessible within the class public accessible from anywhere (like with a struct)

5 Member Functions Typically, data (variables) declared private Functions operate on data –accessor functions – read data, provide access to data but do not change it –update functions – change data –examples from bank account, zoo??? –constructor – builds a new object

6 Writing Classes Typically, two files header and source Header declares member variables, provides function prototypes and bodies of short functions Source provides code for rest of functions When specifying function bodies outside of class definition :: must be used –void BankAccount::withdraw(double amount)

7 Creating and Using Objects BankAccount b(“Sami Rollins”); //Type Name(constructor parameters); //how would you withdraw funds?

8 Creating and Using Objects BankAccount b(“Sami Rollins”); Type Name(constructor parameters); //how would you withdraw funds? b.withdraw(“300”); object_name.method_name(param list);

9 Constructor BankAccount::BankAccount(double init_balance) class_name(parameter list) Special-case function called when a new object is created Used to initialize member variables –Examples?

10 Alternative Initialization BankAccount::BankAccount(double init_balance) { balance = init_balance; } BankAccount::BankAccount(double init_balance) : balance(init_balance) { }

11 Destructor BankAccount::~BankAccount() ~class_name Used if class allocates memory dynamically (uses new) Delete all dynamically declared objects

12 friend Allow a class to access the private members of another class Operator overloading Closely related classes

13 STL and Templates STL – Standard Template Library –collection of classes useful for many programs Templates –a class which can hold objects of any kind vector scores(100); vector bank_records(500); Vector – resizable array


Download ppt "Classes. What is a class? Data and the functions (methods) that operate on that data – collectively called members –Example: bank account class Provide."

Similar presentations


Ads by Google