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 structures may contain members of the same name. struct st1 {int n; struct st2 {float n; Each structure definition must end with a semicolon. 2
object struct Time { int hour; int minute; Time timeobject; Time timearray[ 10 ]; VS. struct Time time; Time *timeptr1; timeptr1= &timeobject; Time *timeptr2; timeptr2 = new Time; 3
Member access operators: Dot operator (.) for structures and objects Arrow operator (->) for pointers Print member hour of timeobject: Time timeobject; cout << timeobject.hour; OR Time *timeptr; timeptr = &timeobject; cout << timeptr->hour; // timeptr->hour is the same as (*timeptr).hour 4
#include <iostream> #include<iomanip> using namespace std; // structure definition struct Time { int hour; // 0-23 int minute; // 0-59 void printuniversal( Time ); void printstandard( Time ); int main() { Time dinnertime; dinnertime.hour = 18; dinnertime.minute= 30; } printuniversal ( dinnertime ); cout<<endl; printstandard( dinnertime ); void printuniversal( Time t ) { } cout << setfill( 0 )<<setw(2) << t.hour << : << setw(2) << t.minute ; void printstandard( Time t ) { } cout << (( t.hour == 0 t.hour == 12)? 12 : t.hour % 12 ) << ":" << setfill( 0 ) << setw(2) << t.minute << (t.hour < 12? " AM" : PM"); 5
struct Time { int hour; int minute; Time x; x.hour = 23; x.minute = 54; All members of the structure are accessible!! All members are public There is INFORMATION HIDING in C++ Structure 6
Before you can drive a car, someone has to design it and build it. A car typically begins as an engineering drawings that include the design for an accelerator pedal that makes the car go faster. The pedal hides the complex mechanisms that actually make the car go faster, just as the brake pedal hides the mechanisms that slow the car, the steering wheel hides the mechanisms that turn the car and so on. This enables people with little or no knowledge of how cars are engineered to drive a car easily, simply by using the accelerator pedal, the brake pedal, the steering wheel, the transmission shifting mechanism and other such simple and user-friendly interfaces to the car s complex internal mechanisms. 7
In C++, we begin by creating a program unit called a class to house a function, just as a car s engineering drawings house the design of an accelerator pedal. A function belonging to a class is called a member function. In a class, you provide one or more member functions that are designed to perform the class s tasks. Just as you cannot drive an engineering drawing of a car, you cannot drive a class. You must create an object of a class before you can get a program to perform the tasks the class describes. Just as many cars can be built from the same engineering drawing, many objects can be built from the same class. 8
When you drive a car, pressing its gas pedal sends a message to the car to perform a task that is, make the car go faster. Similarly, you send messages to an object each message is known as a member-function call and tells a member function of the object to perform its task. This is often called requesting a service from an object. 9
In addition to the capabilities a car provides, it also has many attributes, such as its color, the number of doors, the amount of gas in its tank, its current speed and its total miles driven (i.e., its odometer reading). Like the car s capabilities, these attributes are represented as part of a car s design in its engineering diagrams. As you drive a car, these attributes are always associated with the car. Every car maintains its own attributes. Similarly, an object has attributes that are carried with the object as it s used in a program. These attributes are specified as part of the object s class. Attributes are specified by the class s data members. 10
A class is a data type. Model objects that have both attributes (data members) behaviors (member functions -methods) Object functions data Have a body delineated with braces ({ and }) Class definitions terminate with a semicolon. class Time {/* data members and methods */ keyword class tag 11
Interface Implementation method Object code method method code code data method code 12
person data: name, p_number, address, gender Class methods: getgender(), changeaddress(newaddress) person data: Lena Brat, 761203-7111, Stureplan 4, female person data: Erik Olsson, 780605-4789, Hamngatan 3, male person data: Lars Backe, 671110-A562, Mälartorget 19, male 13
class Time { // data members and methods Time dinnertime; // Creates an object of type Time Time array[ 5 ]; // array of Time objects Time *pointer1; // pointer to a Time object pointer1 = &dinnertime; Time *pointer2 = new Time; // pointer to a Time object 14
An object has attributes that are carried with it as it s used in a program. Such attributes exist throughout the life of the object. A class normally consists of one or more member functions that manipulate the attributes that belong to a particular object of the class. Attributes are represented as variables in a class definition. 15
A variable that is declared in the class definition but outside the bodies of the class s member-function definitions is a data member. Every instance (i.e., object) of a class contains one copy of each of the class s data members. A benefit of making a variable a data member is that all the member functions of the class can manipulate any data members that appear in the class definition. 16
class Time { public: void settime(int, int); // set hour,minute void printstandard(); // print time int hour; // 0 23 int minute; // 0 59 Time class consists data members: hour minute Time class consists member functions settime printstandard; 17
In C ++ classes can limit the access to their members and methods. The three types of access a class can grant are: public : this keyword can be used to expose data members and methods (make accessible wherever the program has access to an object of the class ) private : this keyword can be used to hide data members and methods (make accessible only to member methods of the class ) protected : Similar to private ( will study it later!!) 18
Declaring data members with access specifier private is known as data hiding (information hiding). When a program creates (instantiates) an object, its data members are encapsulated (hidden) in the object and can be accessed only by member functions of the object s class. 19
Variables declared in a function definition s body are known as local variables and can be used only from the line of their declaration in the function to closing right brace (}) of the block in which they re declared. A local variable must be declared before it can be used in a function. A local variable cannot be accessed outside the function in which it s declared. When a function terminates, the values of its local variables are lost. 20
class Time { public: void settime(int, int); // set hour,minute void printuniversal(); // print in universal format void printstandard(); // print in standard format private: int hour; // 0 23 int minute; // 0 59 // Time class consists of public methods and private // data members. // A colon : follows the keywords private and public 21
Access to any class member, whether data member or method, is supported by the member selector operator. and the class indirection operator -> class Time { public: void settime( int h, int m); void printuniversal() const; void printstandard() const; // set hour,minute // print universal time format // print standard time format private: int hour; // 0 23 int minute; // 0 59 main() { Time noww; // declare an object from class Time noww.settime (11,30); noww.minute = 34; //Is it possible? } 23
class C { public : void m(); // public scope private : char d; // private scope int f(); If no public and private keywords are used then the members are default in private scope. class D { int x; // equals to class D { private: int x; 24
A method can be declared inside the class declaration but can be defined outside the class declaration A method can be defined inside the class declaration. Such a definition is said to be inline 25
class Person { public : // declare the methods void setage (unsigned n); unsigned getage() const; private: unsigned age; // definitions for methods void Person::setAge(unsigned n) { age = n; } unsigned Person::getAge() const { return age; } 26
class Person { public : // inline definition void setage (unsigned n) { age = n; unsigned getage() const {return age private: unsigned age; 27
#include <iostream> using namespace std; class Person { public : void setage (unsigned n) { age = n; unsigned getage() const {return age private: unsigned age; void main() { Person p; p.setage(12); cout << p.getage()<<endl; // p.age=12;??????? } Person student [2]; student[0].setage(12); student[1].setage(15); for (int i=0; i<2;i++) cout << student[i].getage()<<endl; 28
A special method that initializes class members. Same name as the class. No return type (not even void). Member variables can be initialized by the constructor or set afterwards Normally, constructors are declared public. 29
C++ requires a constructor call for each object that is created, which helps ensure that each object is initialized before it s used in a program. The constructor call occurs implicitly when the object is created. If a class does not explicitly include a constructor, the compiler provides a default constructor that is, a constructor with no parameters. 30
A class gets a default constructor in one of two ways: The compiler implicitly creates a default constructor in a class that does not define a constructor. You explicitly define a constructor that takes no arguments. If you define a constructor with arguments, C++ will not implicitly create a default constructor for that class. 31
class Person { public : // Constructor Person() { age = 0; name = Unknown ; } void setage (unsigned n) { age = n unsigned getage() const { return age void getname() const { cout <<name<<endl; } private: unsigned age; string name; void main() { Person p; cout << p.getage()<<endl; cout << p.getname()<<endl; } 1992-2010 by Pearson Education, Inc. 32
class Person { public : Person(); // Constructor void setage (unsigned n) { age = n unsigned getage() const { return age void getname() const { cout << name << endl; } private: unsigned age; string name; Person ::Person() { age = 0; name = Unknown ; } void main() { Person p; cout <<p.getage()<<endl; cout <<p.getname()<<endl; } 33
class Person { public : Person() { age = 0; name = Unknown ; } // First Constructor Person(string n) { name = n; } // Second Constructor void setage (unsigned n) { age = n unsigned getage() const { return age void getname() const { cout << name << endl; } private: unsigned age; string name; void main() { Person q; // USING FIRST CONSTRUCTOR cout << q.getage() << endl; cout << q.getname()<< endl } Person p( John ); // USING SECOND CONSTRUCTOR cout << p.getage() << endl; cout << p.getname()<< endl; 34
A constructor is automatically invoked whenever an object is created A destructor is automatically invoked whenever an object is destroyed A destructor takes no arguments and no return type, there can be only one destructor per class class C { public : C() { // constructor ~C() { // destructor } 35
class C { public : C(){name= anonymous ;} C(const char * n) { name=n;} ~C() { cout << destructing <<name<< \n ;} private: string name; int main(){ C c0( John ); { // entering scope... C c1; C c2; } // exiting scope. destructors for c1 and c2 are called C * ptr = new C(); delete ptr; // destructor for ptr object is called } return 0; // destructor for c0 is called 36
Interfaces define and standardize the ways in which things such as people and systems interact with one another. The interface of a class describes what services a class s clients can use and how to request those services, but not how the class carries out the services. A class s public interface consists of the class s public member functions (also known as the class s public services). 37
Interface Implementation method Object code method method code code data method code 38