Sie sind auf Seite 1von 22

Introduction to C/C++

Yedidiah Solowiejczyk Week 9

Introd to C/C++ (Section 2)

Week 9

Review of Classes in C++


Synopsis

Declaring classes Initializing class member variables Public vs. private member functions Constructors & Destructors Inheritance Polymorphism Virtual Member Functions Overriding Member Functions

Standard Libraries math.h, stdlib.h, etc More on Exotic Pointers.


Link Lists Binary Trees Binary Search
Introd to C/C++ (Section 2) Week 9 2

A Brief History of C++


C++ Programming 1980 Stroustrop at Bell Labs extended the C programming language to include the concept of class combining data with the respective functions that manipulate the data Object-Oriented Programming (OOP) Encapsulation Strong data typing Inheritance Reusability Polymorphism Run-time functionality

Introd to C/C++ (Section 2)

Week 9

Object Oriented Programming


Encapsulation
The ability to define new data types and set of operations (functions) governing the new type

Inheritance class derivation


The ability to create new types that inherit properties from exiting types

Polymorphism
The ability of objects that belong to related classes to respond differently to the same operation Virtual functions

Introd to C/C++ (Section 2)

Week 9

C programming vs. Object Oriented Programming C programming


Structured Language
Decomposition of task into procedures (functions) Data is handled separate from procedures Prone to errors because of separation between data and functions

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

Introd to C/C++ (Section 2)

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;}

Introd to C/C++ (Section 2)

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)

int Age, Weight, Id;


public:

~
Destructor never take arguments
};

Destructors never return a value Destructor declaration

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}

cat::~cat(){ } // takes no action


There is only one destructor If you do not provide a destructor, the compiler will provide one

Introd to C/C++ (Section 2)

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; }

Introd to C/C++ (Section 2)

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;

Multiple inheritance derived from two or more classes


class A; class B; class C: public A, public B; //

Square
Circle Point Center(5);

Rectangle

Inheritance
is-a relationship

Introd to C/C++ (Section 2)

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;

class Y:private X; class A:protected B;

Introd to C/C++ (Section 2)

Week 9

12

Inheritance
Inheritance
members
Public memb Private memb Private Protected memb Protected

A public member is accessible


to a publicly derived class A private member is not accessible to derived classes A protected member function are fully visible to derived classes but otherwise private

A C C E S s

I N H E R I T s

public

Public

private

Private

Private

Private

Inheritance Limitations The following operations are not inherited


Constructors Destructors Overloaded operators

protected

Protected

Private

Protected

Introd to C/C++ (Section 2)

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 };

Introd to C/C++ (Section 2)

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 ???? }

Introd to C/C++ (Section 2)

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 <limits.h> - big and small numbers


INT_MAX 32767, INT_MIN -32767

#include <stdlib.h> - catch all


Random # generator

#include <time.h> - date and time #include <math.h> - sin, cos, tan, etc
Introd to C/C++ (Section 2) Week 9 16

Random Number Generators


#include <stdio.h> #include <stdlib.h> //contains the function prototype for rand( ) int main( ) { int i, seed; printf("Enter random number seed prime #\n"); scanf("%d", &seed); srand(seed); // init random number generatoor for(i = 0; i < 5; i++) printf("%12d", rand( )); printf("\n ------- Normalized Random Numbers ----\n"); for(i = 0; i < 5; i++) printf("%12d", rand( )/32767); printf("\n"); } [solowiejczyk@sweng191 Jed]$ !ma make Random cc Random.c -o Random [solowiejczyk@sweng191 Jed]$ ./Random Enter random number seed prime # 1 1804289383 846930886 1681692777 1714636915 1957747793 ------- Normalized Random Numbers ---12947 21969 50348 18204 36306 [solowiejczyk@sweng191 Jed]$ ./Random Enter random number seed prime # 3 1205554746 483147985 844158168 953350440 612121425 ------- Normalized Random Numbers ---9488 36934 56669 58682 15126 [solowiejczyk@sweng191 Jed]$ ./Random Enter random number seed prime # 17 1227918265 3978157 263514239 1969574147 1833982879 ------- Normalized Random Numbers ---14913 7070 31857 43387 59267 [solowiejczyk@sweng191 Jed]$

Introd to C/C++ (Section 2)

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 }

Introd to C/C++ (Section 2)

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

temp.next = X1.next X1.next = &X4; X4.next = temp.next X4.value = 12;

Introd to C/C++ (Section 2)

Week 9

20

Binary Tree Structures


Binary tree is a data structure in which each node has at most

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

Introd to C/C++ (Section 2)

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

Das könnte Ihnen auch gefallen