Presentation is loading. Please wait.

Presentation is loading. Please wait.

Console Programs Console programs are programs that use text to communicate with the use and environment – printing text to screen, reading input from.

Similar presentations


Presentation on theme: "Console Programs Console programs are programs that use text to communicate with the use and environment – printing text to screen, reading input from."— Presentation transcript:

1 Console Programs Console programs are programs that use text to communicate with the use and environment – printing text to screen, reading input from a keyboard. The way to compile a console program in C++ is as follows:

2 Integrated Development Environment (IDEs): Compiling and running console programs using different free IDEs: IDEPlatformConsole programs Code::blocksWindows/Linux/MacOS Compile console programs using Code::blocks Visual Studio ExpressWindows Compile console programs using VS Express 2013 Dev-C++Windows Compile console programs using Dev-C++

3 Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking. Missing casts that produce warnings in C produce errors in C++ the introduction of true O-O classes a formal inheritance mechanism in which derived classes can specialize parent classes formal support for polymorphic behavior in which a derived class may override a base class method simply by providing a method of the same name. support for function overloading in which there may be different implementations with a single function name.

4 Extensions to C (cont'd) an operator overloading mechanism that is analogous to function overloading the ability to pass parameters by reference in addition to the standard pass by value. yet another input/output library that may be used in addtion to standard and low level I/O.

5 Introduction to C++ extensions to C continued: – formal support for polymorphic behavior in which a derived class may override a base class method simply by providing a method of the same name. – support for function overloading in which there may be different implementations with a single function name. – an operator overloading mechanism that is analogous to function overloading – the ability to pass parameters by reference in addition to the standard pass by value. – yet another input/output library that may be used in addtion to standard and low level I/O

6 Interactive I/O using cin and cout C++ uses streams to perform input/output operations A stream is an object that allows a program to insert characters to it or extract characters from it. The standard input/output stream objects are defined in the header file iostream. must be included for any program that outputs data to the screen or inputs data from the keyboard using C++-style stream input/output.

7 Interactive I/O using cin and cout With you automatically get the following objects: cout – a predefined object of the ostream class that displays data to standard output ; corresponds to stdout. Used cin – a predefined object of the istream class that reads data from standard input; corresponds to stdin cerr – a predefined object of the ostream class that represents the standard error stream; corresponds to stderr. clog – a predefined object of the ostream class represents the standard logging stream; is associated with stderr. endl – outputs an end of line character and flushes the buffer.

8 Interactive I/O using cin and cout cout Accesses standard output (the screen) Used in conjunction with the insertion operator << Example cout << "Hello"; cout << " C++ is great!"; cout << endl;

9 Interactive I/O using cin and cout cin Accesses standard input (the keyboard) Used in conjunction with the extraction operator >> to obtain values from the keyboard. Example cin >> x; cin >> y; cin >> b;

10 Namespaces in C++ In C++, as in other languages, variables, functions, and objects are program entities that must have names. C++ uses namespaces to organize the names of program entities. Elements within a namespace may be accessed using the scope resolution operator (::). For example, std::cout refers to the cout stream that is a member of the std namespace. To avoid repeatedly having to type namespace qualifiers, C++ provides a directive called using, which creates an alias to some element of another namespace. For example: int sample() { using std::cout; cout<< "This is a test. " << std::endl; }

11 Namespaces in C++ For frequently-used namespaces, such as std, a special directive can be placed at the top of the file: using namespace std; This directive makes every element inside the std namespace available in the current (usually the global) namespace. using namespace std; int main() { cout<< "This is a test. " << endl; }

12 Class Generalization The class is a generalization of the C structure and can contain: data, as well as function (method) prototypes or full implementations accessibility controls (private, protected, public, friend) – private members of a class are accessible only from within other members of the class (or from their friends).; in general, data will be private. – protected members are accessible from members of their same class (and from their friends) but also from members of their derived classes.

13 Class Generalization accessibility controls (private, protected, public, friend) – public members are accessible from anywhere the object is visible; in general, our functions will be public. – friend functions can access private data in a class; not preferred by O-O purists, who claim that it is a hacker's way to compensate for bad design (which is often true!!)

14 Simple Example The example to the right defines a class (type) called Box. b1 and b2 are objects of the Box class. The class has five members: three data members of type double(width, length, and height), with private access and two member functions with public access: Box and volume. Note that only the function declarations are given, not their definitions. class Box { public: Box(); Box(int w, int l, int h); int volume(); void set_values(int w, int l, int h); private: int width; int length; int height; }; Box b1; // default. No () Box *b2;

15 Simple Example Notice the difference between the class name and the object name. Box is the class name (i.e. the type); whereas, b1 and b2 are objects of type Box. Box and b1 have the same relationship as int and x in the following declaration: int x; where int is the type name (the class) and a is the variable name (the object) class Box { public: Box(); Box(int w, int l, int h); int volume(); void set_values(int w, int l, int h); private: int width; int length; int height; }; Box b1; // default. No () Box *b2;

16 Simple Example After the declarations of Box and b2, within the body of the program, we can refer to any of the public members of the object b2 as if they were normal functions or normal variables just by putting the object's name followed by a dot (.) and then the name of the member, all very similar to what we did with structures. For example Box b2(2, 5, 7); double v = b2.volume(); b2.set_values(3, 4, 5); class Box { public: Box( int w, int l, int h); double volume(); void set values(int w, int l, int h); private: int width; int length; double height; }; Box b1; // default. No () Box b2(2, 5, 7); Box *b3;

17 Simple Example In the case of b3, we must first dynamically create a Box object by using the new operator: b3 = new Box(2, 5, 7); and invoke volume and set_values by double v = b3->volume; v->set_values(5, 3, 8); class Box { public: Box(); Box(double w, double l, double h); double volume(); private: double width; double length; double height; }; Box b1; // default. No () Box b2(2, 5, 7); Box *b3;

18 Simple Example The only members of b1 or b2 that we cannot access from the body of our program outside the Box class are length, width, and height, since they have private access and they can only be referenced from within other members of the Box class. /* CPSC 2100 box.h specification file for the Box class */ class Box { public: Box(); Box(double w, double l, double h); double volume(); private: double width; double length; double height; }; Box b1; // default. No () Box b2(2, 5, 7); Box *b3;

19 Specification and Implementation files class specification file - often used to contain the class declarations. class implementation file - often used to contain the implementation code for the method(s) of a class. This file is also referred to as a source file. In addition to the specification file and the implementation file, you will also need a main function for testing every method of your class. We generally call this program the test driver.

20 Complete Example // class example // box.h (specification file) class Box { public: Box(); Box(int w, int l, int h); ~Box(); int volume(); void set_values(int w, int l, int h); private: int width; int length; int height; }; // test driver main.c #include using namespace std; int main() { Box b1; // default. No () Box b2(4, 3, 5); // statically allocated Box *b3 = new Box(5, 7, 2); // dynamically alloc. b1.set_values(5, 7, 3); cout << "b1 volume = " << b1.volume() << endl; cout << "b2 volume = " << b2.volume() << endl; cout volume() << endl; } // box.cpp (implementation file) Box::Box() { width = 0; length = 0; height = 0; } Box::Box(int w, int l, int h) { width = w; length = l; height = h; } int Box::volume() { return (length * width * height); } void Box::set_values(int w, int l, int h) { width = w; length = l; height = h; }

21 Complete Example // test driver main.c #include using namespace std; int main() { Box b1; // default. No () Box b2(4, 3, 5); // statically allocated Box *b3 = new Box(5, 7, 2); // dynamically allocated b1.set_values(5, 7, 3); cout << "b1 volume = " << b1.volume() << endl; cout << "b2 volume = " << b2.volume() << endl; cout volume() << endl; } Another thing to notice in the above program are the three instances or objects: b1, b2, and b3. Each one has its own member variables and member functions. Output: b1 volume = 105 b2 volume = 60 b3 volume = 70

22 Complete Example // test driver main.c #include #include "box.h" using namespace std; int main() { Box b1; // default. No () Box b2(4, 3, 5); // statically allocated Box *b3 = new Box(5, 7, 2); // dynamically allocated b1.set_values(5, 7, 3); cout << "b1 volume = " << b1.volume() << endl; cout << "b2 volume = " << b2.volume() << endl; cout volume() << endl; } Also notice that the call b1.volume() does not give the same result as the call b2.volume() or b3->volume(). This is because each object of class Box has its own variables width, length, and height. That is the basic concept of object-oriented programming: Data and functions are both members of the object. Output: b1 volume = 105 b2 volume = 60 b3 volume = 70

23 Complete Example // test driver main.c #include #include "box.h" using namespace std; int main() { Box b1; // default. No () Box b2(4, 3, 5); // statically allocated Box *b3 = new Box(5, 7, 2); // dynamically allocated b1.set_values(5, 7, 3); cout << "b1 volume = " << b1.volume() << endl; cout << "b2 volume = " << b2.volume() << endl; cout volume() << endl; } We no longer use sets of global variables that we pass from one function to another as parameters, but instead we handle objects that have their own data and functions embedded as members. Notice that we have not had to give any parameters in any of the calls to b1.volume(), b2.volume(), or b3->volume. These member functions directly used the data members of their respective objects b1, b2, and b3. Output: b1 volume = 105 b2 volume = 60 b3 volume = 70

24 Constructors and Destructors Objects generally need to initialize variables or assign dynamic memory during the creation process in order to become operative and to avoid returning unexpected values during execution. A class can include a special function, called a constructor, that is automatically called whenever a new object of the class is created. The constructor function must have the same name as the class and cannot have a return type - not even void.

25 Constructors and Destructors In the class specification below, the Box class includes two constructors: Box() and Box(int w, int l, int h) // box.h (specification file) class Box { public: Box(); Box(int w, int l, int h); ~Box(); int volume(); void set_values(int w, int l, int h); private: int width; int length; int height; }; In main(), notice how the arguments are passed to the constructor at the moment the objects of the Box class are created. int main() { Box b1; Box b2(4, 3, 5); Box *b3 = new Box(5, 7, 2); b1.set_values(5, 7, 3); cout << "b1 volume = " << b1.volume() << endl; cout << "b2 volume = " << b2.volume() << endl; cout volume() << endl; } Box b2(4, 3, 5); // statically allocated Box *b3 = new Box(5, 7, 2); // dynamically allocated

26 Constructors and Destructors // box.h (specification file) class Box { public: Box(); Box(int w, int l, int h); ~Box(); int volume(); void set_values(int w, int l, int h); private: int width; int length; int height; }; Constructors cannot be called explicitly as if they were regular member functions. They are only executed when a new object of the class is created. You can also see how neither the constructor prototype declaration (within the class) nor the latter constructor definition includes a return value -- not even void. int main() { Box b1(); Box b2(4, 3, 5); Box *b3 = new Box(5, 7, 2); b1.set_values(5, 7, 3); cout << "b1 volume = " << b1.volume() << endl; cout << "b2 volume = " << b2.volume() << endl; cout volume() << endl; }

27 Destructor // box.h (specification file) class Box { public: Box(); Box(int w, int l, int h); ~Box(); int volume(); void set_values(int w, int l, int h); private: int width; int length; int height; }; Constructors cannot be called explicitly as if they were regular member functions. They are only executed when a new object of the class is created. You can also see how neither the constructor prototype declaration (within the class) nor the latter constructor definition includes a return value -- not even void. int main() { Box b1; Box b2(4, 3, 5); Box *b3 = new Box(5, 7, 2); b1.set_values(5, 7, 3); cout << "b1 volume = " << b1.volume() << endl; cout << "b2 volume = " << b2.volume() << endl; cout volume() << endl; }

28 Constructors and Destructors Objects generally need to initialize variables or assign dynamic memory during the creation process in order to become operative and to avoid returning unexpected values during execution. A class can include a special function, called a constructor, that is automatically called whenever a new object of the class is created. The constructor function must have the same name as the class and cannot have a return type - not even void. In the class specification below, the Box class includes two constructors: Box() and Box(int w, int l, int h) // box.h (specification file) class Box { public: Box(); Box(int w, int l, int h); ~Box(); int volume(); void set_values(int w, int l, int h); private: int width; int length; int height; };

29 Complete Example Box::Box() { width = 0; length = 0; height = 0; } Box::Box(int w, int l, int h) { width = w; length = l; height = h; } int Box::volume() { return (length * width * height); } void set_values(int w, int l, int h) { width = w; length = l; height = h; } The cope resolution operator (::) specifies the class to which the member being declared belongs, granting exactly the same scope properties as if this function definition were directly included within the class definition. For example, in the function, set_values(), for the previous code, we were able to use the variables width, length, and height, which are private members of class Box, which means they are only accessible from members of the Box class.

30 Complete Example Box::Box() { width = 0; length = 0; height = 0; } Box::Box(int w, int l, int h) { width = w; length = l; height = h; } int Box::volume() { return (length * width * height); } void set_values(int w, int l, int h) { width = w; length = l; height = h; } The members width, length, and height have private access (remember that if nothing else is said, all members have private access. By declaring them private, we deny access to them from anywhere outside the class, except for friend functions, to set values for those members within the object. Perhaps in a simple example as the Box class, it is difficult to see any utility in protecting these three variables, but in greater projects, it may be very important that values cannot be modified in an unexpected way (unexpected from the point of view of the object).

31 Complete Example Box::Box() { width = 0; length = 0; height = 0; } Box::Box(int w, int l, int h) { width = w; length = l; height = h; } int Box::volume() { return (length * width * height); } void set_values(int w, int l, int h) { width = w; length = l; height = h; } The members width, length, and height have private access (remember that if nothing else is said, all members have private access. By declaring them private, we deny access to them from anywhere outside the class, except for friend functions, to set values for those members within the object. Perhaps in a simple example as the Box class, it is difficult to see any utility in protecting these three variables, but in greater projects, it may be very important that values cannot be modified in an unexpected way (unexpected from the point of view of the object).

32 Complete Example Box::Box() { width = 0; length = 0; height = 0; } Box::Box(int w, int l, int h) { width = w; length = l; height = h; } int Box::volume() { return (length * width * height); } void set_values(int w, int l, int h) { width = w; length = l; height = h; } The destructor fulfills the opposite functionality. It is automatically called when an object is destroyed, either because its scope of existence has finished or because it it is an object dynamically assigned and it is released using the operator delete.

33 Complete Example Box::Box() { width = 0; length = 0; height = 0; } Box::Box(int w, int l, int h) { width = w; length = l; height = h; } int Box::volume() { return (length * width * height); } void set_values(int w, int l, int h) { width = w; length = l; height = h; } The destructor must have the same name as the class, but preceded with a tilde sign (~) and it must not return a value. The use of destructor is especially suitable when an object assigns dynamic memory during its lifetime and at the moment of being destroyed or released when we went to release the memory that hee,object remembered.

34 Overloading Like any other function, a constructor can also be overloaded with more than one function that has the same name but different types or number of parameters, as we have seen with the Box class. For overloaded functions, the compiler will call the one whose parameters match the arguments used in the function call. In the case of constructors, which are automatically called when an object is created, the one executed is the one that matches the arguments passed when the object is declared

35 Overloading // box.h (specification file) class Box { public: Box(); Box(int w, int l, int h); ~Box(); int volume(); void set_values(int w, int l, int h); private: int width; int length; int height; }; In the above code, b1 was declared with no arguments, so it has been initialized with the constructor that has no parameters (this is called a default constructor), which initializes width, length, and height to 0. b2 was declared with three arguments, so it has been initialized with the constructor that receives three parameters. int main() { Box b1; Box b2(4, 3, 5); Box *b3 = new Box(5, 7, 2); b1.set_values(5, 7, 3); cout << "b1 volume = " << b1.volume() << endl; cout << "b2 volume = " << b2.volume() << endl; cout volume() << endl; }

36 Default Constructors If you do not declare any constructors, the compiler assumes the class to have a default constructor with no parameters; therefore, after declaring a class like the following: the compiler provides a default constructor with base values assigned to the instance variables. class CPlusExample { public: void multiply(int n, int m); private: int a; int b; int c: }

37 Default Constructors The multiply function will then be defined as class CPlusExample { public: void multiply(int m, int n); private: int a; int b; int c: } void multiply(int m, int n) { a = m; b = n; c = a * b; }

38 Default Constructors But as soon as you declare your own constructor for a class, the compiler no longer provides an implicit default constructor. So, for the following declaration, you have to declare all objects of that class according to the constructor prototype you defined for them. class CPlusExample { public: CPlusExample(int m, int n); void multiply(); private: int a; int b; int c: }

39 Default Constructors For example, here we have declared a constructor that has two parameters. The following declaration would be correct: But is not, because there is no default constructor. class CPlusExample { public: CPlusExample(int m, int n); void multiply(); private: int a; int b; int c: } CPlusExample ex(3, 4); CPlusExample ex;

40 Default Constructors Since we have declared a constructor class CPlusExample { public: CPlusExample(int m, int n); void multiply(); private: int a; int b; int c: }

41 Default Constructors But as soon as you declare your own constructor for a class, the compiler no longer provides an implicit default constructor. So you have to declare all objects of that class according to the constructor prototype you defined for them. Here we have declared a constructor that two parameters of type int. The following object declaration would be correct But is not, since there is no default constructor. class CPlusExample { public: int a, b, c: CPlusExample(int n, int n); void multiply(int n, int m); } CPlusExample ex(2, 8); CPlusExample ex;;

42 File I/O scanf, fscanf, printf and fprint f are still available C++ has another I/O library To read from a file or write to a file using C++-sytle I/O, you need to include the header file. For an input file ifstream inFile("data.dat"); // opens data.txt for input or ifstream inFile; inFile.open("data.dat");

43 File I/O For an output file ofstream outFile("results.out"); // opens results.out or ofstream outFile; outFile.open("results.out"); // opens results.out

44 File I/O Once the files are open, you can use > inFile>> x >> y; outFile<< x + y << endl; Use close() to close the file inFile.close(); outFile.close();

45 File I/O Example #include using namespace std; int main() { int x; int sum = 0; ifstream inFile("data.in"); // opens data.in ofstream outFile; outFile.open("results.out"); // opens results.out inFile>> x; while(!inFile.eof()) { sum = sum + x; inFile >> x; } outFile << "sum = " << sum << endl; inFile.close(); outFile.close(); return 0; }


Download ppt "Console Programs Console programs are programs that use text to communicate with the use and environment – printing text to screen, reading input from."

Similar presentations


Ads by Google