Your SlideShare is downloading. ×
0
OOP COMPLETE NOTESBYUmer Tanvir
CSC241:Object OrientedProgrammingSpring 20131. Starting OOPMay25,2013COMSATSInstituteofInformationTechnology2Please turn O...
Study Assignment• I hope you did go through chapter 1 of both the books.• How was the experience?• What did you learn?May ...
Procedural vs. Object-Oriented• ProceduralWithdraw, deposit, transfer• Object OrientedCustomer, money, accountMay 25, 2013...
Object-Orientation(OO)May 25, 2013 COMSATS Institute of Information Technology 5
What is Object-Orientation?• A technique for system modeling• OO model consists of several interacting objectsMay 25, 2013...
What is a Model?• A model is an abstraction of something• Purpose is to understand the product before developing itMay 25,...
Examples – Model• Highway maps• Architectural models• Mechanical modelsMay 25, 2013 COMSATS Institute of Information Techn...
Example – OO ModelMay 25, 2013 COMSATS Institute of Information Technology 9
…Example – OO Model• Objects• Ali• House• Car• Tree• Interactions• Ali lives in the house• Ali drives the carMay 25, 2013 ...
Object-Orientation - Advantages• People think in terms of objects• OO models map to reality• Therefore, OO models are• eas...
What is an Object?An object is• Something tangible (Ali, Car)• Something that can be apprehended intellectually (Time, Dat...
… What is an Object?An object has• State (attributes)• Well-defined behaviour (operations)• Unique identityMay 25, 2013 CO...
Example – Ali is a Tangible Object• State (attributes)• Name• Age• behaviour (operations)• Walks• Eats• Identity• His name...
Example – Car is a Tangible Object• State (attributes)- Color- Model• behaviour (operations)- Start Car- Accelerate- Chang...
Example – Time is an Object ApprehendedIntellectually• State (attributes)- Hours - Seconds- Minutes• behaviour (operations...
Example – Date is an Object ApprehendedIntellectually• State (attributes)- Year - Day- Month• behaviour (operations)- Set ...
Definition• What Is an Object?• An object is a software bundle of related variables and methods.Software objects are often...
Real-world objects share two characteristics• They all have state and behavior• dogs have state (name, color, breed, hungr...
Software objects are modeled after real-worldobjects• A software object maintains its state in one or more variables .• A ...
Can represent real-world objects by usingsoftware objects.• You might want to represent real-world dogs as software object...
Moving to new thinking …• C is a procedural language. A procedure is a list ofinstructions.• Very small programs (tens of ...
Moving to new thinking …• C programming cannot do the following well:• Functions have unrestricted access to global data.•...
Moving to new thinking …• A real world object, e.g. car:• Is its description purely the ability to have a ‘data type’ tore...
Moving to new thinking …• A real world object, e.g. car:• Test drive! Right?• What would you know through a test drive: ho...
Object Oriented Approach …• Neither data nor functions, by themselves, model real-world objects effectively.• OO languages...
Object Oriented Approach …• OOP is all about ‘organization’ and not about programoperation. Most individual statements are...
Abstraction• Abstraction is a way to cope with complexity.• Principle of abstraction:“Capture only those details about an ...
Example – Abstraction• Attributes- Name - Employee ID- Student Roll No - Designation- Year of Study - Salary- CGPA - AgeMa...
Example – Abstraction• behaviour- Study - DevelopExam- GiveExam - TakeExam- PlaySports - Eat- DeliverLecture - WalkMay 25,...
Example – AbstractionAttributes• - Name - Employee ID• - Student Roll No - Designation• - Year of Study - Salary• - CGPA -...
Example – Abstraction• behaviour- Study - DevelopExam- GiveExam - TakeExam- PlaySports - Eat- DeliverLecture - WalkMay 25,...
Example – Abstraction• Attributes- Name - Employee ID- Student Roll No - Designation- Year of Study - Salary- CGPA - AgeMa...
Example – Abstraction• behaviour- Study - DevelopExam- GiveExam - TakeExam- PlaySports - Eat- DeliverLecture - WalkMay 25,...
Example – Abstraction• Ordinary PerspectiveA pet animal with• Four Legs• A Tail• Two Ears• Sharp Teeth• Surgeon’s Perspect...
Example – AbstractionMay 25, 2013 COMSATS Institute of Information Technology 36Driver’s ViewEngineer’s View
Abstraction – Advantages• Simplifies the model by hiding irrelevant details• Abstraction provides the freedom to defer imp...
Classes• In an OO model, some of the objects exhibit identical characteristics(information structure and behaviour)• We sa...
Example – Class• Ali studies mathematics• Anam studies physics• Sohail studies chemistry• Each one is a Student• We say th...
Example – Class• Ahsan teaches mathematics• Aamir teaches computer science• Atif teaches physics• Each one is a teacher• W...
Graphical Representation of ClassesMay 25, 2013 COMSATS Institute of Information Technology 41(Class Name)(attributes)(ope...
Example – Graphical Representation ofClassesMay 25, 2013 COMSATS Institute of Information Technology 42Circlecenterradiusd...
Example – Graphical Representation ofClassesMay 25, 2013 COMSATS Institute of Information Technology 43Personnameagegender...
Inheritance• A child inherits characteristics of its parents• Besides inherited characteristics, a child may have its own ...
Inheritance in Classes• If a class B inherits from class A then it contains all the characteristics(information structure ...
Example – InheritanceMay 25, 2013 COMSATS Institute of Information Technology 46PersonTeacherDoctorStudent
Example – InheritanceMay 25, 2013 COMSATS Institute of Information Technology 47ShapeCircleTriangleLine
Inheritance – “IS A” or“IS A KIND OF” Relationship• Each derived class is a special kind of its base classMay 25, 2013 COM...
Example – “IS A” RelationshipMay 25, 2013 COMSATS Institute of Information Technology 49PersonnameagegendereatwalkTeacherd...
Example – “IS A” RelationshipMay 25, 2013 COMSATS Institute of Information Technology 50ShapecolorcoorddrawrotatesetColorC...
Inheritance – Advantages• Reuse• Less redundancy• Increased maintainabilityMay 25, 2013 COMSATS Institute of Information T...
Reuse with Inheritance• Main purpose of inheritance is reuse• We can easily add new classes by inheriting from existing cl...
Example ReuseMay 25, 2013 COMSATS Institute of Information Technology 53ShapecolorcoorddrawrotatesetColorCircleradiusdrawc...
Example ReuseMay 25, 2013 COMSATS Institute of Information Technology 54PersonnameagegendereatwalkTeacherdesignationsalary...
Example ReuseMay 25, 2013 COMSATS Institute of Information Technology 55PersonnameagegendereatwalkTeacherdesignationsalary...
References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th e...
ThanksMay 25, 2013 COMSATS Institute of Information Technology 57
CSC241:Object OrientedProgrammingSpring 20131. Inheritance & GeneralizationMay25,2013COMSATSInstituteofInformationTechnolo...
Recap – Inheritance• Derived class inherits all the characteristics of the base class• Besides inherited characteristics, ...
Concepts Related with Inheritance• Generalization• Subtyping (extension)• Specialization (restriction)May 25, 2013 COMSATS...
Generalization• In OO models, some classes may have common characteristics• We extract these features into a new class and...
Example – GeneralizationMay 25, 2013 COMSATS Institute of Information Technology 62CirclecolorverticesradiusmovesetColorco...
Example – GeneralizationMay 25, 2013 COMSATS Institute of Information Technology 63ShapecolorverticesmovesetColorCirclerad...
Example – GeneralizationMay 25, 2013 COMSATS Institute of Information Technology 64Teachernameagegenderdesignationsalaryte...
Example – GeneralizationMay 25, 2013 COMSATS Institute of Information Technology 65PersonnameagegendereatwalkTeacherdesign...
Sub-typing & Specialization• We want to add a new class to an existing model• Find an existing class that already implemen...
Sub-typing (Extension)• Sub-typing means that derived class is behaviourally compatible withthe base class• Behaviourally ...
Example –Sub-typing(Extension)May 25, 2013 COMSATS Institute of Information Technology 68PersonnameagegendereatswalksStude...
Example –Sub-typing(Extension)May 25, 2013 COMSATS Institute of Information Technology 69ShapecolorverticessetColormoveCir...
Specialization (Restriction)• Specialization means that derived class is behaviourally incompatiblewith the base class• Be...
Example – Specialization(Restriction)May 25, 2013 COMSATS Institute of Information Technology 71Personage : [0..100]…Adult...
Example – Specialization(Restriction)May 25, 2013 COMSATS Institute of Information Technology 72IntegerSet…NaturalSet…add(...
Overriding• A class may need to override the default behaviour provided by itsbase class• Reasons for overriding• Provide ...
Example – Specific BehaviourMay 25, 2013 COMSATS Institute of Information Technology 74ShapecolorverticesdrawmovesetColorC...
Example – ExtensionMay 25, 2013 COMSATS Institute of Information Technology 75WindowwidthheightopenclosedrawDialogBoxcontr...
Example – RestrictionMay 25, 2013 COMSATS Institute of Information Technology 76IntegerSet…NaturalSet…add( elem )…add( ele...
Example – Improve Performance• Class Circle overridesrotate operation of classShape with a Nulloperation.May 25, 2013 COMS...
Abstract Classes• An abstract class implements an abstract concept• Main purpose is to be inherited by other classes• Can’...
Example – Abstract Classes• Here, Person is an abstract classMay 25, 2013 COMSATS Institute of Information Technology 79Te...
Example – Abstract Classes• Here, Vehicle is an abstract classMay 25, 2013 COMSATS Institute of Information Technology 80B...
Concrete Classes• A concrete class implements a concrete concept• Main purpose is to be instantiated• Provides implementat...
Example – Concrete Classes• Here, Student, Teacher and Doctor are concreteclassesMay 25, 2013 COMSATS Institute of Informa...
Example – Concrete ClassesMay 25, 2013 COMSATS Institute of Information Technology 83• Here, Car, Bus and Truck are concre...
Multiple Inheritance• We may want to reuse characteristics of more than one parent classMay 25, 2013 COMSATS Institute of ...
Example – Multiple InheritanceMay 25, 2013 COMSATS Institute of Information Technology 85Mermaid
Example – Multiple InheritanceMay 25, 2013 COMSATS Institute of Information Technology 86MermaidWoman Fish
Example – Multiple InheritanceMay 25, 2013 COMSATS Institute of Information Technology 87Amphibious Vehicle
Example – Multiple InheritanceMay 25, 2013 COMSATS Institute of Information Technology 88Amphibious VehicleLand Vehicle Wa...
Problems with Multiple Inheritance• Increased complexity• Reduced understanding• Duplicate featuresMay 25, 2013 COMSATS In...
Problem – Duplicate Features• Which eat operation Mermaid inherits?May 25, 2013 COMSATS Institute of Information Technolog...
Solution – Override the Common FeatureMay 25, 2013 COMSATS Institute of Information Technology 91MermaidWoman Fisheat…eat…...
Problem – Duplicate Features(Diamond Problem)• Which changeGear operation Amphibious Vehicleinherits?May 25, 2013 COMSATS ...
Solution to Diamond Problem• Some languages disallow diamond hierarchy• Others provide mechanism to ignore characteristics...
Association• Objects in an object model interact with each other• Usually an object provides services to several other obj...
Kinds of Association• Class Association• Inheritance• Object Association• Simple Association• Composition• AggregationMay ...
Simple Association• Is the weakest link between objects• Is a reference by which one object can interact with some otherob...
Kinds of Simple Association• w.r.t navigation• One-way Association• Two-way Association• w.r.t number of objects• Binary A...
One-way Association• We can navigate along a single direction only• Denoted by an arrow towards the server objectMay 25, 2...
Example – Association• Ali lives in a HouseMay 25, 2013 COMSATS Institute of Information Technology 99Ali Houselives-in11
Example – Association• Ali drives his CarMay 25, 2013 COMSATS Institute of Information Technology 100Ali Cardrives*1
Two-way Association• We can navigate in both directions• Denoted by a line between the associated objectsMay 25, 2013 COMS...
Example – Two-way Association• Employee works for company• Company employs employeesMay 25, 2013 COMSATS Institute of Info...
Example – Two-way Association• Yasir is a friend of Ali• Ali is a friend of YasirMay 25, 2013 COMSATS Institute of Informa...
Binary Association• Associates objects of exactly two classes• Denoted by a line, or an arrow between the associated objec...
Example – Binary Association• Association “works-for” associates objects of exactlytwo classesMay 25, 2013 COMSATS Institu...
Example – Binary Association• Association “drives” associates objects of exactly twoclassesMay 25, 2013 COMSATS Institute ...
Ternary Association• Associates objects of exactly three classes• Denoted by a diamond with lines connected to associated ...
Example – Ternary Association• Objects of exactly three classes are associatedMay 25, 2013 COMSATS Institute of Informatio...
Example – Ternary Association• Objects of exactly three classes are associatedMay 25, 2013 COMSATS Institute of Informatio...
N-ary Association• An association between 3 or more classes• Practical examples are very rareMay 25, 2013 COMSATS Institut...
Composition• An object may be composed of other smaller objects• The relationship between the “part” objects and the “whol...
Example – Composition of AliMay 25, 2013 COMSATS Institute of Information Technology 112AliBodyArmHeadLeg112 2
Example – Composition of ChairMay 25, 2013 COMSATS Institute of Information Technology 113ChairSeatArmBackLeg112 4
Composition is Stronger• Composition is a stronger relationship, because• Composed object becomes a part of the composer• ...
Example – Composition is Stronger• Ali is made up of different body parts• They can’t exist independent of AliMay 25, 2013...
Example – Composition is Stronger• Chair’s body is made up of different parts• They can’t exist independentlyMay 25, 2013 ...
Aggregation• An object may contain a collection (aggregate) of other objects• The relationship between the container and t...
Example – AggregationMay 25, 2013 COMSATS Institute of Information Technology 118RoomCupboardBedChair Table*111
Example – AggregationMay 25, 2013 COMSATS Institute of Information Technology 119Garden Plant*
Aggregation is Weaker• Aggregation is weaker relationship, because• Aggregate object is not a part of the container• Aggre...
Example – Aggregation is Weaker• Furniture is not an intrinsic part of room• Furniture can be shifted to another room, and...
Example – Aggregation is Weaker• A plant is not an intrinsic part of a garden• It can be planted in some other garden, and...
References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th e...
ThanksMay 25, 2013 COMSATS Institute of Information Technology 124
CSC241:Object OrientedProgrammingSpring 20131. Inheritance Concepts2. PolymorphismMay 25, 2013 COMSATS Intitute of Informa...
Class diagram showinginheritanceMay 25, 2013 COMSATS Intitute of Information Technology 126Inheritance among classes issho...
Association• Objects in an object model interact with each other• Usually an object provides services to several other obj...
Kinds of Association• Class Association• Inheritance• Object Association• Simple Association• Composition• AggregationMay ...
Simple Association• Is the weakest link between objects• Is a reference by which one object can interact with some otherob...
Kinds of Simple Association• w.r.t navigation• One-way Association• Two-way Association• w.r.t number of objects• Binary A...
One-way Association• We can navigate along a single direction only• Denoted by an arrow towards the server objectMay 25, 2...
Example – Association• Ali lives in a HouseMay 25, 2013 COMSATS Intitute of Information Technology 132Ali Houselives-in11
Example – Association• Ali drives his CarMay 25, 2013 COMSATS Intitute of Information Technology 133Ali Cardrives*1
Two-way Association• We can navigate in both directions• Denoted by a line between the associated objectsMay 25, 2013 COMS...
Example – Two-way Association• Employee works for company• Company employs employeesMay 25, 2013 COMSATS Intitute of Infor...
Example – Two-way Association• Yasir is a friend of Ali• Ali is a friend of YasirMay 25, 2013 COMSATS Intitute of Informat...
Binary Association• Associates objects of exactly two classes• Denoted by a line, or an arrow between the associated objec...
Example – Binary Association• Association “works-for” associates objects of exactlytwo classesMay 25, 2013 COMSATS Intitut...
Example – Binary Association• Association “drives” associates objects of exactly twoclassesMay 25, 2013 COMSATS Intitute o...
Ternary Association• Associates objects of exactly three classes• Denoted by a diamond with lines connected to associated ...
Example – Ternary Association• Objects of exactly three classes are associatedMay 25, 2013 COMSATS Intitute of Information...
Example – Ternary Association• Objects of exactly three classes are associatedMay 25, 2013 COMSATS Intitute of Information...
N-ary Association• An association between 3 or more classes• Practical examples are very rareMay 25, 2013 COMSATS Intitute...
Class diagram showingassociation• Association among classes is shown as a simple arrow (ray) in UML (UnifiedModeling Langu...
Composition• An object may be composed of other smaller objects• The relationship between the “part” objects and the “whol...
Class diagram showingcompositionMay 25, 2013 COMSATS Intitute of Information Technology 146Composition among classes is sh...
Example – Composition of AliMay 25, 2013 COMSATS Intitute of Information Technology 147AliBodyArmHeadLeg112 2
Example – Composition of ChairMay 25, 2013 COMSATS Intitute of Information Technology 148ChairSeatArmBackLeg112 4
Composition is Stronger• Composition is a stronger relationship, because• Composed object becomes a part of the composer• ...
Example – Composition is Stronger• Ali is made up of different body parts• They can’t exist independent of AliMay 25, 2013...
Example – Composition is Stronger• Chair’s body is made up of different parts• They can’t exist independentlyMay 25, 2013 ...
Composition• Composition is a ‘consists of’ relationship.• COURSE_DATA consists of STUDENT_DATA (besides other things).• S...
Aggregation• An object may contain a collection (aggregate) of other objects• The relationship between the container and t...
Class diagram showingaggregationMay 25, 2013 COMSATS Intitute of Information Technology 155Aggregation among classes is sh...
Example – AggregationMay 25, 2013 COMSATS Intitute of Information Technology 156RoomCupboardBedChair Table*111
Example – AggregationMay 25, 2013 COMSATS Intitute of Information Technology 157Garden Plant*
Aggregation is Weaker• Aggregation is weaker relationship, because• Aggregate object is not a part of the container• Aggre...
Example – Aggregation is Weaker• Furniture is not an intrinsic part of room• Furniture can be shifted to another room, and...
Example – Aggregation is Weaker• A plant is not an intrinsic part of a garden• It can be planted in some other garden, and...
More about „struct‟• More on data hiding• By default all the data members of struct areaccessible (through the struct vari...
More about „struct‟ …struct TEST{int x;}TEST var;var.x = 10;May 25, 2013 National University of Computer and Emerging Scie...
More about „struct‟ …struct stack {int data[100];int top;} S;///////////////////////////////////void push(stack S, int a){...
More about „struct‟ …struct TEST{private:int x;public:void Setx(int val) { x = val; };int Getx() { return x; };}TEST var;v...
Member functions definitionMay 25, 2013 National University of Computer and Emerging Sciences 165struct TEST {private:int ...
Class Compatibility• A class is behaviorally compatible with another if it supports all theoperations of the other class• ...
…Class Compatibility• Derived class is usually a subtype of the base class• It can handle all the legal messages (operatio...
Example – Class CompatibilityMay 25, 2013 COMSATS Intitute of Information Technology 168ShapecolorverticesmovesetColordraw...
Example – Class CompatibilityMay 25, 2013 COMSATS Intitute of Information Technology 169Filesize…openprint…ASCII File…prin...
Polymorphism• In general, polymorphism refers to existence of different forms of asingle entity• For example, both Diamond...
Polymorphism in OO Model• In OO model, polymorphism means that different objects can behavein different ways for the same ...
Example – PolymorphismMay 25, 2013 COMSATS Intitute of Information Technology 172ShapeLine Circle Triangledrawdrawdraw dra...
Example – PolymorphismMay 25, 2013 COMSATS Intitute of Information Technology 173FileASCII File PDF File PS Fileprintprint...
Polymorphism – Advantages• Messages can be interpreted in different waysdepending upon the receiver classMay 25, 2013 COMS...
Polymorphism – Advantages• New classes can be added without changing the existingmodelMay 25, 2013 COMSATS Intitute of Inf...
Polymorphism – Advantages• In general, polymorphism is a powerful tool to develop flexible andreusable systemsMay 25, 2013...
Object-OrientedModelingAn ExampleMay 25, 2013 COMSATS Intitute of Information Technology 177
Problem Statement• Develop a graphic editor that can draw different geometric shapessuch as line, circle and triangle. Use...
Identify ClassesExtract nouns in the problem statement• Develop a graphic editor that can draw different geometric shapes...
…Identify ClassesEliminate irrelevant classes• Editor – Very broad scope• User – Out of system boundaryMay 25, 2013 COMSA...
…Identify ClassesAdd classes by analyzing requirements• Group – required to behave as a shape• “Individual shapes can be ...
…Identify Classes• Shape• Line• Circle• Triangle• MenuMay 25, 2013 COMSATS Intitute of Information Technology 182• Group• ...
Object Model – Graphic EditorMay 25, 2013 COMSATS Intitute of Information Technology 183LineCircleTriangleGroupShapeViewMenu
Identify AssociationsExtract verbs connecting objects•“Individual shapes can be grouped together”• Group consists of line...
… Identify AssociationsVerify access paths• View contains shapes• View contains lines• View contains circles• View contai...
… Identify AssociationsVerify access paths• Menu sends message to View(Simple One-Way Association)May 25, 2013 COMSATS In...
Object Model – Graphic EditorMay 25, 2013 COMSATS Intitute of Information Technology 187TriangleCircleLineShapeViewnnnnnnn...
Identify AttributesExtract properties of the object• From the problem statement• Properties are not mentionedMay 25, 2013...
…Identify AttributesExtract properties of the object• From the domain knowledgeMay 25, 2013 COMSATS Intitute of Informati...
…Identify AttributesExtract properties of the object• From the domain knowledgeMay 25, 2013 COMSATS Intitute of Informati...
Object Model – Graphic EditorMay 25, 2013 COMSATS Intitute of Information Technology 191MenunameisOpenViewnoOfObjectsselec...
Identify OperationsExtract verbs connected with an objectMay 25, 2013 COMSATS Intitute of Information Technology 192• Dev...
… Identify OperationsEliminate irrelevant operations• Develop – out of system boundary• Behave – have broad semanticsMay ...
…Identify OperationsFollowing are selected operations:May 25, 2013 COMSATS Intitute of Information Technology 194• Line– ...
…Identify OperationsFollowing are selected operations:May 25, 2013 COMSATS Intitute of Information Technology 195• Triang...
…Identify OperationsFollowing are selected operations:May 25, 2013 COMSATS Intitute of Information Technology 196• Group–...
…Identify OperationsExtract operations using domain knowledgeMay 25, 2013 COMSATS Intitute of Information Technology 197•...
GroupnoOfObjectsdraw()Triangleangledraw()nnCircleradiusdraw()nnLinelengthdraw()nnShapecolorverticesdraw()select()move()rot...
Identify InheritanceSearch “is a kind of” by looking at keywords like “such as”, “forexample”, etc• “…shapes such as line...
…Identify InheritanceBy analyzing requirements• “Individual shapes can be grouped together and can behave as asingle shap...
Refining the Object Model• Application of inheritance demands an iteration over the wholeobject model• In the inheritance ...
…Refining the Object ModelShare associations• View contains all kind of shapes• Group consists of all kind of shapesMay 2...
…Refining the Object ModelShare attributes• Shape – Line, Circle, Triangle and Group• Color, verticesMay 25, 2013 COMSATS...
…Refining the Object ModelShare operations• Shape – Line, Circle, Triangle and Group• Select• Move• RotateMay 25, 2013 CO...
…Refining the Object ModelShare the interface and override implementation• Shape – Line, Circle, Triangle and Group• Draw...
Linelengthdraw()Circleradiusdraw()Triangleangledraw()GroupnoOfObjectsdraw()Shapecolorverticesdraw()select()move()rotate()n...
GroupnoOfObjectsdraw()Triangleangledraw()nnCircleradiusdraw()nnLinelengthdraw()nnShapecolorverticesdraw()select()move()rot...
Class• Class is a tool to realize objects• Class is a tool for defining a new typeMay 25, 2013 COMSATS Intitute of Informa...
Example• Lion is an object• Student is an object• Both has some attributes and some behaviorsMay 25, 2013 COMSATS Intitute...
Uses• The problem becomes easy to understand• Interactions can be easily modeledMay 25, 2013 COMSATS Intitute of Informati...
Type in C++• Mechanism for user defined types are• Structures• Classes• Built-in types are like int, float and double• Use...
Abstraction• Only include details in the system that are required for making afunctional system• Student• Name• Address• S...
Defining a New User Defined Typeclass ClassName{…DataType MemberVariable;ReturnType MemberFunction();…};May 25, 2013 COMSA...
Exampleclass Student{int rollNo;char *name;float CGPA;char *address;…void setName(char *newName);void setRollNo(int newRol...
Why Member Function• They model the behaviors of an object• Objects can make their data invisible• Object remains in consi...
ExampleStudent aStudent;aStudent.rollNo = 514;aStudent.rollNo = -514; //ErrorMay 25, 2013 COMSATS Intitute of Information ...
Object and Class• Object is an instantiation of a user defined type or a classMay 25, 2013 COMSATS Intitute of Information...
Declaring class variables• Variables of classes (objects) are declared just like variables ofstructures and built-in data ...
Accessing members• Members of an object can be accessed using• dot operator (.) to access via the variable name• arrow ope...
Exampleclass Student{int rollNo;void setRollNo(intaNo);};Student aStudent;aStudent.rollNo;May 25, 2013 COMSATS Intitute of...
struct -> class transition!class TEST {private:int x;public:void Setx(int val) { x = val; };int Getx() { return x; };}main...
Diff. between struct & classclass TEST {int x;void Setx(int val) { x = val; };int Getx() { return x; };}main() {TEST var;v...
Diff. between struct & classclass TEST {int x;public:void Setx(int val) { x = val; };int Getx() { return x; };}main() {TES...
Access specifiersMay 25, 2013 COMSATS Intitute of Information Technology 224
Access specifiers• There are three access specifiers• ‘public’ is used to tell that member can be accessed whenever you ha...
Exampleclass Student{private:char * name;int rollNo;public:void setName(char *);void setRollNo(int);...};May 25, 2013 COMS...
Exampleclass Student{...int rollNo;public:void setRollNo(int aNo);};int main(){Student aStudent;aStudent.SetRollNo(1);}May...
Default access specifiers• When no access specifier is mentioned then by default the member isconsidered private memberMay...
Exampleclass Student{char * name;int RollNo;};class Student{private:char * name;int RollNo;};May 25, 2013 COMSATS Intitute...
Exampleclass Student{char * name;int RollNo;void SetName(char *);};Student aStudent;aStudent.SetName(Ali);May 25, 2013 COM...
Exampleclass Student{char * name;int RollNo;public:void setName(char *);};Student aStudent;aStudent.SetName(“Ali”);May 25,...
Unified Modeling Language (UML) class diagramMay 25, 2013 National University of Computer and Emerging Sciences 232 of 211...
Assignment (CP)• Install IBM Rational Rose or any other UML tool and draw thediagrams used in this lecture and take a prin...
References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th e...
ThanksMay 25, 2013 COMSATS Intitute of Information Technology 235
CSC241:Object OrientedProgrammingSpring 20131. Inheritance Concepts2. PolymorphismMay 25, 2013 COMSATS Intitute of Informa...
Review• Class• Concept• Definition• Data members• Member Functions• Access specifier
Member Functions• Member functions are the functions that operate on the dataencapsulated in the class• Public member func...
Member Functions (contd.)• Define member function inside the class definitionOR• Define member function outside the class ...
Function Inside Class Bodyclass ClassName {…public:ReturnType FunctionName() {…}};
Example•Define a class of student that hasa roll number. This class shouldhave a function that can be usedto set the roll ...
Exampleclass Student{int rollNo;public:void setRollNo(int aRollNo){rollNo = aRollNo;}};
Function Outside Class Bodyclass ClassName{…public:ReturnType FunctionName();};ReturnType ClassName::FunctionName(){…}Scop...
Exampleclass Student{…int rollNo;public:void setRollNo(int aRollNo);};void Student::setRollNo(int aRollNo){…rollNo = aRoll...
Inline Functions• Instead of calling an inline function compiler replaces the code at thefunction call point• Keyword ‘inl...
Exampleinline int Area(int len, int hi){return len * hi;}int main(){cout << Area(10,20);}
Inline Functions• If we define the function inside the class body then the function is bydefault an inline function• In ca...
Exampleclass Student{int rollNo;public:void setRollNo(int aRollNo){…rollNo = aRollNo;}};
Exampleclass Student{…public:inline void setRollNo(int aRollNo);};void Student::setRollNo(int aRollNo){…rollNo = aRollNo;}
Exampleclass Student{…public:void setRollNo(int aRollNo);};inline void Student::setRollNo(intaRollNo){…rollNo = aRollNo;}
Exampleclass Student{…public:inline void setRollNo(int aRollNo);};inline void Student::setRollNo(intaRollNo){…rollNo = aRo...
Constructor
Constructor• Constructor is used to initialize the objects of a class• Constructor is used to ensure that object is in wel...
Constructor (contd.)• Constructor is a special function having same name as the class name• Constructor does not have retu...
Exampleclass Student{…public:Student(){rollNo = 0;…}};
Exampleint main(){Student aStudent;/*constructor is implicitly called at thispoint*/}
Default Constructor• Constructor without any argument is called default constructor• If we do not define a default constru...
Exampleclass Student{int rollNo;char *name;float GPA;public:… //no constructors};
ExampleCompiler generated default constructor{rollNo = 0;GPA = 0.0;name = NULL;}
Constructor Overloading• Constructors can have parameters• These parameters are used to initialize the data members with u...
Exampleclass Student{…public:Student();Student(char * aName);Student(char * aName, int aRollNo);Student(int aRollNo, int a...
ExampleStudent::Student(int aRollNo,char * aName){if(aRollNo < 0){rollNo = 0;}else {rollNo = aRollNo;}…}
Exampleint main(){Student student1;Student student2(“Name”);Student student3(”Name”, 1);Student student4(”Name”,1,4.0);}
Constructor Overloading• Use default parameter value to reduce the writing effort
ExampleStudent::Student( char * aName = NULL,int aRollNo= 0,float aGPA = 0.0){…}Is equivalent toStudent();Student(char * a...
References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th e...
How to correctly Search for asoftware @ google• When we need a software, the first place where wego is at Google Search. I...
ThanksMay 25, 2013 COMSATS Intitute of Information Technology 268
CSC241:Object OrientedProgrammingSpring 20131. FunctionsPlease turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aa...
Revision• Chapter 5 of bookMay 25, 2013 COMSATS Intitute of Information Technology 270
FunctionsMay 25, 2013 COMSATS Intitute of Information Technology 271 A function groups a number of program statements int...
Return typeInput argumentsMay 25, 2013 COMSATS Intitute of Information Technology 272
FunctionsMay 25, 2013 COMSATS Intitute of Information Technology 273//demonstrates a simple function#include <iostream>usi...
FunctionsMay 25, 2013 COMSATS Intitute of Information Technology 274 Each integer read is passed to the cube() function b...
Default ArgumentsMay 25, 2013 COMSATS Intitute of Information Technology 275#include <iostream>using namespace std;//decla...
Inline FunctionMay 25, 2013 COMSATS Intitute of Information Technology 276 A function call involves substantial overhead....
Inline FunctionMay 25, 2013 COMSATS Intitute of Information Technology 277// demonstrates inline functions#include <iostre...
RecursionMay 25, 2013 COMSATS Intitute of Information Technology 278 The existence of functions makes possible aprogrammi...
RecursionMay 25, 2013 COMSATS Intitute of Information Technology 279#include <iostream>using namespace std;// calls itself...
RecursionMay 25, 2013 COMSATS Intitute of Information Technology 280
References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th e...
ThanksMay 25, 2013 COMSATS Intitute of Information Technology 282
CSC241:Object OrientedProgrammingSpring 20131. ConstructorsMay 25, 2013 COMSATS Intitute of Information Technology283Pleas...
Constructor
Constructor• Constructor is used to initialize the objects of a class• Constructor is used to ensure that object is in wel...
Constructor (contd.)• Constructor is a special function having same name as the class name• Constructor does not have retu...
Exampleclass Student{…public:Student(){rollNo = 0;…}};
Exampleint main(){Student aStudent;/*constructor is implicitly called at thispoint*/}
Default Constructor• Constructor without any argument is called default constructor• If we do not define a default constru...
Exampleclass Student{int rollNo;char *name;float GPA;public:… //no constructors};
ExampleCompiler generated default constructor{rollNo = 0;GPA = 0.0;name = NULL;}
Constructor Overloading• Constructors can have parameters• These parameters are used to initialize the data members with u...
Exampleclass Student{…public:Student();Student(char * aName);Student(char * aName, int aRollNo);Student(char * aName, int ...
ExampleStudent::Student(int aRollNo,char * aName){if(aRollNo < 0){rollNo = 0;}else {rollNo = aRollNo;}…}
Exampleint main(){Student student1;Student student2(“Name”);Student student3(”Name”, 1);Student student4(”Name”,1,4.0);}
Constructor Overloading• Use default parameter value to reduce the writing effort
ExampleStudent::Student( char * aName = NULL,int aRollNo= 0,float aGPA = 0.0){…}Is equivalent toStudent();Student(char * a...
Copy Constructor• Copy constructor are used when:• Initializing an object at the time of creation• When an object is passe...
Examplevoid func1(Student student){…}int main(){Student studentA;Student studentB = studentA;func1(studentA);}
Copy Constructor (Syntax)Student::Student(const Student &obj){rollNo = obj.rollNo;name = obj.name;GPA = obj.GPA;}
Shallow Copy• When we initialize one object with another then the compiler copiesstate of one object to the other• This ki...
ExampleStudent studentA;Student studentB = studentA;NameGPARollNostudentANameGPARollNostudentBAHMAD…Memory
Assignment• Lab Assignment No 3May 25, 2013 COMSATS Intitute of Information Technology 303
References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th e...
ThanksMay 25, 2013 COMSATS Intitute of Information Technology 305
CSC241:Object OrientedProgrammingSpring 20131. DestructorPlease turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan A...
Review•Copy constructors•Destructor•this Pointer•Separation of interface andimplementation
Destructor• You might guess that another function is calledautomatically when an object is destroyed. This is indeedthe ca...
Using DestructorMay 25, 2013 COMSATS Intitute of Information Technology 309// foo.cpp demonstrates destructor#include <ios...
this Pointer•There are situations wheredesigner wants to returnreference to current object from afunction•In such cases re...
ExampleStudent Student::setRollNo(int aNo){…return *this;}Student Student::setName(char *aName){…return *this;}
Exampleint main(){Student aStudent;Student bStudent;bStudent = aStudent.setName(“Ahmad”);…bStudent = aStudent.setName(“Ali...
Separation of interface andimplementation•Public member function exposed by aclass is called interface•Separation of imple...
Complex Number•There are two representations of complexnumber• Euler form• z = x + i y• Phasor form• z = |z| (cos  + i si...
Examplefloat getX()float getY()void setNumber(float i, float j)…float xfloat yComplexOld implementationfloat getX()float g...
Exampleclass Complex{ //oldfloat x;float y;public:void setNumber(float i, float j){x = i;y = j;}…};
Exampleclass Complex{ //newfloat z;float theta;public:void setNumber(float i, float j){theta = arctan(j/i);…}…};
Advantages•User is only concerned about ways of accessingdata (interface)•User has no concern about the internalrepresenta...
Separation of interface andimplementation•Usually functions are defined in implementationfiles (.cpp) while the class defi...
Student.hclass Student{int rollNo;public:void setRollNo(int aRollNo);int getRollNo();…};
Student.cpp#include “student.h”void Student::setRollNo(int aNo){…}int Student::getRollNo(){…}
Driver.cpp#include “student.h”int main(){Student aStudent;}
Classes, Objects and Memory• you might have the impression that each object createdfrom a class contains separate copies o...
May 25, 2013 COMSATS Intitute of Information Technology 324
References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th e...
ThanksMay 25, 2013 COMSATS Intitute of Information Technology 326
CSC241:Object OrientedProgrammingSpring 20131. Static class member2. Const member functionPlease turn OFF your Mobile Phon...
static class member• What is a static variable? What is its scope (local, file)and storage class (automatic, static).• Wha...
static class member dataclass foo {private:static int count; //note: “declaration” only!public:foo() //incr count when obj...
static class member• For multiple objects of the same class, new memory isallocated for data members and shared memory for...
static class member• Why this two-part approach?• If static member data were defined inside the class (as itactually was i...
static class member• Be careful:• It’s easy to handle static data incorrectly, and the compiler isnot helpful about such e...
Variable packing in memory• If you do a ‘sizeof(class_obj_or_name)’ for an object ofa class/struct or class/struct name, y...
Data member packing inclass/structclass Counter{private:unsigned char count;unsigned char temp2;short temp1;int temp;stati...
const Member Functions•There are functions that are meant to beread only•There must exist a mechanism to detecterror if su...
Examplebool Student::isRollNo(int aNo){if(rollNo = = aNo){return true;}return false;}May 25, 2013 COMSATS Intitute of Info...
Examplebool Student::isRollNo(int aNo){/*undetected typing mistake*/if(rollNo = aNo){return true;}return false;}May 25, 20...
Examplebool Student::isRollNo(int aNo)const{/*compiler error*/if(rollNo = aNo){return true;}return false;}May 25, 2013 COM...
const Member Functions•Keyword const is placed at the end of theparameter listMay 25, 2013 COMSATS Intitute of Information...
const Member FunctionsDeclaration:class ClassName{ReturnVal Function() const;};Definition:ReturnVal ClassName::Function() ...
Exampleclass Student{public:int getRollNo() const {return rollNo;}};May 25, 2013 COMSATS Intitute of Information Technolog...
const Functions•Constant member functions cannot modify thestate of any object•They are just “read-only”•Errors due to typ...
const Functions•Constructors and Destructors cannot be const•Constructor and destructor are used to modifythe object to a ...
Exampleclass Time{public:Time() const {} //error…~Time() const {} //error…};May 25, 2013 COMSATS Intitute of Information T...
const Function•Constant member function cannot changedata member•Constant member function cannot accessnon-constant member...
Exampleclass Student{char * name;public:char *getName();void setName(char * aName);int ConstFunc() const{name = getName();...
May 25, 2013 COMSATS Intitute of Information Technology 347
References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th e...
ThanksMay 25, 2013 COMSATS Intitute of Information Technology 349
CSC241:Object OrientedProgrammingSpring 20131. Arrays & String (Chapter7)Please turn OFF your Mobile Phones!Saturday, May ...
Arrays In everyday life we commonly group similarobjects into units. We buy eggs by the carton. In computer languages we...
Defining, Reading and Writing Array// gets four ages from user, displays them#include <iostream>using namespace std;int ma...
Calculating Average#include <iostream>using namespace std;int main(){double avg, sum = 0 ;int i ; int marks[10] ; /* array...
Using Direct Access on an Array// Using Direct Access on Array#include <iostream>using namespace std;int main(){int mem[]=...
Printing in Reverse Order#include <iostream>using namespace std;int main(){const int SIZE=5; // defines the size N for 5 e...
Out of Bounds#include <iostream>using namespace std;int main(){float a[] = { 22.2,44.4, 66.6 };float x=11.1;cout << "I m g...
Passing Array to Function#include <iostream>using namespace std;int sum(int[],int); // declarationint main(){int a[] = { 1...
n Dimensional Arrays#include <iostream>using namespace std;int main(){ const int row=2, col=3; int i,j;int ary[row][col] =...
n Dimensional Arrays0x22ff40 = 110x22ff44 = 120x22ff48 = 130x22ff4C = 210x22ff50 = 220x22ff54 = 23ary[0][0]=ary[0][1]=ary[...
2-Dimensional Arrays#include <iostream>using namespace std;int main(){ const int row=3, col=3; int i,j;int ary[row][col] =...
3-Dimensional Arrays0x22ff30 = 110x22ff34 = 120x22ff38 = 130x22ff3C = 210x22ff40 = 220x22ff44 = 23ary[0][0]=ary[0][1]=ary[...
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
All in 1
Upcoming SlideShare
Loading in...5
×

All in 1

710

Published on

Full terminal pack for BSCS-2

Published in: Education, Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
710
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
47
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Transcript of "All in 1"

  1. 1. OOP COMPLETE NOTESBYUmer Tanvir
  2. 2. CSC241:Object OrientedProgrammingSpring 20131. Starting OOPMay25,2013COMSATSInstituteofInformationTechnology2Please turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  3. 3. Study Assignment• I hope you did go through chapter 1 of both the books.• How was the experience?• What did you learn?May 25, 2013 COMSATS Institute of Information Technology 3
  4. 4. Procedural vs. Object-Oriented• ProceduralWithdraw, deposit, transfer• Object OrientedCustomer, money, accountMay 25, 2013 COMSATS Institute of Information Technology 4
  5. 5. Object-Orientation(OO)May 25, 2013 COMSATS Institute of Information Technology 5
  6. 6. What is Object-Orientation?• A technique for system modeling• OO model consists of several interacting objectsMay 25, 2013 COMSATS Institute of Information Technology 6
  7. 7. What is a Model?• A model is an abstraction of something• Purpose is to understand the product before developing itMay 25, 2013 COMSATS Institute of Information Technology 7
  8. 8. Examples – Model• Highway maps• Architectural models• Mechanical modelsMay 25, 2013 COMSATS Institute of Information Technology 8
  9. 9. Example – OO ModelMay 25, 2013 COMSATS Institute of Information Technology 9
  10. 10. …Example – OO Model• Objects• Ali• House• Car• Tree• Interactions• Ali lives in the house• Ali drives the carMay 25, 2013 COMSATS Institute of Information Technology 10AliCarHouseTreelives-indrives
  11. 11. Object-Orientation - Advantages• People think in terms of objects• OO models map to reality• Therefore, OO models are• easy to develop• easy to understandMay 25, 2013 COMSATS Institute of Information Technology 11
  12. 12. What is an Object?An object is• Something tangible (Ali, Car)• Something that can be apprehended intellectually (Time, Date)May 25, 2013 COMSATS Institute of Information Technology 12
  13. 13. … What is an Object?An object has• State (attributes)• Well-defined behaviour (operations)• Unique identityMay 25, 2013 COMSATS Institute of Information Technology 13
  14. 14. Example – Ali is a Tangible Object• State (attributes)• Name• Age• behaviour (operations)• Walks• Eats• Identity• His nameMay 25, 2013 COMSATS Institute of Information Technology 14
  15. 15. Example – Car is a Tangible Object• State (attributes)- Color- Model• behaviour (operations)- Start Car- Accelerate- Change Gear• Identity- Its registration numberMay 25, 2013 COMSATS Institute of Information Technology 15
  16. 16. Example – Time is an Object ApprehendedIntellectually• State (attributes)- Hours - Seconds- Minutes• behaviour (operations)- Set Hours - Set Seconds- Set Minutes• Identity- Would have a unique ID in the modelMay 25, 2013 COMSATS Institute of Information Technology 16
  17. 17. Example – Date is an Object ApprehendedIntellectually• State (attributes)- Year - Day- Month• behaviour (operations)- Set Year - Set Day- Set Month• Identity- Would have a unique ID in the modelMay 25, 2013 COMSATS Institute of Information Technology 17
  18. 18. Definition• What Is an Object?• An object is a software bundle of related variables and methods.Software objects are often used to model real-world objects you findin everyday life.• Objects are key to understanding object-oriented technology. You canlook around you now and see many examples of real-world objects:dog, desk, television set, bicycle.May 25, 2013 COMSATS Institute of Information Technology 18
  19. 19. Real-world objects share two characteristics• They all have state and behavior• dogs have state (name, color, breed, hungry) and behavior (barking,fetching, and wagging tail).• Bicycles have state (current gear, current pedal cadence, two wheels,number of gears) and behavior (braking, accelerating, slowing down,changing gears).May 25, 2013 COMSATS Institute of Information Technology 19
  20. 20. Software objects are modeled after real-worldobjects• A software object maintains its state in one or more variables .• A software object implements its behavior with methods . A methodis a function (subroutine) associated with an object.May 25, 2013 COMSATS Institute of Information Technology 20
  21. 21. Can represent real-world objects by usingsoftware objects.• You might want to represent real-world dogs as software objects in ananimation program or a real-world bicycle as a software object in theprogram that controls an electronic exercise bike.• You can also use software objects to model abstract concepts. Forexample, an event is a common object used in GUI window systems torepresent the action of a user pressing a mouse button or a key onthe keyboard.May 25, 2013 COMSATS Institute of Information Technology 21
  22. 22. Moving to new thinking …• C is a procedural language. A procedure is a list ofinstructions.• Very small programs (tens of lines) need no organization.• As they get large (hundreds of lines), they are divided intofunctions.• Functions are still lists of instructions.• Dividing a program into functions gives a structure to theprogram (hence structured programming).May 25, 2013 COMSATS Institute of Information Technology 22
  23. 23. Moving to new thinking …• C programming cannot do the following well:• Functions have unrestricted access to global data.• Data and Functions are unrelated; they do not form alogical group or show any form of binding.• Cannot model ‘real world’.• In real world, we deal with objects like cars, peopleetc.• Are such objects like ‘data’? Which data type describes acar, for example?• Are such objects like ‘functions’? What will a function car()do?May 25, 2013 COMSATS Institute of Information Technology 23
  24. 24. Moving to new thinking …• A real world object, e.g. car:• Is its description purely the ability to have a ‘data type’ torepresent its specifications or ‘attributes’ only? Forexample what attributes describe a car?• So by having all these attributes ‘only’ do you know allabout a car? Would you buy a car by merely looking atthese attributes and their values?• No! What else do you wish to have?May 25, 2013 COMSATS Institute of Information Technology 24
  25. 25. Moving to new thinking …• A real world object, e.g. car:• Test drive! Right?• What would you know through a test drive: how it‘behaves’ in response to various stimulus!• How can it negotiate a speed braker, a speedy turn, full brakingetc.• Effectively, you wish to know how it ‘functions’.• Behaviour is like a function.• So neither data nor functions, by themselves, modelreal-world objects effectively.May 25, 2013 COMSATS Institute of Information Technology 25
  26. 26. Object Oriented Approach …• Neither data nor functions, by themselves, model real-world objects effectively.• OO languages (like C++) combine both ‘data’ and‘functions that operate on that data’ into a single unit,called ‘object’. Hence ‘encapsulating’ an entity.• The objects functions are called member functions.• Typically, data can be accessed through functions only. Sodata gets ‘hidden’.• Data hiding ensures the data is not accidentally altered.• Reference analogy of a growing company; 2 people vs 100employee company.• Objects communicate with each other by calling eachother’s member functions.May 25, 2013 COMSATS Institute of Information Technology 26
  27. 27. Object Oriented Approach …• OOP is all about ‘organization’ and not about programoperation. Most individual statements are similar to Cstatements. Member functions may be very similar toC procedural functions.• In C you used to think about functions.• In C++ you should think about objects.• Often objects in C++ are real-world analogies.• In C++ objects are ‘instances’ of ‘classes’. E.g. HondaCity is an instance of class car!• Class serves as a cookie cutter and an object a cookie.May 25, 2013 COMSATS Institute of Information Technology 27
  28. 28. Abstraction• Abstraction is a way to cope with complexity.• Principle of abstraction:“Capture only those details about an object that are relevant to currentperspective”May 25, 2013 COMSATS Institute of Information Technology 28
  29. 29. Example – Abstraction• Attributes- Name - Employee ID- Student Roll No - Designation- Year of Study - Salary- CGPA - AgeMay 25, 2013 COMSATS Institute of Information Technology 29Ali is a PhD student and teaches BS students
  30. 30. Example – Abstraction• behaviour- Study - DevelopExam- GiveExam - TakeExam- PlaySports - Eat- DeliverLecture - WalkMay 25, 2013 COMSATS Institute of Information Technology 30Ali is a PhD student and teaches BS students
  31. 31. Example – AbstractionAttributes• - Name - Employee ID• - Student Roll No - Designation• - Year of Study - Salary• - CGPA - AgeMay 25, 2013 COMSATS Institute of Information Technology 31Student’s Perspective
  32. 32. Example – Abstraction• behaviour- Study - DevelopExam- GiveExam - TakeExam- PlaySports - Eat- DeliverLecture - WalkMay 25, 2013 COMSATS Institute of Information Technology 32Student’s Perspective
  33. 33. Example – Abstraction• Attributes- Name - Employee ID- Student Roll No - Designation- Year of Study - Salary- CGPA - AgeMay 25, 2013 COMSATS Institute of Information Technology 33Teacher’s Perspective
  34. 34. Example – Abstraction• behaviour- Study - DevelopExam- GiveExam - TakeExam- PlaySports - Eat- DeliverLecture - WalkMay 25, 2013 COMSATS Institute of Information Technology 34Teacher’s Perspective
  35. 35. Example – Abstraction• Ordinary PerspectiveA pet animal with• Four Legs• A Tail• Two Ears• Sharp Teeth• Surgeon’s PerspectiveA being with• A Skeleton• Heart• Kidney• StomachMay 25, 2013 COMSATS Institute of Information Technology 35A cat can be viewed with different perspectives
  36. 36. Example – AbstractionMay 25, 2013 COMSATS Institute of Information Technology 36Driver’s ViewEngineer’s View
  37. 37. Abstraction – Advantages• Simplifies the model by hiding irrelevant details• Abstraction provides the freedom to defer implementation decisionsby avoiding commitment to detailsMay 25, 2013 COMSATS Institute of Information Technology 37
  38. 38. Classes• In an OO model, some of the objects exhibit identical characteristics(information structure and behaviour)• We say that they belong to the same classMay 25, 2013 COMSATS Institute of Information Technology 38
  39. 39. Example – Class• Ali studies mathematics• Anam studies physics• Sohail studies chemistry• Each one is a Student• We say these objects are instances of the Student classMay 25, 2013 COMSATS Institute of Information Technology 39
  40. 40. Example – Class• Ahsan teaches mathematics• Aamir teaches computer science• Atif teaches physics• Each one is a teacher• We say these objects are instances of the Teacher classMay 25, 2013 COMSATS Institute of Information Technology 40
  41. 41. Graphical Representation of ClassesMay 25, 2013 COMSATS Institute of Information Technology 41(Class Name)(attributes)(operations)(Class Name)Normal FormSuppressedForm
  42. 42. Example – Graphical Representation ofClassesMay 25, 2013 COMSATS Institute of Information Technology 42CirclecenterradiusdrawcomputeAreaNormal FormSuppressedFormCircle
  43. 43. Example – Graphical Representation ofClassesMay 25, 2013 COMSATS Institute of Information Technology 43PersonnameagegendereatwalkNormal FormSuppressedFormPerson
  44. 44. Inheritance• A child inherits characteristics of its parents• Besides inherited characteristics, a child may have its own uniquecharacteristicsMay 25, 2013 COMSATS Institute of Information Technology 44
  45. 45. Inheritance in Classes• If a class B inherits from class A then it contains all the characteristics(information structure and behaviour) of class A• The parent class is called base class and the child class is calledderived class• Besides inherited characteristics, derived class may have its ownunique characteristicsMay 25, 2013 COMSATS Institute of Information Technology 45
  46. 46. Example – InheritanceMay 25, 2013 COMSATS Institute of Information Technology 46PersonTeacherDoctorStudent
  47. 47. Example – InheritanceMay 25, 2013 COMSATS Institute of Information Technology 47ShapeCircleTriangleLine
  48. 48. Inheritance – “IS A” or“IS A KIND OF” Relationship• Each derived class is a special kind of its base classMay 25, 2013 COMSATS Institute of Information Technology 48
  49. 49. Example – “IS A” RelationshipMay 25, 2013 COMSATS Institute of Information Technology 49PersonnameagegendereatwalkTeacherdesignationsalaryteachtakeExamStudentprogramstudyYearstudyheldExamDoctordesignationsalarycheckUpprescribe
  50. 50. Example – “IS A” RelationshipMay 25, 2013 COMSATS Institute of Information Technology 50ShapecolorcoorddrawrotatesetColorCircleradiusdrawcomputeAreaLinelengthdrawTriangleangledrawcomputeArea
  51. 51. Inheritance – Advantages• Reuse• Less redundancy• Increased maintainabilityMay 25, 2013 COMSATS Institute of Information Technology 51
  52. 52. Reuse with Inheritance• Main purpose of inheritance is reuse• We can easily add new classes by inheriting from existing classes• Select an existing class closer to the desired functionality• Create a new class and inherit it from the selected class• Add to and/or modify the inherited functionalityMay 25, 2013 COMSATS Institute of Information Technology 52
  53. 53. Example ReuseMay 25, 2013 COMSATS Institute of Information Technology 53ShapecolorcoorddrawrotatesetColorCircleradiusdrawcomputeAreaLinelengthdrawTriangleangledrawcomputeArea
  54. 54. Example ReuseMay 25, 2013 COMSATS Institute of Information Technology 54PersonnameagegendereatwalkTeacherdesignationsalaryteachtakeExamStudentprogramstudyYearstudyheldExamDoctordesignationsalarycheckUpprescribe
  55. 55. Example ReuseMay 25, 2013 COMSATS Institute of Information Technology 55PersonnameagegendereatwalkTeacherdesignationsalaryteachtakeExamStudentprogramstudyYearstudyheldExamDoctordesignationsalarycheckUpprescribe
  56. 56. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May25,2013COMSATSInstituteofInformationTechnology56
  57. 57. ThanksMay 25, 2013 COMSATS Institute of Information Technology 57
  58. 58. CSC241:Object OrientedProgrammingSpring 20131. Inheritance & GeneralizationMay25,2013COMSATSInstituteofInformationTechnology58Please turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  59. 59. Recap – Inheritance• Derived class inherits all the characteristics of the base class• Besides inherited characteristics, derived class may have its ownunique characteristics• Major benefit of inheritance is reuseMay 25, 2013 COMSATS Institute of Information Technology 59
  60. 60. Concepts Related with Inheritance• Generalization• Subtyping (extension)• Specialization (restriction)May 25, 2013 COMSATS Institute of Information Technology 60
  61. 61. Generalization• In OO models, some classes may have common characteristics• We extract these features into a new class and inherit original classesfrom this new class• This concept is known as GeneralizationMay 25, 2013 COMSATS Institute of Information Technology 61
  62. 62. Example – GeneralizationMay 25, 2013 COMSATS Institute of Information Technology 62CirclecolorverticesradiusmovesetColorcomputeAreaLinecolorverticeslengthmovesetColorgetLengthTrianglecolorverticesanglemovesetColorcomputeArea
  63. 63. Example – GeneralizationMay 25, 2013 COMSATS Institute of Information Technology 63ShapecolorverticesmovesetColorCircleradiuscomputeAreaLinelengthgetLengthTriangleanglecomputeArea
  64. 64. Example – GeneralizationMay 25, 2013 COMSATS Institute of Information Technology 64TeachernameagegenderdesignationsalaryteachtakeExameatwalkStudentnameagegenderprogramstudyYearstudyheldExameatwalkDoctornameagegenderdesignationsalarycheckUpprescribeeatwalk
  65. 65. Example – GeneralizationMay 25, 2013 COMSATS Institute of Information Technology 65PersonnameagegendereatwalkTeacherdesignationsalaryteachtakeExamStudentprogramstudyYearstudyheldExamDoctordesignationsalarycheckUpprescribe
  66. 66. Sub-typing & Specialization• We want to add a new class to an existing model• Find an existing class that already implements some of the desiredstate and behaviour• Inherit the new class from this class and add unique behaviour to thenew classMay 25, 2013 COMSATS Institute of Information Technology 66
  67. 67. Sub-typing (Extension)• Sub-typing means that derived class is behaviourally compatible withthe base class• Behaviourally compatible means that base class can be replaced bythe derived classMay 25, 2013 COMSATS Institute of Information Technology 67
  68. 68. Example –Sub-typing(Extension)May 25, 2013 COMSATS Institute of Information Technology 68PersonnameagegendereatswalksStudentprogramstudyYearstudytakeExam
  69. 69. Example –Sub-typing(Extension)May 25, 2013 COMSATS Institute of Information Technology 69ShapecolorverticessetColormoveCircleradiuscomputeCFcomputeArea
  70. 70. Specialization (Restriction)• Specialization means that derived class is behaviourally incompatiblewith the base class• Behaviourally incompatible means that base class can’t always bereplaced by the derived classMay 25, 2013 COMSATS Institute of Information Technology 70
  71. 71. Example – Specialization(Restriction)May 25, 2013 COMSATS Institute of Information Technology 71Personage : [0..100]…Adultage : [18..100]…setAge( a )…setAge( a )…age = aIf age < 18 thenerrorelseage = a
  72. 72. Example – Specialization(Restriction)May 25, 2013 COMSATS Institute of Information Technology 72IntegerSet…NaturalSet…add( elem )…add( elem )…add elementto the setIf elem < 1 thenerrorelseadd elementto the set
  73. 73. Overriding• A class may need to override the default behaviour provided by itsbase class• Reasons for overriding• Provide behaviour specific to a derived class• Extend the default behaviour• Restrict the default behaviour• Improve performanceMay 25, 2013 COMSATS Institute of Information Technology 73
  74. 74. Example – Specific BehaviourMay 25, 2013 COMSATS Institute of Information Technology 74ShapecolorverticesdrawmovesetColorCircleradiusdrawcomputeAreaLinelengthdrawTriangleangledrawcomputeArea
  75. 75. Example – ExtensionMay 25, 2013 COMSATS Institute of Information Technology 75WindowwidthheightopenclosedrawDialogBoxcontrolsenabledraw1- Invoke Window’sdraw2- draw the dialogbox
  76. 76. Example – RestrictionMay 25, 2013 COMSATS Institute of Information Technology 76IntegerSet…NaturalSet…add( elem )…add( elem )…Add element tothe setIf elem < 1 thengive errorelseAdd element tothe set
  77. 77. Example – Improve Performance• Class Circle overridesrotate operation of classShape with a Nulloperation.May 25, 2013 COMSATS Institute of Information Technology 77ShapecolorcoorddrawrotatesetColorCircleradiusdrawrotate
  78. 78. Abstract Classes• An abstract class implements an abstract concept• Main purpose is to be inherited by other classes• Can’t be instantiated• Promotes reuseMay 25, 2013 COMSATS Institute of Information Technology 78
  79. 79. Example – Abstract Classes• Here, Person is an abstract classMay 25, 2013 COMSATS Institute of Information Technology 79TeacherDoctorStudentPersonnameagegendereatwalk
  80. 80. Example – Abstract Classes• Here, Vehicle is an abstract classMay 25, 2013 COMSATS Institute of Information Technology 80BusTruckCarVehiclecolormodelaccelerateapplyBrakes
  81. 81. Concrete Classes• A concrete class implements a concrete concept• Main purpose is to be instantiated• Provides implementation details specific to the domain contextMay 25, 2013 COMSATS Institute of Information Technology 81
  82. 82. Example – Concrete Classes• Here, Student, Teacher and Doctor are concreteclassesMay 25, 2013 COMSATS Institute of Information Technology 82TeacherDoctorStudentprogramstudyYearstudyheldExamPerson
  83. 83. Example – Concrete ClassesMay 25, 2013 COMSATS Institute of Information Technology 83• Here, Car, Bus and Truck are concrete classesBusCarVehicleTruckcapacityloadunload
  84. 84. Multiple Inheritance• We may want to reuse characteristics of more than one parent classMay 25, 2013 COMSATS Institute of Information Technology 84
  85. 85. Example – Multiple InheritanceMay 25, 2013 COMSATS Institute of Information Technology 85Mermaid
  86. 86. Example – Multiple InheritanceMay 25, 2013 COMSATS Institute of Information Technology 86MermaidWoman Fish
  87. 87. Example – Multiple InheritanceMay 25, 2013 COMSATS Institute of Information Technology 87Amphibious Vehicle
  88. 88. Example – Multiple InheritanceMay 25, 2013 COMSATS Institute of Information Technology 88Amphibious VehicleLand Vehicle Water VehicleVehicleCar Boat
  89. 89. Problems with Multiple Inheritance• Increased complexity• Reduced understanding• Duplicate featuresMay 25, 2013 COMSATS Institute of Information Technology 89
  90. 90. Problem – Duplicate Features• Which eat operation Mermaid inherits?May 25, 2013 COMSATS Institute of Information Technology 90MermaidWoman Fisheat…eat…
  91. 91. Solution – Override the Common FeatureMay 25, 2013 COMSATS Institute of Information Technology 91MermaidWoman Fisheat…eat…eat…Invoke eatoperation ofdesired class
  92. 92. Problem – Duplicate Features(Diamond Problem)• Which changeGear operation Amphibious Vehicleinherits?May 25, 2013 COMSATS Institute of Information Technology 92Amphibious VehicleLand Vehicle Water VehicleVehicleCar BoatchangeGear
  93. 93. Solution to Diamond Problem• Some languages disallow diamond hierarchy• Others provide mechanism to ignore characteristicsfrom one sideMay 25, 2013 COMSATS Institute of Information Technology 93
  94. 94. Association• Objects in an object model interact with each other• Usually an object provides services to several other objects• An object keeps associations with other objects to delegate tasksMay 25, 2013 COMSATS Institute of Information Technology 94
  95. 95. Kinds of Association• Class Association• Inheritance• Object Association• Simple Association• Composition• AggregationMay 25, 2013 COMSATS Institute of Information Technology 95
  96. 96. Simple Association• Is the weakest link between objects• Is a reference by which one object can interact with some otherobject• Is simply called as “association”May 25, 2013 COMSATS Institute of Information Technology 96
  97. 97. Kinds of Simple Association• w.r.t navigation• One-way Association• Two-way Association• w.r.t number of objects• Binary Association• Ternary Association• N-ary AssociationMay 25, 2013 COMSATS Institute of Information Technology 97
  98. 98. One-way Association• We can navigate along a single direction only• Denoted by an arrow towards the server objectMay 25, 2013 COMSATS Institute of Information Technology 98
  99. 99. Example – Association• Ali lives in a HouseMay 25, 2013 COMSATS Institute of Information Technology 99Ali Houselives-in11
  100. 100. Example – Association• Ali drives his CarMay 25, 2013 COMSATS Institute of Information Technology 100Ali Cardrives*1
  101. 101. Two-way Association• We can navigate in both directions• Denoted by a line between the associated objectsMay 25, 2013 COMSATS Institute of Information Technology 101
  102. 102. Example – Two-way Association• Employee works for company• Company employs employeesMay 25, 2013 COMSATS Institute of Information Technology 102Employee Companyworks-for1*
  103. 103. Example – Two-way Association• Yasir is a friend of Ali• Ali is a friend of YasirMay 25, 2013 COMSATS Institute of Information Technology 103Yasir Alifriend11
  104. 104. Binary Association• Associates objects of exactly two classes• Denoted by a line, or an arrow between the associated objectsMay 25, 2013 COMSATS Institute of Information Technology 104
  105. 105. Example – Binary Association• Association “works-for” associates objects of exactlytwo classesMay 25, 2013 COMSATS Institute of Information Technology 105Employee Companyworks-for1*
  106. 106. Example – Binary Association• Association “drives” associates objects of exactly twoclassesMay 25, 2013 COMSATS Institute of Information Technology 106Ali Cardrives*1
  107. 107. Ternary Association• Associates objects of exactly three classes• Denoted by a diamond with lines connected to associated objectsMay 25, 2013 COMSATS Institute of Information Technology 107
  108. 108. Example – Ternary Association• Objects of exactly three classes are associatedMay 25, 2013 COMSATS Institute of Information Technology 108Student TeacherCourse1**
  109. 109. Example – Ternary Association• Objects of exactly three classes are associatedMay 25, 2013 COMSATS Institute of Information Technology 109Project LanguagePerson*1*
  110. 110. N-ary Association• An association between 3 or more classes• Practical examples are very rareMay 25, 2013 COMSATS Institute of Information Technology 110
  111. 111. Composition• An object may be composed of other smaller objects• The relationship between the “part” objects and the “whole” objectis known as Composition• Composition is represented by a line with a filled-diamond headtowards the composer objectMay 25, 2013 COMSATS Institute of Information Technology 111
  112. 112. Example – Composition of AliMay 25, 2013 COMSATS Institute of Information Technology 112AliBodyArmHeadLeg112 2
  113. 113. Example – Composition of ChairMay 25, 2013 COMSATS Institute of Information Technology 113ChairSeatArmBackLeg112 4
  114. 114. Composition is Stronger• Composition is a stronger relationship, because• Composed object becomes a part of the composer• Composed object can’t exist independentlyMay 25, 2013 COMSATS Institute of Information Technology 114
  115. 115. Example – Composition is Stronger• Ali is made up of different body parts• They can’t exist independent of AliMay 25, 2013 COMSATS Institute of Information Technology 115
  116. 116. Example – Composition is Stronger• Chair’s body is made up of different parts• They can’t exist independentlyMay 25, 2013 COMSATS Institute of Information Technology 116
  117. 117. Aggregation• An object may contain a collection (aggregate) of other objects• The relationship between the container and the contained object iscalled aggregation• Aggregation is represented by a line with unfilled-diamond headtowards the containerMay 25, 2013 COMSATS Institute of Information Technology 117
  118. 118. Example – AggregationMay 25, 2013 COMSATS Institute of Information Technology 118RoomCupboardBedChair Table*111
  119. 119. Example – AggregationMay 25, 2013 COMSATS Institute of Information Technology 119Garden Plant*
  120. 120. Aggregation is Weaker• Aggregation is weaker relationship, because• Aggregate object is not a part of the container• Aggregate object can exist independentlyMay 25, 2013 COMSATS Institute of Information Technology 120
  121. 121. Example – Aggregation is Weaker• Furniture is not an intrinsic part of room• Furniture can be shifted to another room, and so can existindependent of a particular roomMay 25, 2013 COMSATS Institute of Information Technology 121
  122. 122. Example – Aggregation is Weaker• A plant is not an intrinsic part of a garden• It can be planted in some other garden, and so can exist independentof a particular gardenMay 25, 2013 COMSATS Institute of Information Technology 122
  123. 123. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May25,2013COMSATSInstituteofInformationTechnology123
  124. 124. ThanksMay 25, 2013 COMSATS Institute of Information Technology 124
  125. 125. CSC241:Object OrientedProgrammingSpring 20131. Inheritance Concepts2. PolymorphismMay 25, 2013 COMSATS Intitute of Information Technology125Please turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  126. 126. Class diagram showinginheritanceMay 25, 2013 COMSATS Intitute of Information Technology 126Inheritance among classes isshown as open triangulararrowhead in UML ClassDiagram.Arrow be read as “derivedfrom”.
  127. 127. Association• Objects in an object model interact with each other• Usually an object provides services to several other objects• An object keeps associations with other objects to delegate tasksMay 25, 2013 COMSATS Intitute of Information Technology 127
  128. 128. Kinds of Association• Class Association• Inheritance• Object Association• Simple Association• Composition• AggregationMay 25, 2013 COMSATS Intitute of Information Technology 128
  129. 129. Simple Association• Is the weakest link between objects• Is a reference by which one object can interact with some otherobject• Is simply called as “association”May 25, 2013 COMSATS Intitute of Information Technology 129
  130. 130. Kinds of Simple Association• w.r.t navigation• One-way Association• Two-way Association• w.r.t number of objects• Binary Association• Ternary Association• N-ary AssociationMay 25, 2013 COMSATS Intitute of Information Technology 130
  131. 131. One-way Association• We can navigate along a single direction only• Denoted by an arrow towards the server objectMay 25, 2013 COMSATS Intitute of Information Technology 131
  132. 132. Example – Association• Ali lives in a HouseMay 25, 2013 COMSATS Intitute of Information Technology 132Ali Houselives-in11
  133. 133. Example – Association• Ali drives his CarMay 25, 2013 COMSATS Intitute of Information Technology 133Ali Cardrives*1
  134. 134. Two-way Association• We can navigate in both directions• Denoted by a line between the associated objectsMay 25, 2013 COMSATS Intitute of Information Technology 134
  135. 135. Example – Two-way Association• Employee works for company• Company employs employeesMay 25, 2013 COMSATS Intitute of Information Technology 135Employee Companyworks-for1*
  136. 136. Example – Two-way Association• Yasir is a friend of Ali• Ali is a friend of YasirMay 25, 2013 COMSATS Intitute of Information Technology 136Yasir Alifriend11
  137. 137. Binary Association• Associates objects of exactly two classes• Denoted by a line, or an arrow between the associated objectsMay 25, 2013 COMSATS Intitute of Information Technology 137
  138. 138. Example – Binary Association• Association “works-for” associates objects of exactlytwo classesMay 25, 2013 COMSATS Intitute of Information Technology 138Employee Companyworks-for1*
  139. 139. Example – Binary Association• Association “drives” associates objects of exactly twoclassesMay 25, 2013 COMSATS Intitute of Information Technology 139Ali Cardrives*1
  140. 140. Ternary Association• Associates objects of exactly three classes• Denoted by a diamond with lines connected to associated objectsMay 25, 2013 COMSATS Intitute of Information Technology 140
  141. 141. Example – Ternary Association• Objects of exactly three classes are associatedMay 25, 2013 COMSATS Intitute of Information Technology 141Student TeacherCourse1**
  142. 142. Example – Ternary Association• Objects of exactly three classes are associatedMay 25, 2013 COMSATS Intitute of Information Technology 142Project LanguagePerson*1*
  143. 143. N-ary Association• An association between 3 or more classes• Practical examples are very rareMay 25, 2013 COMSATS Intitute of Information Technology 143
  144. 144. Class diagram showingassociation• Association among classes is shown as a simple arrow (ray) in UML (UnifiedModeling Language) Class Diagram.• The direction of arrow shows ‘navigability’.• time12 calls time24.• This is unidirectional association.• If both classes call operation of the other, navigability is both sided (bidirectionalassociation).May 25, 2013 COMSATS Intitute of Information Technology 144
  145. 145. Composition• An object may be composed of other smaller objects• The relationship between the “part” objects and the “whole” objectis known as Composition• Composition is represented by a line with a filled-diamond headtowards the composer objectMay 25, 2013 COMSATS Intitute of Information Technology 145
  146. 146. Class diagram showingcompositionMay 25, 2013 COMSATS Intitute of Information Technology 146Composition among classes is shown as solid diamond arrowhead in UML ClassDiagram.
  147. 147. Example – Composition of AliMay 25, 2013 COMSATS Intitute of Information Technology 147AliBodyArmHeadLeg112 2
  148. 148. Example – Composition of ChairMay 25, 2013 COMSATS Intitute of Information Technology 148ChairSeatArmBackLeg112 4
  149. 149. Composition is Stronger• Composition is a stronger relationship, because• Composed object becomes a part of the composer• Composed object can’t exist independentlyMay 25, 2013 COMSATS Intitute of Information Technology 149
  150. 150. Example – Composition is Stronger• Ali is made up of different body parts• They can’t exist independent of AliMay 25, 2013 COMSATS Intitute of Information Technology 150
  151. 151. Example – Composition is Stronger• Chair’s body is made up of different parts• They can’t exist independentlyMay 25, 2013 COMSATS Intitute of Information Technology 151
  152. 152. Composition• Composition is a ‘consists of’ relationship.• COURSE_DATA consists of STUDENT_DATA (besides other things).• STUDENT_DATA lifetime is the same as COURSE_DATA.• Part may belong to only one whole.• The lifetime of the part is the same as the lifetime of the whole.May 25, 2013 National University of Computer and Emerging Sciences 152
  153. 153. Aggregation• An object may contain a collection (aggregate) of other objects• The relationship between the container and the contained object iscalled aggregation• Aggregation is represented by a line with unfilled-diamond headtowards the containerMay 25, 2013 COMSATS Intitute of Information Technology 154
  154. 154. Class diagram showingaggregationMay 25, 2013 COMSATS Intitute of Information Technology 155Aggregation among classes is shown as open diamond arrowhead in UML ClassDiagram.
  155. 155. Example – AggregationMay 25, 2013 COMSATS Intitute of Information Technology 156RoomCupboardBedChair Table*111
  156. 156. Example – AggregationMay 25, 2013 COMSATS Intitute of Information Technology 157Garden Plant*
  157. 157. Aggregation is Weaker• Aggregation is weaker relationship, because• Aggregate object is not a part of the container• Aggregate object can exist independentlyMay 25, 2013 COMSATS Intitute of Information Technology 158
  158. 158. Example – Aggregation is Weaker• Furniture is not an intrinsic part of room• Furniture can be shifted to another room, and so can existindependent of a particular roomMay 25, 2013 COMSATS Intitute of Information Technology 159
  159. 159. Example – Aggregation is Weaker• A plant is not an intrinsic part of a garden• It can be planted in some other garden, and so can exist independentof a particular gardenMay 25, 2013 COMSATS Intitute of Information Technology 160
  160. 160. More about „struct‟• More on data hiding• By default all the data members of struct areaccessible (through the struct variable/object)• This behaviour is known as data being ‘public’.• We can hide them by explicitly marking them as‘private’.• public: data or functions, can be accessed fromanywhere, outside or inside.• private: data or functions, cannot be accessed fromoutside.May 25, 2013 National University of Computer and Emerging Sciences 161
  161. 161. More about „struct‟ …struct TEST{int x;}TEST var;var.x = 10;May 25, 2013 National University of Computer and Emerging Sciences 162struct TEST{public:int x;}TEST var;var.x = 10;struct TEST{private:int x;}TEST var;var.x = 10;//error
  162. 162. More about „struct‟ …struct stack {int data[100];int top;} S;///////////////////////////////////void push(stack S, int a){assert(top<100);S.data[top]=a; S.top++;}May 25, 2013 COMSATS Intitute of Information Technology 163
  163. 163. More about „struct‟ …struct TEST{private:int x;public:void Setx(int val) { x = val; };int Getx() { return x; };}TEST var;var.Setx(10);int y = var.Getx();May 25, 2013 National University of Computer and Emerging Sciences 164struct TEST{private:int x;}TEST var;var.x = 10; //eint y = var.x; //eSo even legitimate access of data goes through an interface!We have secured the data further!!!
  164. 164. Member functions definitionMay 25, 2013 National University of Computer and Emerging Sciences 165struct TEST {private:int x;public:void Setx(int val);int Getx();}void TEST::Setx(int val) {x = val;}int TEST::Getx() {return x;}main() {TEST var;var.Setx(10);int y = var.Getx();}• We can declare memberfunctions inside thestruct and define themoutside as well using thename of struct to resolveambiguity.• V. IMP: Note that thisallows us to separateheader andimplementation files!
  165. 165. Class Compatibility• A class is behaviorally compatible with another if it supports all theoperations of the other class• Such a class is called subtype• A class can be replaced by its subtypeMay 25, 2013 COMSATS Intitute of Information Technology 166
  166. 166. …Class Compatibility• Derived class is usually a subtype of the base class• It can handle all the legal messages (operations) of the base class• Therefore, base class can always be replaced by the derived classMay 25, 2013 COMSATS Intitute of Information Technology 167
  167. 167. Example – Class CompatibilityMay 25, 2013 COMSATS Intitute of Information Technology 168ShapecolorverticesmovesetColordrawCircleradiusdrawcomputeAreaLinelengthdrawgetLengthTriangleangledrawcomputeArea
  168. 168. Example – Class CompatibilityMay 25, 2013 COMSATS Intitute of Information Technology 169Filesize…openprint…ASCII File…print…PDF File…print…PS File…print…
  169. 169. Polymorphism• In general, polymorphism refers to existence of different forms of asingle entity• For example, both Diamond and Coal are different forms of CarbonMay 25, 2013 COMSATS Intitute of Information Technology 170
  170. 170. Polymorphism in OO Model• In OO model, polymorphism means that different objects can behavein different ways for the same message (stimulus)• Consequently, sender of a message does not need to know exact classof the receiverMay 25, 2013 COMSATS Intitute of Information Technology 171
  171. 171. Example – PolymorphismMay 25, 2013 COMSATS Intitute of Information Technology 172ShapeLine Circle Triangledrawdrawdraw drawdrawView
  172. 172. Example – PolymorphismMay 25, 2013 COMSATS Intitute of Information Technology 173FileASCII File PDF File PS Fileprintprintprint printprintEditor
  173. 173. Polymorphism – Advantages• Messages can be interpreted in different waysdepending upon the receiver classMay 25, 2013 COMSATS Intitute of Information Technology 174ShapeLine Circle Triangledrawdrawdraw drawdrawView
  174. 174. Polymorphism – Advantages• New classes can be added without changing the existingmodelMay 25, 2013 COMSATS Intitute of Information Technology 175SquaredrawShapeLine Circle Triangledrawdrawdraw drawdrawView
  175. 175. Polymorphism – Advantages• In general, polymorphism is a powerful tool to develop flexible andreusable systemsMay 25, 2013 COMSATS Intitute of Information Technology 176
  176. 176. Object-OrientedModelingAn ExampleMay 25, 2013 COMSATS Intitute of Information Technology 177
  177. 177. Problem Statement• Develop a graphic editor that can draw different geometric shapessuch as line, circle and triangle. User can select, move or rotate ashape. To do so, editor provides user with a menu listing differentcommands. Individual shapes can be grouped together and canbehave as a single shape.May 25, 2013 COMSATS Intitute of Information Technology 178
  178. 178. Identify ClassesExtract nouns in the problem statement• Develop a graphic editor that can draw different geometric shapessuch as line, circle and triangle. User can select, move or rotate ashape. To do so, editor provides user with a menu listing differentcommands. Individual shapes can be grouped together and canbehave as a single shape.May 25, 2013 COMSATS Intitute of Information Technology 179
  179. 179. …Identify ClassesEliminate irrelevant classes• Editor – Very broad scope• User – Out of system boundaryMay 25, 2013 COMSATS Intitute of Information Technology 180
  180. 180. …Identify ClassesAdd classes by analyzing requirements• Group – required to behave as a shape• “Individual shapes can be grouped together and can behave as a singleshape”• View – editor must have a display areaMay 25, 2013 COMSATS Intitute of Information Technology 181
  181. 181. …Identify Classes• Shape• Line• Circle• Triangle• MenuMay 25, 2013 COMSATS Intitute of Information Technology 182• Group• ViewFollowing classes have been identified:
  182. 182. Object Model – Graphic EditorMay 25, 2013 COMSATS Intitute of Information Technology 183LineCircleTriangleGroupShapeViewMenu
  183. 183. Identify AssociationsExtract verbs connecting objects•“Individual shapes can be grouped together”• Group consists of lines, circles, triangles• Group can also consists of other groups(Composition)May 25, 2013 COMSATS Intitute of Information Technology 184
  184. 184. … Identify AssociationsVerify access paths• View contains shapes• View contains lines• View contains circles• View contains triangles• View contains groups(Aggregation)May 25, 2013 COMSATS Intitute of Information Technology 185
  185. 185. … Identify AssociationsVerify access paths• Menu sends message to View(Simple One-Way Association)May 25, 2013 COMSATS Intitute of Information Technology 186
  186. 186. Object Model – Graphic EditorMay 25, 2013 COMSATS Intitute of Information Technology 187TriangleCircleLineShapeViewnnnnnnnnMenuGroupnnnnnnnnnn
  187. 187. Identify AttributesExtract properties of the object• From the problem statement• Properties are not mentionedMay 25, 2013 COMSATS Intitute of Information Technology 188
  188. 188. …Identify AttributesExtract properties of the object• From the domain knowledgeMay 25, 2013 COMSATS Intitute of Information Technology 189• Line– Color– Vertices– Length• Circle– Color– Vertices– Radius• Triangle– Color– Vertices– Angle• Shape– Color– Vertices
  189. 189. …Identify AttributesExtract properties of the object• From the domain knowledgeMay 25, 2013 COMSATS Intitute of Information Technology 190• Group– noOfObjects• View– noOfObjects– selected• Menu– Name– isOpen
  190. 190. Object Model – Graphic EditorMay 25, 2013 COMSATS Intitute of Information Technology 191MenunameisOpenViewnoOfObjectsselectedShapecolorverticesLinelengthCircleradiusGroupnoOfObjectsTriangleanglennnnnnnnnnnnnnnnn
  191. 191. Identify OperationsExtract verbs connected with an objectMay 25, 2013 COMSATS Intitute of Information Technology 192• Develop a graphic editor that can drawdifferent geometric shapes such as line,circle and triangle. User can select, moveor rotate a shape. To do so, editor providesuser with a menu listing differentcommands. Individual shapes can begrouped together and can behave as asingle shape.
  192. 192. … Identify OperationsEliminate irrelevant operations• Develop – out of system boundary• Behave – have broad semanticsMay 25, 2013 COMSATS Intitute of Information Technology 193
  193. 193. …Identify OperationsFollowing are selected operations:May 25, 2013 COMSATS Intitute of Information Technology 194• Line– Draw– Select– Move– Rotate• Circle– Draw– Select– Move– Rotate
  194. 194. …Identify OperationsFollowing are selected operations:May 25, 2013 COMSATS Intitute of Information Technology 195• Triangle– Draw– Select– Move– Rotate• Shape– Draw– Select– Move– Rotate
  195. 195. …Identify OperationsFollowing are selected operations:May 25, 2013 COMSATS Intitute of Information Technology 196• Group– Draw– Select– Move– Rotate• Menu– Open– Select– Move– Rotate
  196. 196. …Identify OperationsExtract operations using domain knowledgeMay 25, 2013 COMSATS Intitute of Information Technology 197• View– Add– Remove– Group– Show– Select– Move– Rotate
  197. 197. GroupnoOfObjectsdraw()Triangleangledraw()nnCircleradiusdraw()nnLinelengthdraw()nnShapecolorverticesdraw()select()move()rotate()nnViewnoOfObjectsselectedadd()remove()group()show()select()move()rotate()nnnnnnnnMenunameisOpenopen()select()move()rotate()nMay 25, 2013 COMSATS Intitute of Information Technology 198
  198. 198. Identify InheritanceSearch “is a kind of” by looking at keywords like “such as”, “forexample”, etc• “…shapes such as line, circle and triangle…”– Line, Circle and Triangle inherits from ShapeMay 25, 2013 COMSATS Intitute of Information Technology 199
  199. 199. …Identify InheritanceBy analyzing requirements• “Individual shapes can be grouped together and can behave as asingle shape”• Group inherits from ShapeMay 25, 2013 COMSATS Intitute of Information Technology 200
  200. 200. Refining the Object Model• Application of inheritance demands an iteration over the wholeobject model• In the inheritance hierarchy,• All attributes are shared• All associations are shared• Some operations are shared• Others are overriddenMay 25, 2013 COMSATS Intitute of Information Technology 201
  201. 201. …Refining the Object ModelShare associations• View contains all kind of shapes• Group consists of all kind of shapesMay 25, 2013 COMSATS Intitute of Information Technology 202
  202. 202. …Refining the Object ModelShare attributes• Shape – Line, Circle, Triangle and Group• Color, verticesMay 25, 2013 COMSATS Intitute of Information Technology 203
  203. 203. …Refining the Object ModelShare operations• Shape – Line, Circle, Triangle and Group• Select• Move• RotateMay 25, 2013 COMSATS Intitute of Information Technology 204
  204. 204. …Refining the Object ModelShare the interface and override implementation• Shape – Line, Circle, Triangle and Group• DrawMay 25, 2013 COMSATS Intitute of Information Technology 205
  205. 205. Linelengthdraw()Circleradiusdraw()Triangleangledraw()GroupnoOfObjectsdraw()Shapecolorverticesdraw()select()move()rotate()nViewnoOfObjectsselectedadd()remove()group()show()select()move()rotate()nnMenunameisOpenopen()select()move()rotate()nMay 25, 2013 COMSATS Intitute of Information Technology 206
  206. 206. GroupnoOfObjectsdraw()Triangleangledraw()nnCircleradiusdraw()nnLinelengthdraw()nnShapecolorverticesdraw()select()move()rotate()nnViewnoOfObjectsselectedadd()remove()group()show()select()move()rotate()nnnnnnnnMenunameisOpenopen()select()move()rotate()nMay 25, 2013 COMSATS Intitute of Information Technology 207
  207. 207. Class• Class is a tool to realize objects• Class is a tool for defining a new typeMay 25, 2013 COMSATS Intitute of Information Technology 208
  208. 208. Example• Lion is an object• Student is an object• Both has some attributes and some behaviorsMay 25, 2013 COMSATS Intitute of Information Technology 209
  209. 209. Uses• The problem becomes easy to understand• Interactions can be easily modeledMay 25, 2013 COMSATS Intitute of Information Technology 210
  210. 210. Type in C++• Mechanism for user defined types are• Structures• Classes• Built-in types are like int, float and double• User defined type can be• Student in student management system• Circle in a drawing softwareMay 25, 2013 COMSATS Intitute of Information Technology 211
  211. 211. Abstraction• Only include details in the system that are required for making afunctional system• Student• Name• Address• Sibling• Father BusinessMay 25, 2013 COMSATS Intitute of Information Technology 212Relevant to our problemNot relevant to our problem
  212. 212. Defining a New User Defined Typeclass ClassName{…DataType MemberVariable;ReturnType MemberFunction();…};May 25, 2013 COMSATS Intitute of Information Technology 213SyntaxSyntax
  213. 213. Exampleclass Student{int rollNo;char *name;float CGPA;char *address;…void setName(char *newName);void setRollNo(int newRollNo);…};May 25, 2013 COMSATS Intitute of Information Technology 214Member variablesMemberFunctions
  214. 214. Why Member Function• They model the behaviors of an object• Objects can make their data invisible• Object remains in consistent stateMay 25, 2013 COMSATS Intitute of Information Technology 215
  215. 215. ExampleStudent aStudent;aStudent.rollNo = 514;aStudent.rollNo = -514; //ErrorMay 25, 2013 COMSATS Intitute of Information Technology 216
  216. 216. Object and Class• Object is an instantiation of a user defined type or a classMay 25, 2013 COMSATS Intitute of Information Technology 217
  217. 217. Declaring class variables• Variables of classes (objects) are declared just like variables ofstructures and built-in data typesTypeName VaraibaleName;int var;Student aStudent;May 25, 2013 COMSATS Intitute of Information Technology 218
  218. 218. Accessing members• Members of an object can be accessed using• dot operator (.) to access via the variable name• arrow operator (->) to access via a pointer to an object• Member variables and member functions are accessed in a similarfashionMay 25, 2013 COMSATS Intitute of Information Technology 219
  219. 219. Exampleclass Student{int rollNo;void setRollNo(intaNo);};Student aStudent;aStudent.rollNo;May 25, 2013 COMSATS Intitute of Information Technology 220Error
  220. 220. struct -> class transition!class TEST {private:int x;public:void Setx(int val) { x = val; };int Getx() { return x; };}main() {TEST var;var.Setx(10);int y = var.Getx();}May 25, 2013 National University of Computer and Emerging Sciences 221struct TEST {private:int x;public:void Setx(int val) { x = val; };int Getx() { return x; };}main() {TEST var;var.Setx(10);int y = var.Getx();}• Replacing struct with class, does not have any affect!• This is the keyword that OOL (C++) provide for OOP!
  221. 221. Diff. between struct & classclass TEST {int x;void Setx(int val) { x = val; };int Getx() { return x; };}main() {TEST var;var.x = 10; //errorvar.Setx(10); //errorint y = var.Getx(); //error}May 25, 2013 National University of Computer and Emerging Sciences 222struct TEST {int x;void Setx(int val) { x = val; };int Getx() { return x; };}main() {TEST var;var.x = 10; //possiblevar.Setx(10);int y = var.Getx();}• By default struct (C++) members are public,whereas class members are private.
  222. 222. Diff. between struct & classclass TEST {int x;public:void Setx(int val) { x = val; };int Getx() { return x; };}main() {TEST var;var.x = 10; //errorvar.Setx(10);int y = var.Getx();}May 25, 2013 National University of Computer and Emerging Sciences 223struct TEST {private:int x;public:void Setx(int val) { x = val; };int Getx() { return x; };}main() {TEST var;var.x = 10; //errorvar.Setx(10);int y = var.Getx();}• By default struct (C++) members are public,whereas class members are private.
  223. 223. Access specifiersMay 25, 2013 COMSATS Intitute of Information Technology 224
  224. 224. Access specifiers• There are three access specifiers• ‘public’ is used to tell that member can be accessed whenever you haveaccess to the object• ‘private’ is used to tell that member can only be accessed from a memberfunction• ‘protected’ to be discussed when we cover inheritanceMay 25, 2013 COMSATS Intitute of Information Technology 225
  225. 225. Exampleclass Student{private:char * name;int rollNo;public:void setName(char *);void setRollNo(int);...};May 25, 2013 COMSATS Intitute of Information Technology 226Cannot be accessed outside classCan beaccessedoutside class
  226. 226. Exampleclass Student{...int rollNo;public:void setRollNo(int aNo);};int main(){Student aStudent;aStudent.SetRollNo(1);}May 25, 2013 COMSATS Intitute of Information Technology 227
  227. 227. Default access specifiers• When no access specifier is mentioned then by default the member isconsidered private memberMay 25, 2013 COMSATS Intitute of Information Technology 228
  228. 228. Exampleclass Student{char * name;int RollNo;};class Student{private:char * name;int RollNo;};May 25, 2013 COMSATS Intitute of Information Technology 229
  229. 229. Exampleclass Student{char * name;int RollNo;void SetName(char *);};Student aStudent;aStudent.SetName(Ali);May 25, 2013 COMSATS Intitute of Information Technology 230Error
  230. 230. Exampleclass Student{char * name;int RollNo;public:void setName(char *);};Student aStudent;aStudent.SetName(“Ali”);May 25, 2013 COMSATS Intitute of Information Technology 231
  231. 231. Unified Modeling Language (UML) class diagramMay 25, 2013 National University of Computer and Emerging Sciences 232 of 2110..*abstractstaticprivateassociation(“using”)inheritance(“is a”)
  232. 232. Assignment (CP)• Install IBM Rational Rose or any other UML tool and draw thediagrams used in this lecture and take a print out of those diagrams toshow me what you have done.• Deadline: next classMay 25, 2013 COMSATS Intitute of Information Technology 233
  233. 233. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May 25, 2013 COMSATS Intitute of Information Technology 234
  234. 234. ThanksMay 25, 2013 COMSATS Intitute of Information Technology 235
  235. 235. CSC241:Object OrientedProgrammingSpring 20131. Inheritance Concepts2. PolymorphismMay 25, 2013 COMSATS Intitute of Information Technology236Please turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  236. 236. Review• Class• Concept• Definition• Data members• Member Functions• Access specifier
  237. 237. Member Functions• Member functions are the functions that operate on the dataencapsulated in the class• Public member functions are the interface to the class
  238. 238. Member Functions (contd.)• Define member function inside the class definitionOR• Define member function outside the class definition• But they must be declared inside class definition
  239. 239. Function Inside Class Bodyclass ClassName {…public:ReturnType FunctionName() {…}};
  240. 240. Example•Define a class of student that hasa roll number. This class shouldhave a function that can be usedto set the roll number
  241. 241. Exampleclass Student{int rollNo;public:void setRollNo(int aRollNo){rollNo = aRollNo;}};
  242. 242. Function Outside Class Bodyclass ClassName{…public:ReturnType FunctionName();};ReturnType ClassName::FunctionName(){…}Scoperesolutionoperator
  243. 243. Exampleclass Student{…int rollNo;public:void setRollNo(int aRollNo);};void Student::setRollNo(int aRollNo){…rollNo = aRollNo;}
  244. 244. Inline Functions• Instead of calling an inline function compiler replaces the code at thefunction call point• Keyword ‘inline’ is used to request compiler to make a function inline• It is a request and not a command
  245. 245. Exampleinline int Area(int len, int hi){return len * hi;}int main(){cout << Area(10,20);}
  246. 246. Inline Functions• If we define the function inside the class body then the function is bydefault an inline function• In case function is defined outside the class body then we must usethe keyword ‘inline’ to make a function inline
  247. 247. Exampleclass Student{int rollNo;public:void setRollNo(int aRollNo){…rollNo = aRollNo;}};
  248. 248. Exampleclass Student{…public:inline void setRollNo(int aRollNo);};void Student::setRollNo(int aRollNo){…rollNo = aRollNo;}
  249. 249. Exampleclass Student{…public:void setRollNo(int aRollNo);};inline void Student::setRollNo(intaRollNo){…rollNo = aRollNo;}
  250. 250. Exampleclass Student{…public:inline void setRollNo(int aRollNo);};inline void Student::setRollNo(intaRollNo){…rollNo = aRollNo;}
  251. 251. Constructor
  252. 252. Constructor• Constructor is used to initialize the objects of a class• Constructor is used to ensure that object is in well defined state atthe time of creation• Constructor is automatically called when the object is created• Constructor are not usually called explicitly
  253. 253. Constructor (contd.)• Constructor is a special function having same name as the class name• Constructor does not have return type• Constructors are commonly public members
  254. 254. Exampleclass Student{…public:Student(){rollNo = 0;…}};
  255. 255. Exampleint main(){Student aStudent;/*constructor is implicitly called at thispoint*/}
  256. 256. Default Constructor• Constructor without any argument is called default constructor• If we do not define a default constructor the compiler will generate adefault constructor• This compiler generated default constructor initialize the datamembers to their default values
  257. 257. Exampleclass Student{int rollNo;char *name;float GPA;public:… //no constructors};
  258. 258. ExampleCompiler generated default constructor{rollNo = 0;GPA = 0.0;name = NULL;}
  259. 259. Constructor Overloading• Constructors can have parameters• These parameters are used to initialize the data members with usersupplied data
  260. 260. Exampleclass Student{…public:Student();Student(char * aName);Student(char * aName, int aRollNo);Student(int aRollNo, int aRollNo, float aGPA);};
  261. 261. ExampleStudent::Student(int aRollNo,char * aName){if(aRollNo < 0){rollNo = 0;}else {rollNo = aRollNo;}…}
  262. 262. Exampleint main(){Student student1;Student student2(“Name”);Student student3(”Name”, 1);Student student4(”Name”,1,4.0);}
  263. 263. Constructor Overloading• Use default parameter value to reduce the writing effort
  264. 264. ExampleStudent::Student( char * aName = NULL,int aRollNo= 0,float aGPA = 0.0){…}Is equivalent toStudent();Student(char * aName);Student(char * aName, int aRollNo);Student(char * Name, int aRollNo, float aGPA);
  265. 265. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May 25, 2013 COMSATS Intitute of Information Technology 266
  266. 266. How to correctly Search for asoftware @ google• When we need a software, the first place where wego is at Google Search. If you dont know thesoftware name, then we use some keywords atGoogle Search (for e.g. Note Taking software, VideoEditing software, Photo Editing software etc). OnceGoogle show us the results, we click the links afterreading its title and some description. Following suchpractice often wastes our time by clicking uselesslinks. What most of the people dont know is that,you can easily search for the software / applicationsat Google Search using its filtering options. Lets seehow we can do that• Consult the file uploadedMay 25, 2013 COMSATS Intitute of Information Technology 267
  267. 267. ThanksMay 25, 2013 COMSATS Intitute of Information Technology 268
  268. 268. CSC241:Object OrientedProgrammingSpring 20131. FunctionsPlease turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  269. 269. Revision• Chapter 5 of bookMay 25, 2013 COMSATS Intitute of Information Technology 270
  270. 270. FunctionsMay 25, 2013 COMSATS Intitute of Information Technology 271 A function groups a number of program statements into a unitand gives it a name. This unit can then be invoked from other parts of the program. The most important reason to use functions is to aid in theconceptual organization of a program Another reason to use functions is to reduce program size. Anysequence of instructions that appears in a program more thanonce is a candidate for being made into a function. The function’s code is stored in only one place in memory, eventhough the function is executed many times in the course of theprogram.
  271. 271. Return typeInput argumentsMay 25, 2013 COMSATS Intitute of Information Technology 272
  272. 272. FunctionsMay 25, 2013 COMSATS Intitute of Information Technology 273//demonstrates a simple function#include <iostream>using namespace std;int cube(int x); // function derationint main(){ // tests the cube() function:int n = 1;while (n != 0){cin >> n;cout << "tcube(" << n << ") = “<< cube(n) << endl; // Calling a function} // end of while loopsystem("PAUSE"); return 0;}//end of mainint cube( int x ){ // function definitionreturn x*x*x; // returns cube of x:} // { function body }Input ArgumentsReturn type
  273. 273. FunctionsMay 25, 2013 COMSATS Intitute of Information Technology 274 Each integer read is passed to the cube() function by the call cube(n). The valuereturned by the function replaces the expression cube(n) and then is passed tothe output object cout The main() function passes the value 5 to the cube() function, and the cube()function returns the value 125 to the main() function. The argument n is passed by value to the formal parameter x. This simply meansthat x is assigned the value of n when the function is called.
  274. 274. Default ArgumentsMay 25, 2013 COMSATS Intitute of Information Technology 275#include <iostream>using namespace std;//declaration with default argumentsvoid repchar(char=*, int=45);int main(){repchar(); //prints 45 asterisksrepchar(=); //prints 45 equal signsrepchar(+, 30); //prints 30 plus signssystem("PAUSE"); return 0;}// displays line of charactersvoid repchar(char ch, int n){// defaults supplied if necessaryfor(int j=0; j<n; j++) // loops n timescout << ch; // prints chcout << endl;}
  275. 275. Inline FunctionMay 25, 2013 COMSATS Intitute of Information Technology 276 A function call involves substantial overhead.Extra time and space have to be used to invokethe function, pass parameters to it, allocatestorage for its local variables, store thecurrent variables and the location of executionin the main program, etc. In some cases, it is better to avoid all thisby specifying the function to be inline. Thistells the compiler to replace each call to thefunction with explicit code for the function. To the programmer, an inline function appearsthe same as an ordinary function, except forthe use of the inline specifier.
  276. 276. Inline FunctionMay 25, 2013 COMSATS Intitute of Information Technology 277// demonstrates inline functions#include <iostream>using namespace std;inline float lbstokg(float pounds){// converts pounds to kilogramsreturn 0.453592 * pounds;}int main(){float lbs;cout << "nEnter your weight in pounds: ";cin >> lbs;cout << "Your weight in kilograms is " << lbstokg(lbs)<< endl;return 0;}
  277. 277. RecursionMay 25, 2013 COMSATS Intitute of Information Technology 278 The existence of functions makes possible aprogramming technique called recursion. Recursion involves a function callingitself. This sounds rather improbable, andindeed a function calling itself is often abug. However, when used correctly thistechnique can be surprisingly powerful. Recursion is much easier to understand withan example than with lengthy explanations,so let‟s apply it to a program: The next program, uses recursion instead ofa loop to calculate factorial.
  278. 278. RecursionMay 25, 2013 COMSATS Intitute of Information Technology 279#include <iostream>using namespace std;// calls itself to calculate factorialsunsigned long fct(unsigned long n){static int I = 0; I++;cout << "You Called Me " << I << " times" << endl;if(n > 1)return n * fct(n-1); //self callelsereturn 1;}int main(){int n;cout << "Enter an integer: "; cin >> n;cout << "Factorial of " << n << " is " << fct(n) << "n";system("PAUSE"); return 0;}
  279. 279. RecursionMay 25, 2013 COMSATS Intitute of Information Technology 280
  280. 280. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.May 25, 2013 COMSATS Intitute of Information Technology 281
  281. 281. ThanksMay 25, 2013 COMSATS Intitute of Information Technology 282
  282. 282. CSC241:Object OrientedProgrammingSpring 20131. ConstructorsMay 25, 2013 COMSATS Intitute of Information Technology283Please turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  283. 283. Constructor
  284. 284. Constructor• Constructor is used to initialize the objects of a class• Constructor is used to ensure that object is in well defined state atthe time of creation (Lion 4 legs, Roll No +ve int)• Constructor is automatically called when the object is created• Constructor are not usually called explicitly
  285. 285. Constructor (contd.)• Constructor is a special function having same name as the class name• Constructor does not have return type• Constructors are commonly public members
  286. 286. Exampleclass Student{…public:Student(){rollNo = 0;…}};
  287. 287. Exampleint main(){Student aStudent;/*constructor is implicitly called at thispoint*/}
  288. 288. Default Constructor• Constructor without any argument is called default constructor• If we do not define a default constructor the compiler will generate adefault constructor• This compiler generated default constructor initialize the datamembers to their default values
  289. 289. Exampleclass Student{int rollNo;char *name;float GPA;public:… //no constructors};
  290. 290. ExampleCompiler generated default constructor{rollNo = 0;GPA = 0.0;name = NULL;}
  291. 291. Constructor Overloading• Constructors can have parameters• These parameters are used to initialize the data members with usersupplied data
  292. 292. Exampleclass Student{…public:Student();Student(char * aName);Student(char * aName, int aRollNo);Student(char * aName, int aRollNo, float aGPA);};
  293. 293. ExampleStudent::Student(int aRollNo,char * aName){if(aRollNo < 0){rollNo = 0;}else {rollNo = aRollNo;}…}
  294. 294. Exampleint main(){Student student1;Student student2(“Name”);Student student3(”Name”, 1);Student student4(”Name”,1,4.0);}
  295. 295. Constructor Overloading• Use default parameter value to reduce the writing effort
  296. 296. ExampleStudent::Student( char * aName = NULL,int aRollNo= 0,float aGPA = 0.0){…}Is equivalent toStudent();Student(char * aName);Student(char * aName, int aRollNo);Student(char * Name, int aRollNo, float aGPA);
  297. 297. Copy Constructor• Copy constructor are used when:• Initializing an object at the time of creation• When an object is passed by value to a function
  298. 298. Examplevoid func1(Student student){…}int main(){Student studentA;Student studentB = studentA;func1(studentA);}
  299. 299. Copy Constructor (Syntax)Student::Student(const Student &obj){rollNo = obj.rollNo;name = obj.name;GPA = obj.GPA;}
  300. 300. Shallow Copy• When we initialize one object with another then the compiler copiesstate of one object to the other• This kind of copying is called shallow copying
  301. 301. ExampleStudent studentA;Student studentB = studentA;NameGPARollNostudentANameGPARollNostudentBAHMAD…Memory
  302. 302. Assignment• Lab Assignment No 3May 25, 2013 COMSATS Intitute of Information Technology 303
  303. 303. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May 25, 2013 COMSATS Intitute of Information Technology 304
  304. 304. ThanksMay 25, 2013 COMSATS Intitute of Information Technology 305
  305. 305. CSC241:Object OrientedProgrammingSpring 20131. DestructorPlease turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  306. 306. Review•Copy constructors•Destructor•this Pointer•Separation of interface andimplementation
  307. 307. Destructor• You might guess that another function is calledautomatically when an object is destroyed. This is indeedthe case. Such a function is called a destructor.• A destructor also has the same name as the class namebut is preceded by a tilde (~) sign:• Like constructors, destructors do not have a return value.They also take no arguments.• The most common use of destructors is to de-allocatememory that was allocated for the object by theconstructor.May 25, 2013 COMSATS Intitute of Information Technology 308
  308. 308. Using DestructorMay 25, 2013 COMSATS Intitute of Information Technology 309// foo.cpp demonstrates destructor#include <iostream>using namespace std;class Foo{private:int data;public:Foo() : data(0) // constructor (same name as class){cout<< "Wakeup n" ; }~Foo() // destructor (same name with tilde){cout<< "ByeBye n" ; }};int main(){Foo s1, s2; // define two objects of class Foosystem( "PAUSE" ); // Foo *s3; s3 = new Foo; delete s3;return 0;}
  309. 309. this Pointer•There are situations wheredesigner wants to returnreference to current object from afunction•In such cases reference is takenfrom this pointer like (*this)
  310. 310. ExampleStudent Student::setRollNo(int aNo){…return *this;}Student Student::setName(char *aName){…return *this;}
  311. 311. Exampleint main(){Student aStudent;Student bStudent;bStudent = aStudent.setName(“Ahmad”);…bStudent = aStudent.setName(“Ali”).setRollNo(2);return 0;}
  312. 312. Separation of interface andimplementation•Public member function exposed by aclass is called interface•Separation of implementation from theinterface is good software engineering
  313. 313. Complex Number•There are two representations of complexnumber• Euler form• z = x + i y• Phasor form• z = |z| (cos  + i sin )• z is known as the complex modulus and  is known asthe complex argument or phase
  314. 314. Examplefloat getX()float getY()void setNumber(float i, float j)…float xfloat yComplexOld implementationfloat getX()float getY()void setNumber(float i, float j)…float zfloat thetaComplexNew implementation
  315. 315. Exampleclass Complex{ //oldfloat x;float y;public:void setNumber(float i, float j){x = i;y = j;}…};
  316. 316. Exampleclass Complex{ //newfloat z;float theta;public:void setNumber(float i, float j){theta = arctan(j/i);…}…};
  317. 317. Advantages•User is only concerned about ways of accessingdata (interface)•User has no concern about the internalrepresentation and implementation of the class
  318. 318. Separation of interface andimplementation•Usually functions are defined in implementationfiles (.cpp) while the class definition is given inheader file (.h)•Some authors also consider this as separation ofinterface and implementation
  319. 319. Student.hclass Student{int rollNo;public:void setRollNo(int aRollNo);int getRollNo();…};
  320. 320. Student.cpp#include “student.h”void Student::setRollNo(int aNo){…}int Student::getRollNo(){…}
  321. 321. Driver.cpp#include “student.h”int main(){Student aStudent;}
  322. 322. Classes, Objects and Memory• you might have the impression that each object createdfrom a class contains separate copies of that class’s dataand member functions.• It’s true that each object has its own separate data items• But all the objects in a given class use the same memberfunctions.• The member functions are created and placed in memoryonly once—when they are defined in the class definition.• Since the functions for each object are identical. The dataitems, however, will hold different values.May 25, 2013 COMSATS Intitute of Information Technology 323
  323. 323. May 25, 2013 COMSATS Intitute of Information Technology 324
  324. 324. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May 25, 2013 COMSATS Intitute of Information Technology 325
  325. 325. ThanksMay 25, 2013 COMSATS Intitute of Information Technology 326
  326. 326. CSC241:Object OrientedProgrammingSpring 20131. Static class member2. Const member functionPlease turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  327. 327. static class member• What is a static variable? What is its scope (local, file)and storage class (automatic, static).• What if a data member is static?• A member variable defined as static has characteristicssimilar to a normal static variable: It is visible onlywithin the class, but its lifetime is the entire program.• It continues to exist even if there are no objects of theclass.• Why would we need a static member data?May 25, 2013 COMSATS Intitute of Information Technology 328
  328. 328. static class member dataclass foo {private:static int count; //note: “declaration” only!public:foo() //incr count when object created{ count++;}int getcount() //returns count{ return count;}};int foo::count = 0; //*definition* of countMay 25, 2013 COMSATS Intitute of Information Technology 329int main(){foo f1, f2, f3; //create three objectscout << “count is “ << f1.getcount()<< endl; //each objectcout << “count is “ << f2.getcount()<< endl; //sees thecout << “count is “ << f3.getcount()<< endl; //same valuereturn 0;}
  329. 329. static class member• For multiple objects of the same class, new memory isallocated for data members and shared memory for allthe functions.• This shared memory is also used for static datamembers.• Static data member requires two separate statementsfor:• Declaration (compiler is told about type and name)• Definition (compiler sets aside memory)May 25, 2013 COMSATS Intitute of Information Technology 330
  330. 330. static class member• Why this two-part approach?• If static member data were defined inside the class (as itactually was in early versions of C++), it would violate theidea that a class definition is only a blueprint and does notset aside any memory.• Putting the definition of static member data outside theclass also serves to emphasize that the memory space forsuch data is allocated only once, before the program startsto execute,• and that one static member variable is accessed by anentire class; each object does not have its own version ofthe variable, as it would with ordinary member data.• In this way a static member variable is more like a globalvariable.May 25, 2013 COMSATS Intitute of Information Technology 331
  331. 331. static class member• Be careful:• It’s easy to handle static data incorrectly, and the compiler isnot helpful about such errors.• If you include the declaration of a static variable but forget itsdefinition, there will be no warning from the compiler.• Everything looks fine until you get to the linker, which will tellyou that you’re trying to reference an undeclared globalvariable.• This happens even if you include the definition but forget theclass name (the foo:: in the example above).May 25, 2013 COMSATS Intitute of Information Technology 332
  332. 332. Variable packing in memory• If you do a ‘sizeof(class_obj_or_name)’ for an object ofa class/struct or class/struct name, you get the size ofthe memory allocated for data members.• Memory alignment in class/struct is a bit different.May 25, 2013 COMSATS Intitute of Information Technology 333
  333. 333. Data member packing inclass/structclass Counter{private:unsigned char count;unsigned char temp2;short temp1;int temp;static int obj;public:Counter() : count(0){}}May 25, 2013 COMSATS Intitute of Information Technology 334int sz = sizeof(Counter);ORCounter c1;int sz = sizeof(c1);Gives sz = 8If there was no temp2, sz will still be 8.If there was no temp1, sz will still be 8.If rearranged, sz will change.Experiment at home and make concepts.
  334. 334. const Member Functions•There are functions that are meant to beread only•There must exist a mechanism to detecterror if such functions accidentally changethe data memberMay 25, 2013 COMSATS Intitute of Information Technology 335
  335. 335. Examplebool Student::isRollNo(int aNo){if(rollNo = = aNo){return true;}return false;}May 25, 2013 COMSATS Intitute of Information Technology 336
  336. 336. Examplebool Student::isRollNo(int aNo){/*undetected typing mistake*/if(rollNo = aNo){return true;}return false;}May 25, 2013 COMSATS Intitute of Information Technology 337
  337. 337. Examplebool Student::isRollNo(int aNo)const{/*compiler error*/if(rollNo = aNo){return true;}return false;}May 25, 2013 COMSATS Intitute of Information Technology 338
  338. 338. const Member Functions•Keyword const is placed at the end of theparameter listMay 25, 2013 COMSATS Intitute of Information Technology 339
  339. 339. const Member FunctionsDeclaration:class ClassName{ReturnVal Function() const;};Definition:ReturnVal ClassName::Function() const{…}May 25, 2013 COMSATS Intitute of Information Technology 340
  340. 340. Exampleclass Student{public:int getRollNo() const {return rollNo;}};May 25, 2013 COMSATS Intitute of Information Technology 341
  341. 341. const Functions•Constant member functions cannot modify thestate of any object•They are just “read-only”•Errors due to typing are also caught at compiletimeMay 25, 2013 COMSATS Intitute of Information Technology 342
  342. 342. const Functions•Constructors and Destructors cannot be const•Constructor and destructor are used to modifythe object to a well defined stateMay 25, 2013 COMSATS Intitute of Information Technology 343
  343. 343. Exampleclass Time{public:Time() const {} //error…~Time() const {} //error…};May 25, 2013 COMSATS Intitute of Information Technology 344
  344. 344. const Function•Constant member function cannot changedata member•Constant member function cannot accessnon-constant member functionsMay 25, 2013 COMSATS Intitute of Information Technology 345
  345. 345. Exampleclass Student{char * name;public:char *getName();void setName(char * aName);int ConstFunc() const{name = getName();//errorsetName(“Ahmad”);//error}};May 25, 2013 COMSATS Intitute of Information Technology 346
  346. 346. May 25, 2013 COMSATS Intitute of Information Technology 347
  347. 347. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May 25, 2013 COMSATS Intitute of Information Technology 348
  348. 348. ThanksMay 25, 2013 COMSATS Intitute of Information Technology 349
  349. 349. CSC241:Object OrientedProgrammingSpring 20131. Arrays & String (Chapter7)Please turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  350. 350. Arrays In everyday life we commonly group similarobjects into units. We buy eggs by the carton. In computer languages we also need to grouptogether data items of the same type. The mostbasic mechanism that accomplishes this in C++is the array. Arrays can hold a few data items or tens ofthousands. The data items grouped in an arraycan be simple types such as int or float, orthey can be user-defined types such asstructures and objects. An array groups items of the same type. Theitems in a in an array are accessed by anindex number. Using an index number to specifyan item allows easy access to a large numberof items.
  351. 351. Defining, Reading and Writing Array// gets four ages from user, displays them#include <iostream>using namespace std;int main(){int age[4], j; //array age of 4 intsfor(j=0; j<4; j++){ //get 4 agescout << "Enter an age: ";cin >> age[j]; //access array element}for(j=0; j<4; j++){ //display 4 agescout << "age[" << j << "] = " << age[j] << endl;cout <<"Address " << &age[j] << " = " << age[j] <<endl;}system("PAUSE"); return 0;}
  352. 352. Calculating Average#include <iostream>using namespace std;int main(){double avg, sum = 0 ;int i ; int marks[10] ; /* array declaration */for ( i = 0 ; i <= 9 ; i++ ){cout << "nEnter marks ";cin >> marks[i]; /* store data in array */}for ( i = 0 ; i <= 9 ; i++ )sum = sum + marks[i] ; /* read data fromarray*/avg = sum / 10 ;cout << "n Average marks = " << avg <<endl;system("PAUSE"); return 0;}
  353. 353. Using Direct Access on an Array// Using Direct Access on Array#include <iostream>using namespace std;int main(){int mem[]={50,60,70} ; // Initialize the arraycout << "mem[0] = " << mem[0] << endl;cout << "mem[1] = " << mem[1] << endl;cout << "mem[2] = " << mem[2] << endl;mem[0] = 80;mem[1] = 90;mem[2] = 100;cout << endl;cout << "mem[0] = " << mem[0] << endl;cout << "mem[1] = " << mem[1] << endl;cout << "mem[2] = " << mem[2] << endl;system("PAUSE"); return 0;}
  354. 354. Printing in Reverse Order#include <iostream>using namespace std;int main(){const int SIZE=5; // defines the size N for 5 elementsdouble a[SIZE]; // declares the array‟s elements astype doublecout << "Enter " << SIZE << " numbers:t";for (int i=0; i<SIZE; i++)cin >> a[i];cout << "In reverse order: ";for (int i=SIZE-1; i>=0; i--)cout << " " << a[i];system("PAUSE"); return 0;}
  355. 355. Out of Bounds#include <iostream>using namespace std;int main(){float a[] = { 22.2,44.4, 66.6 };float x=11.1;cout << "I m going to Crash " << endl;cin >> x;a[3333] = 88.8; // ERROR: index is out of bounds!return 0;}
  356. 356. Passing Array to Function#include <iostream>using namespace std;int sum(int[],int); // declarationint main(){int a[] = { 11,33, 55,77 };int size = sizeof(a)/sizeof(int);cout << "sum(a,size) = " << sum(a,size) << endl;cout << endl << a[0] << endl;system("PAUSE"); return 0;}int sum(int a[],int n){int sum=0;for (int i=0; i<n; i++)sum += a[i];a[0] = 100;return sum;}
  357. 357. n Dimensional Arrays#include <iostream>using namespace std;int main(){ const int row=2, col=3; int i,j;int ary[row][col] = {{11,12,13},{21,22,23}};for(i=0 ; i< row ; i++){for(j=0 ; j<col; j++){ cout << ary[i][j] << " ";}cout << endl;}for(i=0 ; i< row ; i++){for(j=0 ; j<col; j++){cout << &ary[i][j] << "="<<ary[i][j]<<"t";}cout << endl;}return 0;}
  358. 358. n Dimensional Arrays0x22ff40 = 110x22ff44 = 120x22ff48 = 130x22ff4C = 210x22ff50 = 220x22ff54 = 23ary[0][0]=ary[0][1]=ary[0][2]=ary[1][0]=ary[1][1]=ary[1][2]=232221131211
  359. 359. 2-Dimensional Arrays#include <iostream>using namespace std;int main(){ const int row=3, col=3; int i,j;int ary[row][col] = {{11,12,13},{21,22,23},{31,32,33} };for(i=0 ; i< row ; i++){for(j=0 ; j<col; j++){ cout << ary[i][j] << " ";}cout << endl;}for(i=0 ; i< row ; i++){for(j=0 ; j<col; j++){cout << &ary[i][j] << "="<<ary[i][j]<<"t";}cout << endl;}system("PAUSE"); return 0;}
  360. 360. 3-Dimensional Arrays0x22ff30 = 110x22ff34 = 120x22ff38 = 130x22ff3C = 210x22ff40 = 220x22ff44 = 23ary[0][0]=ary[0][1]=ary[0][2]=ary[1][0]=ary[1][1]=ary[1][2]=0x22ff48 = 310x22ff4C = 320x22ff50 = 33ary[2][0]=ary[2][1]=ary[2][2]=333231232221131211
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×