Beruflich Dokumente
Kultur Dokumente
Week 9
Synopsis
Declaring classes Initializing class member variables Public vs. private member functions Constructors & Destructors Inheritance Polymorphism Virtual Member Functions Overriding Member Functions
Week 9
Polymorphism
The ability of objects that belong to related classes to respond differently to the same operation Virtual functions
Week 9
C++
OOP Language
Builds strong link between the data structures and the methods that manipulate the data Think of objects & their behavior
Mammals Persons Mobile phones Satellite vehicles Geometric Shapes
Week 9
Classes in C++
Structure
collection of variables of different types contained within a name (tag)
Example
class cat
// template of an object
Class
collection of (member) variables of different types combined with a set of related (member) functions contained within a name (tag)
Classes
encapsulate the data and functions into one collection the object.
Encapsulation
makes programming and maintenance easier Everything is one place C++ imposes a built in discipline
Introd to C/C++ (Section 2) Week 9
{ private: //protected area unsigned int Age; // data members unsigned int Weight; public: // member function void Meow( ); }; // member function declaration void Meow( void); int main( ){ cat X; //instantiate (object) X X.Meow; //invoke method X.Age = 5; //forbidden private } void Cat::Meow( ) // class definition { cout << Meow << endl; }
Class Skeleton
Private member data members protect data in class from being erroneously modified from the outside the class Privatize data members Public member functions Socialize (make public) member functions allow access to private parts via built-in functions (public accessor) Every public member function has access to the private data members Member function definition use scoping operator :: int cat::getAge( ) { :::::::: }
Introd to C/C++ (Section 2)
Example
class cat // class declaration or prototype { // private: - by default int Age; int Weight; public: // public member functions void setAge(int x){Age = x;} //inline void setWeight(int y){Weight = y;} int getAge(){return Age;} int getWeight(); void Meow(); }; int main() { cat X; int temp; X.setAge(6); X.setWeight(20); temp = X.getAge( ); temp = X.getWeight( ); } // access thru scoping operator :: int cat::getWeight() {return Weight;} void cat::setWeight(int W){weight = W;} 7
Week 9
Constructors
Constructors Constructor - is unique member function that is used for initializing the data members of a class Constructors can take parameters but it is not mandatory Constructors cannot return a value even void Constructor has the same name as class Default constructors if you do not declare a constructor the compiler will provide one automatically Constructors declarations cat::cat(int age, int weight); cat::cat(int age); cat::cat( ) default constructor If you provide a constructor then default constructor will not be provided automatically by compiler you should create your own
Example class Cat // prototype (declaration) { private: int Age, Weight, Id; public: // constructors Cat(int age, int weight, int id); Cat( );// default constructor
// member functions int getAge(){return Age}; int getWeight() (){return Weight}; //inline fnct void Meow(); }; int main() { Cat X(5,20,35); //constructors Cat Y; } Cat::Cat(int age, int weight, int id) //definitions { Age = age; Weight = weight; Id = id; } Cat::Cat( ) // default constructor {Age = 0; Weight = 0; Id = 0;}
Week 9
Destructors
Destructor - is a unique member function cleans up after object goes out scope de-allocates memory Destructors have always the name of the class Destructors are always preceded with
class Cat {
private:
// prototype (declaration)
~
Destructor never take arguments
};
Cat(int age, int weight, int id); // constructors Cat( );// default constructor ~Cat( ); //destructor int getAge(); //other member functions int getWeight(); void Meow(); int main() { Cat X(5,20,35); Cat Y; } Cat::Cat(int age, int weight, int id) //definitions { Age = age; Weight = weight; Id = id; } // default constructor Cat::Cat( ) {Age = 0; Weight = 0; Id = 0;} Cat::~Cat( ){ cout << going out of scope}
Week 9
Friend Functions
Friend member function does exactly what other member functions except that it has access to private members of one or more classes class tax; //announcement class customer{ int cost_item; public: customer(){balance = 0;} friend void PRINT(customer x, tax y); } class tax{ int rate; public: tax( ){rate = 0;} friend void PRINT(customer x, tax y); }; void PRINT(customer x, tax y) { cout << x.getName << getName << endl; cout << y.getTax << y.getTax << endl; }
Week 9
10
Inheritance
A class that adds new functionality to an existing class is said to be derived from the original (base) class A class inherits from its base class many of its attributes Single inheritance derived from a single class
class A; class B: public A
Single Inheritance
Shape
Attributes
int X; Int Y;
Square
Circle Point Center(5);
Rectangle
Inheritance
is-a relationship
Week 9
11
Inheritance
Class inheritance allows members of one class to be used as if they were members of a second class A derived class can inherit from its base class in three ways:
public private protected A class can contain three types of members: public
Visible outside the class
private
Accessible only thru public member functions
protected
Accessible only thru public member functions Protected data & functions are fully visible to derived classes
Examples
class Student:public Person;
Week 9
12
Inheritance
Inheritance
members
Public memb Private memb Private Protected memb Protected
A C C E S s
I N H E R I T s
public
Public
private
Private
Private
Private
protected
Protected
Private
Protected
Week 9
13
Inheritance
If a base class and a derived class have identical named public functions with the same signature, invoking the function in the derived class overrides the base function Example class Circle:public Shape{ //derived
private: int r; // radius public: void Print( ){cout << Circle << endl;} }; class Rectangle:public Shape{//derived private: int len, ht;; public: void Print( ){cout << Rectangle << endl;} }; int main() { Circle c; Rectangle r; c.Print( ); // Circle r.Print( ); // Rectangle }
class Shape{ public: void setColor(int new_color); void move(int x, int y); void Print( ){cout << Shape << endl;} //constructors //destructors private: int x, y; //center of shape };
Week 9
14
Virtual Functions
#define PI 3.14159 class Shape{ public: void setColor(int new_color); void move(int x, int y); virtual float area( ){return -1;} virtual float perim( ){return -1;} //constructors //destructors private: int x, y; //center of shape }; class Circle:public Shape{ //derived private: int r; public: virtual float area( ){ return (PI*r*r);} };
class Rectangle:public Shape{//derived private: int u, v; public: virtual float area( ){ return (u*v);} virtual float perim( ){retrun (2*u + 2*v;} }; int main() { Shape *p; // pointer to shape Circle c; Rectangle r; int flag = 1; if( flag ==1 ) p = &c; //point to circle else p = &r; //point to rectangle p->area( ); //get area ???? }
Week 9
15
Standard Libraries
C STANDARD LIBRARY
Contains function prototypes, type and macro definitions
#include <ctype.h> - character handling #include <errno.h> - error handling #include <string.h> - string handling
int strlen(char *s1), int strcmp(char *s1, *char *s2), etc
#include <time.h> - date and time #include <math.h> - sin, cos, tan, etc
Introd to C/C++ (Section 2) Week 9 16
Week 9
17
Templates
Templates are patterns from which classes can be created Example Template <class Type> class Array { public: Array(int Size); //constructor ~Array( ){delete [ ] Array_ptr;} int getSize(){return size;} private: int size; Type *Array_ptr; }; Array<Type>::Array(int Size) { size = Size; Array_ptr = new Type[size]; //Heap }
int main() { Array<int> A[4]; //array 4 ints Array<float> F[12]; { Array<char> C[32]; }//destroy C after going out of scope }
Week 9
18
Linked List
linked list - is a data structure that consists of a sequence of data records such that in each record there is a field that contains a reference (i.e., a link) to the next record in the sequence.
The principal benefit of a linked list over a conventional array is that the order of the linked items may be different from the order that the data items are stored in memory or on disk. For that reason, linked lists allow insertion and removal of nodes at any point in the list, with a constant number of operations. On the other hand, linked lists by themselves do not allow random access to the data, or any form of efficient indexing. Thus, many basic operations such as obtaining the last node of the list, or finding a node that contains a given datum, or locating the place where a new node should be inserted may require scanning most of the list elements.
Introd to C/C++ (Section 2) Week 9 19
Linked Lists
struct node { int value; struct node *next; };
X4
value struct node X1, X2,X3, X4; strcut node *temp; X1.value = 5; X1 X2 X3 X1.next = &X2; X2.value = 6; value value value NULL X2.next = &X3 Link Lists are used when you need to maintain a disorganized list X3.value= 7; of items that can be dynamically allocated and de-allocated Example: Modeling communications center receiving & dropping random calls X3.next = NULL
Week 9
20
lemon
two children
date
pear
berry
grape
orange quince
struct node{ char fruit[32]; char describer[128]; struct node *left; struct node *right; }; Searches are quick ~ log2(N) fast rather than N
Week 9
21
Binary Search
Problem: Given an sorted list of values (names), what is average # searches that are necessary to find a random value (name)? Linear Search - probing each name in the list, will take on the average N/2 comparisons Binary Search algorithm is implemented by jumping to middle of array and testing target name vs. array name (equal, smaller, larger) Algorithm requires log2 (N) vs. O(N)
e.g. log2 (1024) ~ 10 attempts vs. O(1024/2) Benson |Doe | Frank ||Julian| **|Oscar |**
Introd to C/C++ (Section 2) Week 9
| Zorba
22