clarity. In the first form, the access specifier public : is needed to {

Size: px
Start display at page:

Download "clarity. In the first form, the access specifier public : is needed to {"

Transcription

1 Structure Time CSC 211 Intermediate Programming Classes in C++ // Create a structure, set its members, and print it. struct Time // structure definition int hour; // 0-23 int minute; // 0-59 int second; // 0-59 ; void printmilitary( const Time & ); // prototype void printstandard( const Time & ); // prototype 1 2 Time dinnertime; // variable of new type Time // set members to valid values dinnertime.hour = 18; dinnertime.minute = 30; dinnertime.second = 0; cout << "Dinner will be held at "; printmilitary( dinnertime ); cout << " military time,\nwhich is "; printstandard( dinnertime ); cout << " standard time.\n"; // set members to invalid values dinnertime.hour = 29; dinnertime.minute = 73; cout << "\ntime with invalid values: "; printmilitary( dinnertime ); cout << endl; 3 // Print the time in military format void printmilitary( const Time &t ) cout << ( t.hour < 10? "0" : "" ) << t.hour << ":" << ( t.minute < 10? "0" : "" ) << t.minute; // Print the time in standard format void printstandard( const Time &t ) cout << ( ( t.hour == 0 t.hour == 12 )? 12 : t.hour % 12 ) << ":" << ( t.minute < 10? "0" : "" ) << t.minute << ":" << ( t.second < 10? "0" : "" ) << t.second << ( t.hour < 12? " AM" : " PM" ); Output Dinner will be held at 18 : 30 military time, Which is 6 : 30 : 00 PM standard time. Time with invalid values : 29 : 73 4 Implementing a Time Abstract Data Type with a Classes Notes Class Declaration By default, members are private; thus, in the second form, the Form 1 access specifier is optional, but is commonly included for class ClassName clarity. In the first form, the access specifier is needed to specify the public section of the class and private : to specify where the public section ends and the private section begins. Declarations of public members Although not commonly done, a class may have several private and public sections; the keyword private : marks the beginning of Declarations of private members each private section and the keyword marks the beginning ; Form 2 of each public section. class ClassName The data members are normally placed in the private section(s) of a class and the function members in the public section(s). // optional Private members can be accessed only by member functions and by Declarations of private members friend functions. Declarations of public members Public members can be accessed by both member and nonmember ; 5 functions. 6 1

2 Notes cont d OOP encapsulates data (attributes) and functions (behavior) into packages called classes. Out of a class, a programmer can create an object. One class can be reused many times to make many objects of the same class. Classes have the property of information hiding. This means that although class objects may know how to communicate with one other across well-defined interfaces, classes are not normally allowed to know how other classes are implemented implementation details are hidden within the classes themselves. In C and other procedural programming languages, programming tends to be action-oriented, whereas in C++ programming it is object-oriented. In C, the unit of programming is the function. In C++, the unit of programming is the class from which objects are eventually instantiated (created). Notes cont d C++ programmers concentrate on creating their own user-defined types called classes. Classes are also referred to as programmerdefined types. Each class contains data as well as the set of functions that manipulate the data. The data components of a class are called data members. The function components of a class are called member functions ( or methods in other OOLanguages ). Just as an instance of a builtin type such as int is called a variable, an instance of a class is called an object. Classes in C++ are a natural evolution of the C notion of struct. Classes enable the programmer to model objects that have attributes (represented as data members ) and behaviors or operations (represented as member functions). Types containing data members and member functions are defined in C++ using the keyword class. Member functions are sometimes called methods in other OO programming languages, and are invoked in response to messages sent to an object. A message corresponds to a member-function C programmers concentrate on writing functions. Data is certainly important, but the view is that data exists primarily in call sent from one object to another or sent from a function to an support of the actions that functions perform. 7 object. 8 Similarities: Structures and Classes Both can be used to model objects with different attributes represented as data members. They can thus be used to organize nonhomogeneous data sets. They have essentially the same syntax. Differences: Members of a class by default are private (cannot be accessed by nonmember functions). Members of a struct by default are public (can be accessed by nonmember functions via the dot operator. Because the data in a struct is public by default, we think of a struct as a passive data structure. The operations that are performed on a struct are usually global functions to which the struct is passed as a parameter. Although a struct may have member functions, they are seldom defined. In contrast, a class is an active data structure where the operations defined on the data members are member functions of the class. 9 Here is the equivalent class representation of a struct complex. //Show complex number in both struct and class representations //Implement as a struct (default is public) struct complex void assign(double r, double i); void print() cout << real << " + " << imag << "i "; double real, imag; ; inline void complex::assign(double r, double i = 0.0) real = r; imag = i; 10 Class complex Class complex cont d //Make public and private explicit in class class complex_c1 //need to know style- our preference void assign(double r, double i); void print() cout << real << " + " << imag << "i "; double real, imag; ; inline void complex_c1::assign(double r, double i = 0.0) real = r; imag = i; 11 //Implement as a class (default is private) class complex_c2 //old private-implicit style double real, imag; void assign(double r, double i); void print() cout << real << " + " << imag << "i "; ; void complex_c2::assign(double r, double i = 0.0) real = r; imag = i; 12 2

3 Test file main() complex a; complex_c1 b; complex_c2 c; a.assign(1.1, 2.2); b.assign(3.3, 4.4); c.assign(5.5, 6.6); cout << "\ncomplex from struct definition: "; a.print(); cout << "\ncomplex from class definition: "; b.print(); cout << "\ncomplex from explicit class definition: "; c.print(); Example - Fig. 6.3 Once a class has been defined, the class name can be used to declare objects of that class. Fig. 6.3 contains a simple definition for class Time. class Time Time ( ) ; void settime (int, int, int) ; void printmilitary ( ) ; void printstandard ( ) ; private : int hour ; // 0 23 int minute ; ; // 0 59 int second ; // 0 59 ; Discussions Our Time class definition begins with the keyword class. The body of the class definition is enclosed within left and right braces. The class definition terminates with a semicolon. Our Time class definition and our Time structure definition each contain integer members hour, minute and second. The and private : labels are called member accessed specifiers. Any data member or member function declared after member specifier public is accessible wherever the program has access to an object of class Time. Any data member or member function declared after member access specifier private is accessible only to member functions of the class. Member access specifiers are always followed by a colon ( : ) and can appear multiple times and in any order in a class definition. 15 Discussions cont d Notice the member function with the same name as the class; it ia called a constructor function of that class. A constructor is a special member function that initializes the data members of a class object. A class s constructor function is called automatically when an object of that class is created. Note that no return type is specified for the constructor. The three integer members appear after the private member access specifier. This indicates that these data members of the class are only accessible to member functions and to friend of the class. Thus, the data members can only be accesses by the four functions whose prototypes appear in the class definition (or by friends of the class). Data members are normally listed in the private portion of a class and member functions are normally listed in the public portion. It is possible to have private member functions as well as public data, but it is considered a poor programming practice. 16 Discussions cont d Example Once the class has been defined, it can be used as a type in declarations as follows: Fig. 6.3 uses the Time class. The program instantiates a single object of class Time called t. When Time sunset, arrayoftime[5], *pointertotime, &dinnertime = sunset ; // object of type Time // array of Time objects // pointer to a Time object // reference to a Time object an object is instantiated, the Time constructor is called automatically and explicitly initializes each private data member to 0. The time is then printed in military and standard formats to confirm that the members have been properly initialized. The time is then set using the settime member function and is printed The class name becomes a new type specifier. There may be many objects of a class, just as there may be many variables of a type such as int. again in both formats. Then settime attempts to set the data members to invalid values, and the time is again printed in both formats

4 // Fig. 6.3 // Time class. // Time abstract data type (ADT) definition class Time Time(); // constructor void settime( int, int, int ); // set hour, minute, second void printmilitary(); // print military time format void printstandard(); // print standard time format int hour; // 0-23 int minute; // 0-59 int second; // 0-59 ; // Time constructor initializes each data member to zero. // Ensures all Time objects start in a consistent state. Time::Time() hour = minute = second = 0; 19 // Set a new Time value using military time. Perform validity // checks on the data values. Set invalid values to zero. void Time::setTime( int h, int m, int s ) hour = ( h >= 0 && h < 24 )? h : 0; minute = ( m >= 0 && m < 60 )? m : 0; second = ( s >= 0 && s < 60 )? s : 0; // Print Time in military format void Time::printMilitary() cout << ( hour < 10? "0" : "" ) << hour << ":" << ( minute < 10? "0" : "" ) << minute; // Print Time in standard format void Time::printStandard() cout << ( ( hour == 0 hour == 12 )? 12 : hour % 12 ) << ":" << ( minute < 10? "0" : "" ) << minute << ":" << ( second < 10? "0" : "" ) << second << ( hour < 12? " AM" : " PM" ); 20 // Driver to test simple class Time Output Time t; // instantiate object t of class Time cout << "The initial military time is "; t.printmilitary(); cout << "\nthe initial standard time is "; t.printstandard(); t.settime( 13, 27, 6 ); cout << "\n\nmilitary time after settime is "; t.printmilitary(); cout << "\nstandard time after settime is "; t.printstandard(); t.settime( 99, 99, 99 ); // attempt invalid settings The initial military time is 00 : 00 The initial standars time is 12 : 00 : 00 AM Military time after settime is 13 : 27 Standard time after settime is 1 : 27 : 06 PM After attempting invalid settings: Military time : 00 : 00 Standard time : 12 : 00 : 00 AM cout << "\n\nafter attempting invalid settings:" << "\nmilitary time: "; t.printmilitary(); Note that the data members of a class cannot be initialized where they cout << "\nstandard time: "; t.printstandard(); cout << endl; are declared in the class body. These data members should be initialized by the class s constructor, or they can be assigned values by set function Constructor Constructors - Syntax A constructor is a member function of a class that has the same name as the class. A constructor is called automatically when an object of the class is declared. Constructors are used to initialize objects. A constructor must have the same name as the class of which it is a member. A constructor can also be called explicitly in order to create a new object. When we declare an object and want the constructor with zero arguments to be called, we do not include any parentheses after the object declaration. Syntax (for an object declaration when we have constructors) : Class_Name Object_Name (Arguments_for_Constructor) ; Syntax (for an explicit constructor call) : Object = Constructor_Name (Arguments_for_Constructor) ;

5 The Default Constructor: Example: this can be a constructor with no arguments or a constructor where all arguments have default values. It has the special purpose of iinitializing arrays of objects of its class. If a class does not have a constructor, the system provides a default constructor that does nothing This constructor will be called if class objects are declared. If a class has constructors, but does not have a default constructor, array allocation causes a syntactic error. In this case C++ compiler will generate no other constructors. class SampleClass SampleClass(int parameter1, double parameter2) ; with two arguments void do_stuff( ) ; private : int data1 ; double data2 ; ; SampleClass my_object(7, 7.77) ; // legal SampleClass your_object ; // illegal // constructor Solution: To add two arguments to the declaration of your_object To add a constructor definition for a constructor with no arguments SampleClass( ) ; If we do not want the default constructor to initialize any member variables, we leave the constructor s body empty. The following constructor definition is perfectly legal. It does nothing when called except make the compiler happy. SampleClass : : SampleClass( ) Do nothing. The implicit call to the constructor without arguments does not include parentheses. However when we explicitly call a constructor without arguments in an assignment statements, we do use parentheses. BankAccount account2( ) ; // this will cause problems Account1 = BankAccount( ) ; // OK Discussions A function with the same name as the class but preceded with a tilde character (~) is called the destructor of that class. The destructor does termination housekeeping on each class object before the memory for the object is reclaimed by the system. Destructors cannot take arguments and hence cannot be overloaded. The class definition contains declarations of the class s data members and the class s member functions. The member function declarations are the function prototypes. Member functions can be defined inside a class, but it is a good programming practice to define the functions outside the class definition Syntax: Member Function Definition ( non- constructor) Returned_Type Class_Name : : Function_Name(Parameter_List) Function_Body_Statements Action : The operation Funtion_Name( ) is a member function of the class called Class_Name. The scope resolution operator : : associates the function with the class. We use the dot operator or arrow operator to specify a member of the class object. We use the scope resolution opearator : : to specify the class name when giving the function definition for a member function. 29 Discussions Note the use of the binary scope resolution operator ( : : ) in each member function definition following the class definition in Fig Once a class is defined and its member functions are declared, the member functions must be defined. Each member function of the class can be defined directly in the class body (rather than including the function prototype of the class), or the member function can be defined after the class body. When a member function is defined after its corresponding class definition, the function name is preceded by the class name and the binary scope resolution operator ( : : ). Even though a member function declared in a class definition may be defined outside that class definition, that member function is still within that class s scope, i.e. its name is known only to other members of the class unless referred to via an object of the class, a reference to an object of the class, or a pointer to an object of the class. If a member function is defined in a class definition, the member function is automatically inlined. Member functions defined outside a class definition may be made inline by explicitly using the keyword inline. Remember that the compiler reserves the right not to inline any 30 function. 5

6 Discussions Classes simplify programming because the client need only be concerned with the operations encapsulated and embedded in the objects. Clients need not be concerned with a class s implementation. Interfaces do change, but less frequently than implementations. By hiding the implementation we eliminate the possibility of other program parts becoming dependent on the details of the class implementation. Often classes may be derived from other classes that provide attributes and behaviors the new class can use. Deriving new classes from existing classes is called inheritance. Classes can also include objects of other classes as members. Including class objects as members of other class is called composition. 31 Example: class StudentAccount private : string studentid ; // ID in the form ##.#### string studentname ; // student name double balance ; // account balance // constructor that initializes the data attributes StudentAccount(string ID, string name, double initbal) ; double getbalance( ) ; // return current balance void writeaccount( ) ; // output account information ; // return current value of private data member balance double StudentAccount : : getbalance( ) return balance ; 32 Example cont d: General Initializer Constructor with Initialization List // output account information along with labels void StudentAccount : : writeaccount( ) cout << ID : << studentid << endl ; cout << Name : << studentname << endl ; cout.setf(ios : : fixed, ios : : floatfield) ; // flags for real numbers cout.precision(2) ; // #include <iomanip.h> cout << Balance : << $ << balance << endl ; // general initializer constructor without initialization list StudentAccount : : StudentAccount (string ID, string name, double initbal) studentid = ID ; studentname = name ; balance = initbal ; 33 Syntax ClassName : : ClassName(T1 arg1, T2 arg2,, Tn argn) : datax (argm),, datay (argk) Statements initialize remaining data members Action: From the initialization list, data member datax is assigned the value argm, datay is assigned the value argk, and so forth. The remaining data members are assigned initial values in the body of the constructor. 34 Example: StudentAccount : : StudentAccount (string ID, string name, double initbal) : studentid ( ID), studentname(name), balance( initbal) In the above example, the function body is empty since no other statements are required. With simple constructors, all data members are given values by the initialization list and the function body is empty. 35 Example: Implementing the Rectangle class Class Rectangle // constructor Rectangle(double l = 0.0, double w = 0.0); // compute rectangle measurements double perimeter ( ) ; double area ( ) ; // data access functions double getlenght ( ) ; // return length double getwidth ( ) ; // return width // data update function void setsides(double l, double w) ; // update dimensions // length and width of the rectangle object double length, width ; ; 36 6

7 Implementing the Rectangle class cont d Constructor: // implementation of the Rectangle constructor Rectangle : : Rectangle (double l, double w) : length(l), width(w) Access Functions: // return the value of the length atribute double Rectangle : : getlength ( ) return length ; // return the value of the width atribute double Rectangle : : getwidth ( ) return width ; 37 Implementing the Rectangle class cont d Update Function: The values of length and width are initially set by the constructor. Their values can be updated during run-time by using the member function setsides( ). Since an initialization list is available only to the constructor, the new values must be assigned in the body of the function. // assign new values for the length and width void Rectangle : : setsides(double l, double w) length = l ; width = w ; 38 Implementing the Rectangle class cont d Measurement Functions : // the area is the product of the length and width double Rectangle : : area( ) return length * width ; // the perimeter is twice the sum of the length and width double Rectangle : : perimeter ( ) return 2 * (length + width) ; 39 // main program #include <math.h> // access sqrt function #include rect.h // access Rectangle class int main( ) double diagonal ; Rectangle rect(4.5, 8.2) ; cout.setf(ios : : fixed, ios : : floatfield) ; // flags for real numbers cout.precision(2) ; // #include <iomanip.h> cout << Area is << rect.area( ) << endl ; diagonal = sqrt(rect.getlength( ) * rect.getlength( ) + (rect.getwidth( ) * rect.getwidth( ) ) ; cout << Diagonal is << diagonal << endl ; return 0 ; Area is Diagonal is Class Scope and Accessing Class Members Nonmember functions are defined at file scope. Member functions have function scope in a class. // Fig. 6.4: fig06_04.cpp // Demonstrating the class member access operators. and -> // CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA! // Simple class Count class Count int x; void print() cout << x << endl; ; 41 Count counter, // create counter object *counterptr = &counter, // pointer to counter &counterref = counter; // reference to counter cout << "Assign 7 to x and print using the object's name: "; counter.x = 7; // assign 7 to data member x counter.print(); // call member function print cout << "Assign 8 to x and print using a reference: "; counterref.x = 8; // assign 8 to data member x counterref.print(); // call member function print cout << "Assign 10 to x and print using a pointer: "; counterptr->x = 10; // assign 10 to data member x counterptr->print(); // call member function print Assign 7 to x and print using the object s name : 7 Assign 8 to x and print using a reference : 8 Assign 10 to x and print using a pointer :

8 Separating Interface from Implementation Syntax : Class Header File (public interface) // Declaration of the class (including the function prototypes) // type of the file: header file (.h) // Prevent multiple inclusions of header file #ifndef ClassName_H #define ClassName_H // class declaration class ClassName. private :. ; #endif 43 Syntax: Member Function Definitions (implementation of the class) // class implementation // type of the file: source file (.cpp) #include <C++ system header files> #include programmer-defined header files // constructor implementation classname : : classname (... ) : // member functions implementation returntype classname : : memberfunction (... ) Example: Syntax : Driver Program // Driver to test the class // type of the file: source file (.cpp) #include <C++ system header files> #include programmer-defined header files returntype main ( ) Fig. 6.6 splits the program of Fig. 6.3 into multiple files.. It consists of the header file time1.h in which class Time is declared, the file time2.cpp in which the member functions of class Time are defined, and the file fig06_o5.cpp in which function main is defined Controlling Access to Members Only member functions and friends of that class can access a class s private members. The public members of a class may be accessed by any function in the program. The primary purpose of public members is to present to the class s clients a view of the services (behavior) the class provides. This set a services forms the public interface of the class. The private members of a class as well as the definitions of its public member functions are not accessible to the clients of a class. These components form the implementation of the class. 47 // Fig. 6.6: time1.h // Declaration of the Time class. #ifndef TIME1_H #define TIME1_H // Time abstract data type definition class Time Time(); // constructor void settime( int, int, int ); // set hour, minute, second void printmilitary(); // print military time format void printstandard(); // print standard time format int hour; // 0-23 int minute; // 0-59 int second; // 0-59 ; #endif 48 8

9 // Fig. 6.6: time1.cpp // Member function definitions for Time class. #include "time1.h" // Time constructor initializes each data member to zero. // Ensures all Time objects start in a consistent state. Time::Time() hour = minute = second = 0; // Set a new Time value using military time. Perform validity // checks on the data values. Set invalid values to zero. void Time::setTime( int h, int m, int s ) hour = ( h >= 0 && h < 24 )? h : 0; minute = ( m >= 0 && m < 60 )? m : 0; second = ( s >= 0 && s < 60 )? s : 0; // Print Time in military format void Time::printMilitary() cout << ( hour < 10? "0" : "" ) << hour << ":" << ( minute < 10? "0" : "" ) << minute; // Print time in standard format void Time::printStandard() cout << ( ( hour == 0 hour == 12 )? 12 : hour % 12 ) << ":" << ( minute < 10? "0" : "" ) << minute << ":" << ( second < 10? "0" : "" ) << second << ( hour < 12? " AM" : " PM" ); 49 // Fig. 6.6: fig06_06.cpp // Demonstrate errors resulting from attempts // to access private class members. #include "time1.h" int main( ) Time t; // Error: 'Time::hour' is not accessible t.hour = 7; // Error: 'Time::minute' is not accessible cout << "minute = " << t.minute; Compiling FIG06_06.CPP : Error FIG06_06.CPP 12 : Time : : hour is not accessible Error FIG06_06.CPP 12 : Time : : minute is not accessible 50 Using Default Arguments with Constructors // Fig. 6.8: time2.h // Declaration of the Time class. #ifndef TIME2_H #define TIME2_H // Time abstract data type definition class Time Time( int = 0, int = 0, int = 0 ); void settime( int, int, int ); void printmilitary(); void printstandard(); int hour; // 0-23 int minute; // 0-59 int second; // 0-59 ; #endif // default constructor // set hour, minute, second // print military time format // print standard time format 51 // Fig. 6.8: time2.cpp // Member function definitions for Time class. #include "time2.h" // Time constructor initializes each data member to zero. // Ensures all Time objects start in a consistent state. Time::Time( int hr, int min, int sec ) settime( hr, min, sec ); // Set a new Time value using military time. Perform validity // checks on the data values. Set invalid values to zero. void Time::setTime( int h, int m, int s ) hour = ( h >= 0 && h < 24 )? h : 0; minute = ( m >= 0 && m < 60 )? m : 0; second = ( s >= 0 && s < 60 )? s : 0; // Print Time in military format void Time::printMilitary() cout << ( hour < 10? "0" : "" ) << hour << ":" << ( minute < 10? "0" : "" ) << minute; // Print Time in standard format void Time::printStandard() cout << ( ( hour == 0 hour == 12 )? 12 : hour % 12 ) << ":" << ( minute < 10? "0" : "" ) << minute << ":" << ( second < 10? "0" : "" ) << second << ( hour < 12? " AM" : " PM" ); 52 // Fig. 6.8: fig06_08.cpp // Demonstrating a default constructor // function for class Time. #include "time2.h" Time t1, // all arguments defaulted t2(2), // minute and second defaulted t3(21, 34), // second defaulted t4(12, 25, 42), // all values specified t5(27, 74, 99); // all bad values specified cout << "Constructed with:\n << "all arguments defaulted:\n "; t1.printmilitary(); cout << "\n "; t1.printstandard(); cout << "\nhour specified; minute and second defaulted:" << "\n "; t2.printmilitary(); cout << "\n "; t2.printstandard(); cout << "\nhour and minute specified; second defaulted:" << "\n "; t3.printmilitary(); cout << "\n "; t3.printstandard(); cout << "\nhour, minute, and second specified:" << "\n "; t4.printmilitary(); cout << "\n "; t4.printstandard(); cout << "\nall invalid values specified:" << "\n "; t5.printmilitary(); cout << "\n "; t5.printstandard(); cout << endl; 53 Constructed with : All arguments defaulted : 00 : : 00 : 00 AM hour specified ; minute and second defaulted : 02 : 00 2 : 00 : 00 AM hour and minute specified ; second defaulted : 21 : 34 9 : 34 : 00 PM hour, minute, and second specified : 12 : : 25 : 42 PM all invalid values specified : 00 : : 00 : 00 AM 54 9

10 Using Destructors A destructor is a special member function of a class. The name of the destructor for a class is the tilde (~) character followed by the class name. A class s destructor is called when an object is destroyed e.g. when program execution leaves the scope in which an object of that class was instantiated. The destructor itself does not actually destroy the object it performs termination housekeeping before the systems reclaims the object s memory so that memory may be reused to hold new objects. A destructor receives no parameters and returns no value. A class may have only one destructor destructor overloading is not allowed. 55 When Constructors and Destructors are Called Constructors and destructors are called automatically. Generally, destructor calls are made in the reverse order of the constructor calls. Constructors are called for objects defined in global scope before any other function (including main) in that file begins execution. The corresponding destructors are called when main terminates or the exit function is called. Constructors are called for automatic local objects when execution reaches the point where the objects are defined. The corresponding destructors are called when the objects leave scope ( i.e., the block in which they are defined is exited). Constructors and destructors for automatic objects are called each time the objects enter and leave scope. Constructors are called for static local objects only once when execution first reaches the point where the objects are defined. Corresponding destructors are called when main terminates or the exit function is called. 56 // Fig. 6.9: create.h // Definition of class CreateAndDestroy. #ifndef CREATE_H #define CREATE_H class CreateAndDestroy CreateAndDestroy( int ); // constructor ~CreateAndDestroy(); // destructor int data; ; #endif 57 // Fig. 6.9: create.cpp // Member function definitions for class CreateAndDestroy #include "create.h" CreateAndDestroy::CreateAndDestroy( int value ) data = value; cout << "Object " << data << " constructor"; CreateAndDestroy::~CreateAndDestroy() cout << "Object " << data << " destructor " << endl; 58 // Fig. 6.9: fig06_09.cpp // Demonstrating the order in which constructors and // destructors are called. #include "create.h" void create( void ); // prototype CreateAndDestroy first( 1 ); // global object cout << " (global created before main)" << endl; CreateAndDestroy second( 2 ); // local object cout << " (local automatic in main)" << endl; static CreateAndDestroy third( 3 ); // local object cout << " (local static in main)" << endl; create(); // call function to create objects CreateAndDestroy fourth( 4 ); // local object cout << " (local automatic in main)" << endl; Object 1 constructor (global created before main) Object 2 constructor (local automatic in main) Object 3 constructor (local static in main) Object 5 constructor (local automatic in create) Object 6 constuctor (local static in create) Object 7 constructor (local automatic in create) Object 7 destructor Object 5 destructor Object 4 constructor (local automatic in main) Object 4 destructor Object 2 destructor Object 6 destructor Object 3 destructor // Function to create objects void create( void ) CreateAndDestroy fifth( 5 ); cout << " (local automatic in create)" << endl; static CreateAndDestroy sixth( 6 ); cout << " (local static in create)" << endl; CreateAndDestroy seventh( 7 ); cout << " (local automatic in create)" << endl; 59 Object 1 destructor 60 10

11 Function main declares three objects. Objects second and fourth are local automatic objects, and object third is a static local object. The constructor for each of these objects are called when execution reaches the point where each object is declared. The destructors for objects fourth and second are called in that order when the end of main is reached. Because object third is static, it exists until program termination. The destructor for object third is called before the destructor for first, but Function create declares three objects fifth and seventh are local automatic objects, and sixth is a static local object. The destructors for objects seventh and fifth are called in that order when the end of create is reached. Because sixth is static, it exists until program termination. The destructor of sixth is called before the destructors for third and first, but after all other objects are destroyed. after all other objects are destroyed Assignment by Default Memberwise Copy The assignment operator ( = ) can be used to assign an object to another object of the same type. Such assignment is by default performed by memberwise copy each member of one object is copied individually to the same member in another object. 63 // Fig. 6.12: fig06_12.cpp // Demonstrating that class objects can be assigned // to each other using default memberwise copy // Simple Date class class Date Date( int= 1, int= 1, int= 1990 ); // default constructor void print(); int month; int day; int year; ; // Simple Date constructor with no range checking Date::Date( int m, int d, int y ) month = m; day = d; year = y; // Print the Date in the form mm-dd-yyyy void Date::print() cout << month << '-' << day << '-' << year; 64 Date date1( 7, 4, 1993 ), date2; // d2 defaults to 1/1/90 cout << "date1 = "; date1.print(); cout << "\ndate2 = "; date2.print(); date2 = date1; // assignment by default memberwise copy cout << "\n\nafter default memberwise copy, date2 = "; date2.print(); cout << endl; date1 = date2 = After default memberwise copy, date2 =

57:017, Computers in Engineering C++ Classes

57:017, Computers in Engineering C++ Classes 57:017, Computers in Engineering C++ Classes Copyright 1992 2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Introduction Object-oriented programming (OOP) Encapsulates

More information

Classes: A Deeper Look

Classes: A Deeper Look Classes: A Deeper Look 1 Introduction Implementing a Time Abstract Data Type with a class Class Scope and Accessing Class Members Separating Interface from Implementation Controlling Access to Members

More information

Chapter 16: Classes and Data Abstraction

Chapter 16: Classes and Data Abstraction Chapter 16: Classes and Data Abstraction 16.1 Introduction 16.2 Implementing a Time Abstract Data Type with a Class 16.3 Class Scope and Accessing Class Members 16.4 Separating Interface from Implementation

More information

Classes and Data Abstraction

Classes and Data Abstraction 6 Classes and Data Abstraction Objectives To understand the software engineering concepts of encapsulation and data hiding. To understand the notions of data abstraction and abstract data types (ADTs).

More information

Introduction to Programming session 24

Introduction to Programming session 24 Introduction to Programming session 24 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel sslides Sharif Universityof Technology Outlines Introduction

More information

Chapter 6: Classes and Data Abstraction

Chapter 6: Classes and Data Abstraction Chapter 6: Classes and Data Abstraction 1 6.1 Introduction 6.2 Structure Definitions 6.3 Accessing Structure Members 6.4 Implementing a User-Defined Type Time with a struct 6.5 Implementing a Time Abstract

More information

More C++ Classes. Systems Programming

More C++ Classes. Systems Programming More C++ Classes Systems Programming C++ Classes Preprocessor Wrapper Time Class Case Study Class Scope and Assessing Class Members Using handles to access class members Access and Utility Functions Destructors

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3 Jan 20, 2004 Quiz 1 2 Average: about 3.8 More than half obtained: 4 + Highest is 8 Need more work/practice! Quiz 1

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 5: Classes September 14, 2004 Structure Definitions 2 Structures Aggregate data types built using elements of other types

More information

Fundamentals of Programming Session 24

Fundamentals of Programming Session 24 Fundamentals of Programming Session 24 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Preview 9/20/2017. Object Oriented Programing with C++ Object Oriented Programing with C++ Object Oriented Programing with C++

Preview 9/20/2017. Object Oriented Programing with C++ Object Oriented Programing with C++ Object Oriented Programing with C++ Preview Object Oriented Programming with C++ Class Members Inline Functions vs. Regular Functions Constructors & Destructors Initializing class Objects with Constructors C++ Programming Language C Programming

More information

W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls

W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls 1 W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls 2 7.4 friend Functions and friend Classes friend function and friend classes Can access private

More information

Pointer Assignments. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 18 October 29, The new Operator

Pointer Assignments. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 18 October 29, The new Operator CISC11 Introduction to Computer Science Dr. McCoy Lecture 1 October 29, 2009 Pointer Assignments Pointer variables can be "assigned": int *p1, *p2; p2 = p1; Assigns one pointer to another "Make p2 point

More information

9.1 Introduction. Integrated Time class case study Preprocessor wrapper Three types of handles on an object. Class functions

9.1 Introduction. Integrated Time class case study Preprocessor wrapper Three types of handles on an object. Class functions 1 9 Classes: A Deeper Look, Part 1 OBJECTIVES In this chapter you ll learn: How to use a preprocessor p wrapper to prevent multiple definition errors caused by including more than one copy of a header

More information

Classes and Data Abstraction. Topic 5

Classes and Data Abstraction. Topic 5 Classes and Data Abstraction Topic 5 Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes The data and functions of a class

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3: Classes May 24, 2004 2 Classes Structure Definitions 3 Structures Aggregate data types built using elements of other

More information

1 // Fig. 6.13: time2.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> Outline. 4 5 using std::cout; 6 7 #include <iomanip>

1 // Fig. 6.13: time2.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> Outline. 4 5 using std::cout; 6 7 #include <iomanip> CISC11 Introduction to Computer Science Dr. McCoy Lecture 20 November, 2009. Using Default Arguments with Constructors Constructors Can specify default arguments Default constructors Defaults all arguments

More information

Classes and Objects. Types and Classes. Example. Object Oriented Programming

Classes and Objects. Types and Classes. Example. Object Oriented Programming Classes and Objects Types and Classes Chapter 6 Object Oriented program development. Read this Chapter 7 Classes Read this Chapter 8 More About Classes Some sections will be assigned later Chapter 9 Inheritance.

More information

Chapter 9 Classes : A Deeper Look, Part 1

Chapter 9 Classes : A Deeper Look, Part 1 Chapter 9 Classes : A Deeper Look, Part 1 C++, How to Program Deitel & Deitel Fall 2016 CISC1600 Yanjun Li 1 Time Class Case Study Time Class Definition: private data members: int hour; int minute; int

More information

Object Oriented Design

Object Oriented Design Object Oriented Design Chapter 9 Initializing a non-static data member in the class definition is a syntax error 1 9.2 Time Class Case Study In Fig. 9.1, the class definition is enclosed in the following

More information

A Deeper Look at Classes

A Deeper Look at Classes A Deeper Look at Classes Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by

More information

Lecture 5. Function Pointers

Lecture 5. Function Pointers Lecture 5 Pointers to functions Complicated declarations Allocating and deallocating memory Classes const member functions Constructors and destructor this pointer static members Templates Lec 5 Programming

More information

Computer Programming with C++ (21)

Computer Programming with C++ (21) Computer Programming with C++ (21) Zhang, Xinyu Department of Computer Science and Engineering, Ewha Womans University, Seoul, Korea zhangxy@ewha.ac.kr Classes (III) Chapter 9.7 Chapter 10 Outline Destructors

More information

Fig. 7.1 Fig. 7.2 Fig. 7.3 Fig. 7.4 Fig. 7.5 Fig. 7.6 Fig. 7.7 Fig. 7.8 Fig. 7.9 Fig. 7.10

Fig. 7.1 Fig. 7.2 Fig. 7.3 Fig. 7.4 Fig. 7.5 Fig. 7.6 Fig. 7.7 Fig. 7.8 Fig. 7.9 Fig. 7.10 CHAPTER 7 CLASSES: PART II 1 Illustrations List (Main Page) Fig. 7.1 Fig. 7.2 Fig. 7.3 Fig. 7.4 Fig. 7.5 Fig. 7.6 Fig. 7.7 Fig. 7.8 Fig. 7.9 Fig. 7.10 Using a Time class with const objects and const member

More information

Computer Programming Class Members 9 th Lecture

Computer Programming Class Members 9 th Lecture Computer Programming Class Members 9 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2015 Eom, Hyeonsang All Rights Reserved Outline Class

More information

Introduction to Classes

Introduction to Classes Introduction to Classes Procedural and Object-Oriented Programming Procedural and Object-Oriented Programming Procedural programming focuses on the process/actions that occur in a program Object-Oriented

More information

Classes and Data Abstraction. Topic 5

Classes and Data Abstraction. Topic 5 Classes and Data Abstraction Topic 5 Classes Class User Defined Data Type Object Variable Data Value Operations Member Functions Object Variable Data Value Operations Member Functions Object Variable Data

More information

Chapter 17 - C++ Classes: Part II

Chapter 17 - C++ Classes: Part II Chapter 17 - C++ Classes: Part II 17.1 Introduction 17.2 const (Constant) Objects and const Member Functions 17.3 Composition: Objects as Members of Classes 17.4 friend Functions and friend Classes 17.5

More information

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Chapter 17 - C++ Classes: Part II 17.1 Introduction 17.2 const (Constant) Objects and const Member Functions 17.3 Composition: Objects as Members of Classes 17.4 friend

More information

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2

More information

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT). UNITII Classes Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT). It s a User Defined Data-type. The Data declared in a Class are called Data- Members

More information

Chapter 10 Introduction to Classes

Chapter 10 Introduction to Classes C++ for Engineers and Scientists Third Edition Chapter 10 Introduction to Classes CSc 10200! Introduction to Computing Lecture 20-21 Edgardo Molina Fall 2013 City College of New York 2 Objectives In this

More information

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. 1

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. 1 C How to Program, 6/e 1 Structures : Aggregate data types are built using elements of other types struct Time { int hour; int minute; Members of the same structure must have unique names. Two different

More information

Angela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan.

Angela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan. C++ Classes: Part II Angela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 17.2 const (Constant) Objects and

More information

Introduction Of Classes ( OOPS )

Introduction Of Classes ( OOPS ) Introduction Of Classes ( OOPS ) Classes (I) A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class.

More information

Lecture 18 Tao Wang 1

Lecture 18 Tao Wang 1 Lecture 18 Tao Wang 1 Abstract Data Types in C++ (Classes) A procedural program consists of one or more algorithms that have been written in computerreadable language Input and display of program output

More information

Classes: A Deeper Look. Systems Programming

Classes: A Deeper Look. Systems Programming Classes: A Deeper Look Systems Programming Deeper into C++ Classes const objects and const member functions Composition Friendship this pointer Dynamic memory management new and delete operators static

More information

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming Chapter 13: Introduction to Classes 1 13.1 Procedural and Object-Oriented Programming 2 Procedural and Object-Oriented Programming Procedural programming focuses on the process/actions that occur in a

More information

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

Preview 11/1/2017. Constant Objects and Member Functions. Constant Objects and Member Functions. Constant Objects and Member Functions

Preview 11/1/2017. Constant Objects and Member Functions. Constant Objects and Member Functions. Constant Objects and Member Functions Preview Constant Objects and Constant Functions Composition: Objects as Members of a Class Friend functions The use of Friend Functions Some objects need to be modifiable and some do not. A programmer

More information

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 12: Classes and Data Abstraction Objectives In this chapter, you will: Learn about classes Learn about private, protected,

More information

Topics. Topics (Continued) 7.1 Abstract Data Types. Abstraction and Data Types. 7.2 Object-Oriented Programming

Topics. Topics (Continued) 7.1 Abstract Data Types. Abstraction and Data Types. 7.2 Object-Oriented Programming Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Topics 7.1 Abstract Data Types 7.2 Object-Oriented Programming

More information

Object-Oriented Design (OOD) and C++

Object-Oriented Design (OOD) and C++ Chapter 2 Object-Oriented Design (OOD) and C++ At a Glance Instructor s Manual Table of Contents Chapter Overview Chapter Objectives Instructor Notes Quick Quizzes Discussion Questions Projects to Assign

More information

Deitel Dive-Into Series: Dive-Into Cygwin and GNU C++

Deitel Dive-Into Series: Dive-Into Cygwin and GNU C++ 1 Deitel Dive-Into Series: Dive-Into Cygwin and GNU C++ Objectives To be able to use Cygwin, a UNIX simulator. To be able to use a text editor to create C++ source files To be able to use GCC to compile

More information

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

C++ Classes, Constructor & Object Oriented Programming

C++ Classes, Constructor & Object Oriented Programming C++ Classes, Constructor & Object Oriented Programming Object Oriented Programming Programmer thinks about and defines the attributes and behavior of objects. Often the objects are modeled after real-world

More information

Lecture #1. Introduction to Classes and Objects

Lecture #1. Introduction to Classes and Objects Lecture #1 Introduction to Classes and Objects Topics 1. Abstract Data Types 2. Object-Oriented Programming 3. Introduction to Classes 4. Introduction to Objects 5. Defining Member Functions 6. Constructors

More information

Abstraction in Software Development

Abstraction in Software Development Abstract Data Types Programmer-created data types that specify values that can be stored (type of data) operations that can be done on the values The user of an abstract data type (ADT) does not need to

More information

Classes: A Deeper Look, Part 2

Classes: A Deeper Look, Part 2 10 But what, to serve our private ends, Forbids the cheating of our friends? Charles Churchill Instead of this absurd division into sexes they ought to class people as static and dynamic. Evelyn Waugh

More information

Object Oriented Design

Object Oriented Design Object Oriented Design Lecture 3: Introduction to C++ (Continue) Examples using declarations that eliminate the need to repeat the std:: prefix 1 Examples using namespace std; enables a program to use

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Constructor - example

Constructor - example Constructors A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is same as the class name. The constructor is invoked whenever

More information

Department of Computer science and Engineering Sub. Name: Object oriented programming and data structures Sub. Code: EC6301 Sem/Class: III/II-ECE Staff name: M.Kavipriya Two Mark Questions UNIT-1 1. List

More information

Function Overloading

Function Overloading Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures

More information

Object Oriented Programming(OOP).

Object Oriented Programming(OOP). Object Oriented Programming(OOP). OOP terminology: Class : A class is a way to bind data and its associated function together. It allows the data to be hidden. class Crectangle Data members length; breadth;

More information

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year Object Oriented Programming Assistant Lecture Omar Al Khayat 2 nd Year Syllabus Overview of C++ Program Principles of object oriented programming including classes Introduction to Object-Oriented Paradigm:Structures

More information

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual

More information

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public

More information

G205 Fundamentals of Computer Engineering. CLASS 3, Wed. Sept Stefano Basagni Fall 2004 M-W, 1:30pm-3:10pm

G205 Fundamentals of Computer Engineering. CLASS 3, Wed. Sept Stefano Basagni Fall 2004 M-W, 1:30pm-3:10pm G205 Fundamentals of Computer Engineering CLASS 3, Wed. Sept. 15 2004 Stefano Basagni Fall 2004 M-W, 1:30pm-3:10pm Function Calls A function is called via its name Actual parameters are passed for the

More information

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity. OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

More information

Data Structures using OOP C++ Lecture 3

Data Structures using OOP C++ Lecture 3 References: th 1. E Balagurusamy, Object Oriented Programming with C++, 4 edition, McGraw-Hill 2008. 2. Robert L. Kruse and Alexander J. Ryba, Data Structures and Program Design in C++, Prentice-Hall 2000.

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Friends and Overloaded Operators

Friends and Overloaded Operators Friend Function Friends and Overloaded Operators Class operations are typically implemented as member functions Some operations are better implemented as ordinary (nonmember) functions CSC 330 OO Software

More information

Object-Based Programming (Deitel chapter 8)

Object-Based Programming (Deitel chapter 8) Object-Based Programming (Deitel chapter 8) 1 Plan 2 Introduction Implementing a Time Abstract Data Type with a Class Class Scope Controlling Access to Members Referring to the Current Object s Members

More information

Friends and Overloaded Operators

Friends and Overloaded Operators Friends and Overloaded Operators Friend Function Class operations are typically implemented as member functions Some operations are better implemented as ordinary (nonmember) functions CSC 330 OO Software

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Programming II Lecture 2 Structures and Classes

Programming II Lecture 2 Structures and Classes 3. struct Rectangle { 4. double length; 5. double width; 6. }; 7. int main() 8. { Rectangle R={12.5,7}; 9. cout

More information

Class 15. Object-Oriented Development from Structs to Classes. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Class 15. Object-Oriented Development from Structs to Classes. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski) Class 15 Object-Oriented Development from Structs to Classes The difference between structs and classes A class in C++ is basically the same thing as a struct The following are exactly equivalent struct

More information

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Fall 2012 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions. Dr.G.R.Damodaran College of Science (Autonomous, affiliated to the Bharathiar University, recognized by the UGC)Reaccredited at the 'A' Grade Level by the NAAC and ISO 9001:2008 Certified CRISL rated 'A'

More information

Lecture 7. Log into Linux New documents posted to course webpage

Lecture 7. Log into Linux New documents posted to course webpage Lecture 7 Log into Linux New documents posted to course webpage Coding style guideline; part of project grade is following this Homework 4, due on Monday; this is a written assignment Project 1, due next

More information

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Spring 2013 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform

More information

IS0020 Program Design and Software Tools Midterm, Fall, 2004

IS0020 Program Design and Software Tools Midterm, Fall, 2004 IS0020 Program Design and Software Tools Midterm, Fall, 2004 Name: Instruction There are two parts in this test. The first part contains 22 questions worth 40 points you need to get 20 right to get the

More information

Programming Abstractions

Programming Abstractions Programming Abstractions C S 1 0 6 B Cynthia Lee Topics du Jour: Make your own classes! Needed for Boggle assignment! We are starting to see a little bit in MarbleBoard assignment as well 2 Classes in

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING THROUGH C++ Practical: OOPS THROUGH C++ Subject Code: 1618407 PROGRAM NO.1 Programming exercise on executing a Basic C++

More information

System Design and Programming II

System Design and Programming II System Design and Programming II CSCI 194 Section 01 CRN: 10968 Fall 2017 David L. Sylvester, Sr., Assistant Professor Chapter 13 Introduction to Classes Procedural and Object-Oriented Programming Procedural

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

SFU CMPT Topic: Classes

SFU CMPT Topic: Classes SFU CMPT-212 2008-1 1 Topic: Classes SFU CMPT-212 2008-1 Topic: Classes Ján Maňuch E-mail: jmanuch@sfu.ca Friday 15 th February, 2008 SFU CMPT-212 2008-1 2 Topic: Classes Encapsulation Using global variables

More information

Class. SSE2034: System Software Experiment 3, Fall 2018, Jinkyu Jeong

Class. SSE2034: System Software Experiment 3, Fall 2018, Jinkyu Jeong Class Prof. Jinkyu Jeong (Jinkyu@skku.edu) TA -- Minwoo Ahn (minwoo.ahn@csl.skku.edu) TA -- Donghyun Kim (donghyun.kim@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu

More information

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT Two Mark Questions UNIT - I 1. DEFINE ENCAPSULATION. Encapsulation is the process of combining data and functions

More information

OBJECT ORIENTED PROGRAMMING

OBJECT ORIENTED PROGRAMMING Classes and Objects So far you have explored the structure of a simple program that starts execution at main() and enables you to declare local and global variables and constants and branch your execution

More information

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University) Estd: 1994 JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli - 621014 (An approved by AICTE and Affiliated to Anna University) ISO 9001:2000 Certified Subject Code & Name : CS 1202

More information

2 ADT Programming User-defined abstract data types

2 ADT Programming User-defined abstract data types Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct

More information

Recharge (int, int, int); //constructor declared void disply();

Recharge (int, int, int); //constructor declared void disply(); Constructor and destructors in C++ Constructor Constructor is a special member function of the class which is invoked automatically when new object is created. The purpose of constructor is to initialize

More information

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int, Classes Starting Savitch Chapter 10 l l A class is a data type whose variables are objects Some pre-defined classes in C++ include int, char, ifstream Of course, you can define your own classes too A class

More information

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University (5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University Key Concepts Function templates Defining classes with member functions The Rule

More information

EL2310 Scientific Programming

EL2310 Scientific Programming (pronobis@kth.se) Overview Overview Wrap Up Introduction to Object Oriented Paradigm More on and Members Operator Overloading Last time Intro to C++ Differences between C and C++ Intro to OOP Today Object

More information

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND Introduction to Classes 13.2 The Class Unit 4 Chapter 13 CS 2308 Fall 2016 Jill Seaman 1 l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains

More information

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Fall 2013 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform

More information

C Functions. Object created and destroyed within its block auto: default for local variables

C Functions. Object created and destroyed within its block auto: default for local variables 1 5 C Functions 5.12 Storage Classes 2 Automatic storage Object created and destroyed within its block auto: default for local variables auto double x, y; Static storage Variables exist for entire program

More information

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 4 FUNCTIONS. 4.1 Introduction CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main

More information

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class. Classes and Objects Week 5 Gaddis:.2-.12 14.3-14.4 CS 5301 Spring 2015 Jill Seaman The Class! A class in C++ is similar to a structure.! A class contains members: - variables AND - functions (often called

More information

Chapter 1: Object-Oriented Programming Using C++

Chapter 1: Object-Oriented Programming Using C++ Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms

More information

Example : class Student { int rollno; float marks; public: student( ) //Constructor { rollno=0; marks=0.0; } //other public members };

Example : class Student { int rollno; float marks; public: student( ) //Constructor { rollno=0; marks=0.0; } //other public members }; Constructors A Member function with the same name as its classis called Constructor and it is used to initilize the objects of that class type with a legal value. A Constructor is a special member function

More information

Introduction to C++ Introduction to C++ 1

Introduction to C++ Introduction to C++ 1 1 What Is C++? (Mostly) an extension of C to include: Classes Templates Inheritance and Multiple Inheritance Function and Operator Overloading New (and better) Standard Library References and Reference

More information