1 / 30

C++ Classes

C++ Classes. Compiling C++ programs Input & output Class definition Member function definitions Utility functions Constructors Destructors Other member functions. C++. C++ is an enhanced version of C Object-oriented-programming capabilities Other improvements on C features

Télécharger la présentation

C++ Classes

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. C++ Classes • Compiling C++ programs • Input & output • Class definition • Member function definitions • Utility functions • Constructors • Destructors • Other member functions

  2. C++ • C++ is an enhanced version of C • Object-oriented-programming capabilities • Other improvements on C features • Is a “superset” of C • Can compile C programs with C++ compiler • Development • Bjarne Stroustrupat Bell Labs in early 1980’s • From C & Simula-67 • Originally called “C with classes” • Later changed to “C++”

  3. Compiling C++ Programs • For C++ files, end with “.cpp” • In UNIX, use “g++” compiler % g++ program.cpp % ./a.out or: % g++ program.cpp –o output % ./output

  4. Makefile in C++ • Save following as “makefile” output: program.o <tab>g++ program.o -o output <blank line> program.o: program.cpp <tab>g++ -c program.cpp <blank line> • Type in “make” to run the makefile • % make • g++ -c program.cpp • g++ program.o -o output • % ./output

  5. //A program that adds 2 integers (add.cpp) #include <iostream> using namespace std; int main(){ int int1 = 0; cout << "Enter an integer: "; cin >> int1; int int2 = 0; cout << "Enter another integer: "; cin >> int2; int sum = int1 + int2; cout<<int1<<"+"<<int2<<"="<<sum<<endl; return 0; }

  6. Header Files & namespace #include <iostream> • Preprocessor directive • Input/output stream header file • List of standard library header files (p. 533) • For programmer-defined header files • #include “myHeaderFile.h” using namespace std; • Standard C++ library namespace (used to prevent overlapping names)

  7. Output & Input cout << "Enter an integer: "; • Output values to the screen • Standard output stream (cout), or “see-out” • Stream insertion operator (<<), or “put to” cin >> int1; • Obtain a value from the keyboard • Standard input stream (cin), or “see-in” • Stream extraction operator (>>), or “get from”

  8. C & C++ Differences • C: procedural programming language • Programming is action-oriented • Function is basic unit of programming

  9. C & C++ Differences • C++: object-oriented programming language • Programming is object-oriented • Class (a user-defined data type) is basic unit of programming • Attributes (data members) • Behaviors or operations (member functions) • Objects (variables) are created (instantiated) from the class • Regular variables (char, int, double, etc.) are instances of built-in data types

  10. //Fraction class definition (ADT - abstract data type) class Fraction{ public://accessible anywhere in program //Constructor initializes each data member Fraction(){ num = 0; den = 1; } //Set a new Fraction value & check data void set(int n , int d ){ if(d == 0) d = 1; if(d < 0) {d = -d; n = -n;} num = n; den = d; } //Print a Fraction void print() const{ cout << num << " / " << den; } private: //accessible only to member functions intnum; //data member int den; //data member };//terminate class definition with a semicolon

  11. Member Access Specifiers • public: • Any data member or data function declared after this is accessible anywhere in the program • private: • Any data member or data function declared after this is only accessible to member functions of the class • If no specifiers are declared, then the default is private • Can list specifiers in any order • protected: • Used for inheritance

  12. Constant (const) • Principle of least privilege • Users should be given no more privilege than necessary to perform a job • Good software engineering • Function definition void print() const{ cout<<num<<"/"<<den<<endl; } • Const member functions cannot modify the object’s data members (not allowed by compiler)

  13. Driver Program // Driver program to test class Fraction void main(){ //instantiate object f1 of class Fraction Fraction f1; f1.print(); // 0/1 //set the data Fraction f2; f2.set( 13, -27); f2.print(); // -13/27 //attempt invalid data Fraction f3; f3.set( 99, 0); f3.print(); // 99/1 } //See complete program at fraction.cpp

  14. Accessing Class Members /*Use accessor functions to change or access class member data (See access.cpp)*/ class Fraction { private: int num, den; public: Fraction(){num = 0; den = 1; } void print() const{cout << num << "/" << den;} void setNum(int n){num = n;} void setDen(int d){if(d==0)d=1; den = d;} int getNum(){return num;} int getDen(){return den;} };

  15. Driver Program // Driver program to test class Fraction int main(){ //set & get the data Fraction f2; f2.setNum(13); f2.setDen(27); cout<<"f2's numerator is:"<<f2.getNum()<<endl; cout<<" f2's denominator is:"<<f2.getDen()<<endl; return 0; } //Fraction f2's numerator is: 13 //Fraction f2's denominator is: 27

  16. Utility Functions • Not all member functions are public • Utility functions are private • Also called a “helper function” • Supports the operation of member functions • Not intended to be used by the clients of a class • Cannot use in the main() function

  17. Utility Functions //See utility.cpp class Fraction { public: ... void set( int n = 0, int d = 1){ if(d==0) d = 1; if(d < 0) {d = -d; n = -n;} num = n; den = d; reduce(); } private: int num, den; void reduce(){...} };

  18. Utility Functions //Finds GCD using Euclid's algorithm (utility.cpp) ... void reduce(){ int a = num; int b = den; while (b!=0){ int temp = a % b; a = b; b = temp; } num = num / a; den = den / a; } ... void main(){ Fraction f3; f3.set(6, 4); f3.print(); // 3/2 }

  19. Function Overloading • Functions have same name, different parameters #include <iostream> using namespace std; int square(int); double square(double); int main(){ cout<<"square = "<<square(3)<<endl; //square = 9 cout<<"square = "<<square(3.3)<<endl; //square = 10.89 return 0; } int square(int a){return a*a;} double square(double a){return a*a;} //See overload.cpp

  20. Constructors • A constructor is a class member function with the same name as its class • Used to initialize the class data members • Can have several overloaded constructors to initialize data members in different ways • Data to be initialized is put in parenthesis to the right of the object’s name

  21. //Example of 3 overloaded constructors class Fraction { int num, den; //default is "private:" public: Fraction(){ cout<<"constructor1"<<endl; num = 0; den = 1; } Fraction(int n) { cout<<"constructor2"<<endl; num = n; den = 1; } Fraction(int n, int d) {cout<<"constructor3"<<endl; num = n; den = d; } }; void main(){ Fraction f1, f2(2), f3(3,4); Fraction f[5] = {Fraction(), Fraction(6), Fraction(7,8)}; } • What is the output? • See constructors.cpp

  22. Reference Variables • Used as an alias for other variables • It is an automatically dereferenced pointer //see ref.cpp #include <iostream> using namespace std; int main(){ int a = 7; int &b = a; /*put "&" in front of reference variable when declaring it*/ a++; cout<<"a="<<a<<" b="<<b<<endl; return 0; } //a=8 b=8

  23. Reference Variables • Used in functions for call-by-reference #include <iostream> using namespace std; void square(int &); int main(){ int c = 2; cout<<"c="<<c<<endl; //c=2 square(c); cout<<"c="<<c<<endl; //c=4 return 0; } void square(int &d){ d = d * d; }

  24. Copy Constructor • Called in three cases • When initializing an object in a program with parenthesis Fraction a; Fraction b(a); • When initializing an object in a program with the equals sign (Note: this is not the default assignment operator) Fraction a; Fraction b = a; • When passing-by-value to a function void foo(Fraction f){...}

  25. Copy Constructor • Can create your own copy constructor Fraction(const Fraction &f){ num=f.num; den=f.den; } • Otherwise the computer will create one for you • By default, performed by memberwise copy • Each data member of one object is copied to another object’s data members • Can cause problems with dynamically allocated data members (such as linked list) • Example code: copy.cpp

  26. Destructors • A destructor is a class member function with the same name as its class with a tilde (~) character in front of it • Called when an object is “destroyed” • When program execution leaves the scope in which the object of that class was instantiated • For global objects & static objects, when the program ends execution • Performs termination housekeeping so memory can be returned to the system • Useful for dynamically allocated data members (such as linked list)

  27. class Fraction { //What’s the output? int num, den; public: //constructor Fraction(int n) { num = n; den = 1; cout<<"Constructor ("<<num<<"/"<<den<<")"<<endl; } //destructor ~Fraction() { cout<<"Destructor ("<<num<<"/"<<den<<")"<<endl; } }; Fraction f1(10); int main(){ Fraction f2(20); { Fraction f3(30); static Fraction f4(40); { Fraction f5(50); } } return 0; } //See destructor.cpp

  28. Other Member Functions • We can create any function that we wish for a class • For example, add(), subtract, multiply(), and divide() function for class Fraction • See math.cpp Fraction add(const Fraction &f){ int num3 = num * f.den + den * f.num; int den3 = den * f.den; Fraction f3(num3, den3); f3.reduce(); return f3; }

  29. Passing Parameters • When passing a parameter to a method • Call-by-reference more efficient than call-by-value • Call-by-value creates a “local copy” of the variable with the “copy constructor” • Call-by-reference simple maintains a “place-holder”, as the actual changes are make to the variable in the calling routine • Not a big deal with simple data types (int, etc.) • Can be a big deal with user-defined data types (that contain a lot of data)

  30. For Improved Efficiency • When possible, make parameters call-by-reference • Can speed up execution for some data types • If the data members should not be changed, use “const” reference parameters • Can help to prevent programming bugs • Principle of least privilege • A function should not be able to change a parameter if it is not necessary

More Related