1 / 22

What is C++?

What is C++?. (almost) A superset of C: (almost) every valid C program is a valid C++ program (with the same effect and efficiency). An OO language with classes, objects, methods, (multiple!) inheritance. A modern language with exceptions, templates, references.

atira
Download Presentation

What is C++?

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. What is C++? • (almost) A superset of C: (almost) every valid C program is a valid C++ program (with the same effect and efficiency). • An OO language with classes, objects, methods, (multiple!) inheritance. • A modern language with exceptions, templates, references. • Among the OO languages C++ is certainly: • The one that can create the fastest running applications. • Not the one that allows the fastest development of applications.

  2. A Clock class interface // file clock.h #ifndef CLOCK_H #define CLOCK_H class Clock { public: // Public operations. void set (int hour, int min, int sec); int readHour (void) { return h; } int readMin (void) { return m; } int readSec (void) { return s; } void write (bool writeSec = true); void tick (void); private: // Internal representation of the time. int h, m, s; }; #endif Specification in .h file, implementation in .cpp file.

  3. A Clock class specification // file clock.h #ifndef CLOCK_H #define CLOCK_H class Clock { public: // Public operations. void set (int hour, int min, int sec); int readHour (void) { return h; } int readMin (void) { return m; } int readSec (void) { return s; } void write (bool writeSec = true); void tick (void); private: // Internal representation of the time. int h, m, s; }; #endif There is no user-defined constructor: hence the compiler will define one without parameters, that does essentially nothing. So we need an init function to set the initial values. This is bad style, we will do better lateron.

  4. A Clock class specification // file clock.h #ifndef CLOCK_H #define CLOCK_H class Clock { public: // Public operations. void set (int hour, int min, int sec); int readHour (void) { return h; } int readMin (void) { return m; } int readSec (void) { return s; } void write (bool writeSec = true); void tick (void); private: // Internal representation of the time. int h, m, s; }; #endif Simple methods, that are unlikely ever to change, can be defined in the class declaration. Parameters to C++ function (methods are functions) can have a default parameter. Do not forget this final ‘;’ !!!

  5. A Clock class implementation // file Clock.cpp #include <iostream > #include <iomanip> #include ”Clock.h” using namespace std; // The clock is set // to the time hour:min:sec void Clock::set ( int hour, int min, int sec ){ h = hour; m = min; this->s = sec; } Always include the definition of the class. The function header is the same as in the .h file, except for the Clock:: before the name. Attributes are automatically visible. You can use this->, but why clutter the code? (cpp file continues in next sheet)

  6. A Clock class implementation Three lines needed for formatted character I/O. (cpp file continues from previous sheet) #include <iostream > #include <iomanip> using namespace std; The default value of the parameter is NOT repeated here. // Write the time in the // format hh:mm (writeSec==true) // or hh:mm:ss (writeSec==false) void Clock::write( bool writeSec ) { cout << setw (2) << setfill ('0') << h << ':' << setw (2) << setfill ('0') << m; if (writeSec){ cout << ':' << setw (2) << setfill ('0') << s; } } C++’s version of sprintf: just ‘shift everything into cout’.

  7. A Clock class implementation (cpp file continues from previous sheet) // Advance the clock one second, 24h-style void Clock::tick ( void ){ s = (s + 1) % 60; if( s == 0 ){ m = (m + 1) % 60; if( m == 0 ){ h = (h + 1) % 24; } } }

  8. Using the Clock class #include ”Clock.h” void f( void ){ Clock c; c.set( 15, 50, 38 ); c.write(); Clock * pC = new Clock; pC->set(15, 55, 43); for (int i = 0; i < 33; i++) pC->tick(); pC->write(); delete pC; } (1) Use the class name as type in a variable declaration. The constructor is called. (2) Use the new operator to allocoate a Clock on the heap. The constructor is called. Objects allocated by (2) must be deallocated explicitly. Objects allocated by (1) are deallocated implicitly. Note: NO ‘()’

  9. Constructors (Only) when you define none, the compiler will define a default constructor for you. It has no parameters, like this one: class Clock { public: // Constructors. Clock(); Clock( int hour, int min, int sec ); . . . }; Better combine allocation and initialisation, so we can pass initialisation parameters to the constructor. Notes: you can have as many constructors as you want; constructors have no return type, not even void!

  10. Constructors - implementation Constructor implementation, using assignments. Clock::Clock( void ){ h = m = s = 0; } Clock::Clock( int hour, int min, int sec ){ h = hour; m = min; s = sec; } • Alternative, using the int constructors in the initializer list. • This is the preferred way: • Efficient. • Can be used with constants. • Can be used when no default constructor is available. Clock::Clock( int hour, int min, int sec ): h(hour), m(min), s(sec) {}

  11. Constructors – use defaults! class Clock { public: Clock (); Clock ( int hour, int min, int sec ); }; Why write both(+ implementations)? When you can have the same effect with this: class Clock { public: Clock ( int hour = 0, int min = 0, int sec = 0 ): h(hour), m(min), s(sec) {} }; This effectively defines initializers with zero, one, two, and three parameters.

  12. Using the constructors Clock c1; Clock c2(12); Clock * pC1 = new Clock(15,45); Clock * pC2 = new Clock(16,10,15); c1.write(); c2.write(); pC1->write(); pC2->write(); On the stack On the heap 00.00.00 12.00.00 15.45.00 16.10.15

  13. An object can be an attribute This is called Compostition, somtimes Composition-aggregation

  14. A copy constructor • A constructor with its class type as argument, but const &, is called a copy-constructor. • This copy-constructor is called: • When an explicit copy is constructed • When a parameter is passed by value • When a class object is returned Flight( const Flight & f ); Why this ‘&’ ? This is not an assignment! Flight k(f); Flight k = f; Flight (char * nr, Clock dep, Clock arr ) Clock f( void ){ Clock c; . . . return c; } (note: NOT for an assignment!)

  15. The default copy constructor • When you don’t define a copy constructor, the compiler will define one. • This default copy constructor will: • Call the copy constructor for each attribute (with the value of the current attribute). • Build-in types like char, int, float, struct, and pointers have copy constructors that behave like their assignment operators: they do a bit-wise copying from the source to the destination.

  16. Flight class definition : destructor class Flight { public: // Constructors. Flight(){ no = new char [1]; no[0] = '\0'; } Flight( char flightNo[], int depH, int depM, int arrH, int arrM ); Flight( char flightNo[], Clock depT, Clock arrT ); // Copy constructor Flight( const Flight & f ); // Destructor ~Flight () { delete [] no; } // Public operations. void init( char flightNo[], int depH, int depM, int arrH, int arrM ); void delay( int min ); void writeInfo( void ); private: // Internal representation of a flight. char * no; Clock dep, arr; }; • A destructor is called automatically: • When an object leaves scope. • When an object is disposed.

  17. Flight class - constructors Flight::Flight(){ no = new char [1]; no[0] = '\0'; } Flight::Flight( char flightNo[], int depH, int depM, int arrH, int arrM ): dep( Clock( depH, depM, 0 ) ), arr( Clock( arrH, arrM ) ) { no = new char [ strlen( flightNo ) + 1 ]; strcpy( no, flightNo ); } Flight::Flight( char flightNo[], Clock depT, Clock arrT ): dep( depT ), arr( arrT ) { no = new char[ strlen( flightNo ) + 1 ]; strcpy( no, flightNo ); } Construct clocks, pass them Error? Array new Why +1 ?? Pass the clocks we got

  18. Flight class – init, delay void Flight::init( char flightNo[], int depH, int depM, int arrH, int arrM ){ no = new char[ strlen( flightNo ) + 1 ]; strcpy ( no, flightNo ); dep.set( depH, depM, 0 ); arr.set( arrH, arrM ); } void Flight::delay( int min ){ for( int i = 1; i <= min * 60; i++ ){ dep.tick (); } for( int j = 1; j <= min * 60; j++ ){ arr.tick (); } } Why not simply void Flight::init( char flightNo[], int depH, int depM, int arrH, int arrM ){ no = flightNo; dep.set( depH, depM, 0 ); arr.set( arrH, arrM ); }

  19. copy constructor (wrong) Flight::Flight( const Flight & f ) : dep( f.dep ), arr( f.arr ), no( f.no ) {} This is what the default copy constructor would do too. Let’s create a flight f, and a copy of it called g. Flight f("SK1853", 8, 10, 10, 55); Flight g(f); • This is what we get (a shallow copy). • Two problems: • Changing a flight’s name • Dealocation

  20. copy constructor (good) Flight::Flight( const Flight & f ) : dep( f.dep ), arr( f.arr ) { no = new char[ strlen( f.no ) + 1 ]; strcpy( no, f.no ); } Allocate a new string, copy the content. Now we get real individuals, not a Borg (deep copy).

  21. Consequences of a pointer attribute • Whenever you have a pointer attribute, you almost certainly need: • A constructor that initializes the pointer; each constructor must do so. • A copy constructor that creates a deep copy. • A destructor. • (next lesson) an assignment operator.

More Related