1 c++ structures starting to think about objects
TRANSCRIPT
![Page 1: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/1.jpg)
11
C++ StructuresC++ Structures
Starting to think about objectsStarting to think about objects......
![Page 2: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/2.jpg)
StructureStructure
A Structure is a container, it can hold a A Structure is a container, it can hold a bunch of bunch of thingsthings..– These things can be of any type.These things can be of any type.
Structures are used to organize related data Structures are used to organize related data (variables) into a nice neat package.(variables) into a nice neat package.
22
![Page 3: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/3.jpg)
Example - Student RecordExample - Student Record
Student Record:Student Record:– Name Name a stringa string– HW GradesHW Grades an array of 3 doublesan array of 3 doubles– Test GradesTest Grades an array of 2 doublesan array of 2 doubles– Final AverageFinal Average a doublea double
33
![Page 4: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/4.jpg)
Structure MembersStructure Members
Each Each thingthing in a structure is called in a structure is called member.member.
Each Each membermember has a name, a type and a value.has a name, a type and a value.
Names follow the rules for variable names.Names follow the rules for variable names.
Types can be any defined typeTypes can be any defined type..
44
![Page 5: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/5.jpg)
55
Example Structure DefinitionExample Structure Definition
struct StudentRecord {struct StudentRecord {
char *name;char *name; // student name// student name
double hw[3];double hw[3]; // homework grades// homework grades
double test[2];double test[2]; // test grades// test grades
double ave;double ave; // final average// final average
};};
![Page 6: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/6.jpg)
Using a structUsing a struct
By defining a structure you create a new By defining a structure you create a new data type.data type.
Once a struct is defined, you can create Once a struct is defined, you can create variables of the new type.variables of the new type.
StudentRecord stu;StudentRecord stu;
66
![Page 7: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/7.jpg)
Accessing MembersAccessing Members You can treat the members of a struct You can treat the members of a struct
just like variables.just like variables. You need to use the You need to use the member access member access
operator operator '.' (pronounced "dot"): '.' (pronounced "dot"):
cout << stu.name << endl;cout << stu.name << endl;
stu.hw[2] = 82.3;stu.hw[2] = 82.3;
stu.ave = total/100; stu.ave = total/100;
77
![Page 8: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/8.jpg)
88
Structure AssignmentStructure Assignment
You can use structures just like variables:You can use structures just like variables:
StudentRecord s1,s2;StudentRecord s1,s2;
s1.name = "Joe Student";s1.name = "Joe Student";
……
s2 = s1;s2 = s1; Copies the entire structure
![Page 9: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/9.jpg)
99
Be CarefulBe CarefulIf a member is a pointer, If a member is a pointer, copyingcopying means means
copying the pointer (not what is pointed copying the pointer (not what is pointed to)to)..
name
ave
test
hw
"Joe Student"
![Page 10: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/10.jpg)
1010
Probably not what you wantProbably not what you want
StudentRecord s1,s2;StudentRecord s1,s2;
s1.name = "Joe Student";s1.name = "Joe Student";
……
s2 = s1;s2 = s1;
s2.name = "Jane Doe";s2.name = "Jane Doe";
// now s1.name and s2.name are both// now s1.name and s2.name are both
// "Jane Doe"// "Jane Doe"
![Page 11: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/11.jpg)
1111
Pointers to StructuresPointers to Structures
Pointers to structures are used often.Pointers to structures are used often. There is another There is another member access member access
operatoroperator used with pointers: used with pointers: ->->
StudentRecord *sptr;StudentRecord *sptr;
……
cout << "Name is" << cout << "Name is" << sptr->namesptr->name; ;
cout << "Ave is " << cout << "Ave is " << sptr->avesptr->ave;;
it looks like a "pointer
!"
![Page 12: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/12.jpg)
1212
Sample Function (won't work!)Sample Function (won't work!)
void update_average( StudentRecord stu) {void update_average( StudentRecord stu) {
double tot=0;double tot=0;
for (int i=0;i<3;i++)for (int i=0;i<3;i++)
tot += stu.hw[i];tot += stu.hw[i];
for (int i=0;i<3;i++)for (int i=0;i<3;i++)
tot += stu.test[i];tot += stu.test[i];
stu.ave = tot/5;stu.ave = tot/5;
}}
![Page 13: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/13.jpg)
1313
This one worksThis one works
void update_average( StudentRecord *stu)void update_average( StudentRecord *stu){ {
double tot=0double tot=0;;
for (int i=0;i<3;i++)for (int i=0;i<3;i++)
tot += stu->hw[i]tot += stu->hw[i];;
for (int i=0;i<3;i++)for (int i=0;i<3;i++)
tot += stu->test[i]tot += stu->test[i];;
stu->ave = tot/5stu->ave = tot/5;;
}}
![Page 14: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/14.jpg)
1414
Or use a reference parameterOr use a reference parameter
void update_average( StudentRecord &stu) {void update_average( StudentRecord &stu) {
double tot=0;double tot=0;
for (int i=0;i<3;i++)for (int i=0;i<3;i++)
tot += stu.hw[i];tot += stu.hw[i];
for (int i=0;i<3;i++)for (int i=0;i<3;i++)
tot += stu.test[i];tot += stu.test[i];
stu.ave = tot/5;stu.ave = tot/5;
}}
![Page 15: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/15.jpg)
1515
Other stuff you can do with a Other stuff you can do with a structstruct
You can also associate special functions You can also associate special functions with a structure (called with a structure (called member functionsmember functions).).
A C++ A C++ classclass is very similar to a structure, we is very similar to a structure, we will focus on classes.will focus on classes.– Classes can have (data) membersClasses can have (data) members– Classes can have member functions.Classes can have member functions.– Classes can also Classes can also hidehide some of the members some of the members
(functions and data).(functions and data).
![Page 16: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/16.jpg)
1616
Quick ExampleQuick Examplestruct StudentRecord {struct StudentRecord {
char *name; // student namechar *name; // student name
double hw[3]; // homework double hw[3]; // homework gradesgrades
double test[2]; // test gradesdouble test[2]; // test grades
double ave; // final averagedouble ave; // final average
void print_ave() {void print_ave() {
cout << "Name: " << name << endl;cout << "Name: " << name << endl;
cout << "Average: " << ave << endl;cout << "Average: " << ave << endl;
}}
};};
![Page 17: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/17.jpg)
1717
Using the member functionUsing the member function
doubleStudentRecord studoubleStudentRecord stu;;
// … // …set values in the structureset values in the structure
stu.print_avestu.print_ave ;)( ;)(
![Page 18: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/18.jpg)
C++ Classes C++ Classes &&
Object Oriented ProgrammingObject Oriented Programming
Exerted fromExerted from: : elearning.najah.edu/OldData/pdfs/elearning.najah.edu/OldData/pdfs/C++C++%20%20ClassesClasses%20Tutorials.%20Tutorials.pptppt
![Page 19: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/19.jpg)
Object Oriented ProgrammingObject Oriented Programming
Programmer Programmer thinksthinks about and defines the about and defines the attributes and behavior of objects.attributes and behavior of objects.
Often the objects are modeled after real-Often the objects are modeled after real-world entities.world entities.
Very different approach than Very different approach than function-basedfunction-based programming (like C).programming (like C).
![Page 20: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/20.jpg)
Object Oriented ProgrammingObject Oriented Programming
Object-oriented programming (OOP) Object-oriented programming (OOP) – Encapsulates data (attributes) and functions Encapsulates data (attributes) and functions
(behavior) into packages called classes.(behavior) into packages called classes. So, Classes are user-defined (programmer-So, Classes are user-defined (programmer-
defined) types.defined) types.– Data (data members) Data (data members) – Functions (member functions or methods)Functions (member functions or methods)
In other words, they are structures + In other words, they are structures + functionsfunctions
![Page 21: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/21.jpg)
Classes in C++Classes in C++
A class definition begins with the keyword A class definition begins with the keyword classclass..
The body of the class is contained within a The body of the class is contained within a set of braces, set of braces, { } ;{ } ; (notice the semi-colon). (notice the semi-colon).
class class_name}.….….…;{
Class body (data member + methodsmethods)
Any valid identifier
![Page 22: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/22.jpg)
Classes in CClasses in C++++
Within the body, the keywords Within the body, the keywords private:private: and and public:public: specify the access level of the specify the access level of the members of the class.members of the class.– the default is the default is privateprivate..
Usually, the data members of a class are Usually, the data members of a class are declared in the declared in the private:private: section of the class section of the class and the member functions are in and the member functions are in public:public: section.section.
![Page 23: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/23.jpg)
Classes in C++Classes in C++
class class_name}
private:………
public:………
;{
Public members or methods
private members or methods
![Page 24: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/24.jpg)
Classes in C++Classes in C++
Member access specifiersMember access specifiers
– publicpublic: : can be accessed outside the class directly.can be accessed outside the class directly.
– The public stuff is The public stuff is the interfacethe interface..
– privateprivate:: Accessible only to member functions of classAccessible only to member functions of class Private members and methods are for internalPrivate members and methods are for internal use use
only.only.
![Page 25: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/25.jpg)
Class ExampleClass Example
This class example shows how we can This class example shows how we can encapsulate (gather) a circle information into encapsulate (gather) a circle information into one package (unit or class) one package (unit or class)
class Circle{ private:
double radius; public:
void setRadius(double r);double getDiameter();
double getArea();double getCircumference();
};
No need for others classes to access and retrieve its value directly. The class methods are responsible for that only.
They are accessible from outsidethe class, and they can access themember (radius)
![Page 26: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/26.jpg)
Creating an object of a ClassCreating an object of a Class
Declaring a variable of a class type creates an Declaring a variable of a class type creates an objectobject. You can have many variables of the same . You can have many variables of the same type (class).type (class).– InstantiationInstantiation
Once an object of a certain class is instantiated, a Once an object of a certain class is instantiated, a new memory location is created for it to store its new memory location is created for it to store its data members and codedata members and code
You can instantiate many objects from a class You can instantiate many objects from a class type.type.– Ex) Circle c; Circle *c; Ex) Circle c; Circle *c;
![Page 27: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/27.jpg)
Special Member FunctionsSpecial Member Functions
ConstructorConstructor::– Public function memberPublic function member– called when a new object is created called when a new object is created
(instantiated).(instantiated).– Initialize data members.Initialize data members.– Same name as classSame name as class– No return typeNo return type– Several constructorsSeveral constructors
Function overloadingFunction overloading
![Page 28: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/28.jpg)
Special Member FunctionsSpecial Member Functions
class Circle{ private:
double radius; public:
Circle();Circle(int r); void setRadius(double r);double getDiameter();double getArea();double getCircumference();
};
Constructor with no argument
Constructor with one argument
![Page 29: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/29.jpg)
Implementing class methodsImplementing class methods
Class implementation: writing the code of class Class implementation: writing the code of class methods.methods.
There are two ways:There are two ways:1.1. Member functions defined outside classMember functions defined outside class
Using Binary scope resolution operator (Using Binary scope resolution operator (::::)) ““Ties” member name to class nameTies” member name to class name Uniquely identify functions of particular classUniquely identify functions of particular class Different classes can have member functions with same Different classes can have member functions with same
namename– Format for defining member functionsFormat for defining member functions
ReturnTypeReturnType ClassNameClassName::::MemberFunctionNameMemberFunctionName( ){( ){……
}}
![Page 30: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/30.jpg)
Implementing class methodsImplementing class methods
2.2. Member functions defined inside classMember functions defined inside class– Do not need scope resolution operator, class Do not need scope resolution operator, class
name;name;class Circle{ private:
double radius; public:
Circle() { radius = 0.0;}Circle(int r);void setRadius(double r){radius = r;}double getDiameter(){ return radius *2;}double getArea();double getCircumference();
};
Defined inside class
![Page 31: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/31.jpg)
class Circle{ private:
double radius; public:
Circle() { radius = 0.0;}Circle(int r);void setRadius(double r){radius = r;}double getDiameter(){ return radius *2;}double getArea();double getCircumference();
};Circle::Circle(int r){ radius = r;}double Circle::getArea(){ return radius * radius * (22.0/7);}double Circle:: getCircumference(){ return 2 * radius * (22.0/7);}
Defined outside class
![Page 32: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/32.jpg)
Accessing Class MembersAccessing Class Members
Operators to access class membersOperators to access class members– Identical to those for Identical to those for structstructss– Dot member selection operator (Dot member selection operator (..))
ObjectObject Reference to objectReference to object
– Arrow member selection operator (Arrow member selection operator (->->) ) PointersPointers
![Page 33: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/33.jpg)
class Circle{ private:
double radius; public:
Circle() { radius = 0.0;}Circle(int r);void setRadius(double r){radius = r;}double getDiameter(){ return radius *2;}double getArea();double getCircumference();
};Circle::Circle(int r){ radius = r;}double Circle::getArea(){ return radius * radius * (22.0/7);}double Circle:: getCircumference(){ return 2 * radius * (22.0/7);}
void main(){ Circle c1,c2(7);
cout<<“The area of c1:” <<c1.getArea()<<“\n”;
//c1.raduis = 5;//syntax error c1.setRadius(5);
cout<<“The circumference of c1:”<< c1.getCircumference()<<“\n”;
cout<<“The Diameter of c2:”<<c2.getDiameter()<<“\n”;
}
The first constructor is
called
The second constructor is
called
Since radius is a private class data
member
![Page 34: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/34.jpg)
class Circle{ private:
double radius; public:
Circle() { radius = 0.0;}Circle(int r);void setRadius(double r){radius = r;}double getDiameter(){ return radius *2;}double getArea();double getCircumference();
};Circle::Circle(int r){ radius = r;}double Circle::getArea(){ return radius * radius * (22.0/7);}double Circle:: getCircumference(){ return 2 * radius * (22.0/7);}
void main(){ Circle c(7); Circle *cp1 = &c; Circle *cp2 = new Circle(7); cout<<“The are of cp2:”
<<cp2->getArea(); }
![Page 35: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/35.jpg)
DestructorsDestructors
DestructorsDestructors– Special member functionSpecial member function– Same name as class Same name as class
Preceded with tilde (Preceded with tilde (~~))
– No arguments No arguments – No return valueNo return value– Cannot be overloadedCannot be overloaded– Before system reclaims object’s memoryBefore system reclaims object’s memory
Reuse memory for new objectsReuse memory for new objects Mainly used to de-allocate dynamic memory locationsMainly used to de-allocate dynamic memory locations
![Page 36: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/36.jpg)
Another class ExampleAnother class Example
This class shows how to handle time parts.This class shows how to handle time parts.class Time{ private:
int *hour,*minute,*second; public:
Time();Time(int h,int m,int s);void printTime();void setTime(int h,int m,int s);int getHour(){return *hour;}int getMinute(){return *minute;}int getSecond(){return *second;}void setHour(int h){*hour = h;}void setMinute(int m){*minute = m;}void setSecond(int s){*second = s;}~Time();
};
Destructor
![Page 37: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/37.jpg)
Time::Time(){
hour = new int;minute = new int;second = new int;*hour = *minute = *second = 0;
}
Time::Time(int h,int m,int s){
hour = new int;minute = new int;second = new int;*hour = h;*minute = m;*second = s;
}
void Time::setTime(int h,int m,int s){
*hour = h;*minute = m;*second = s;
}
Dynamic locations should be allocated
to pointers first
![Page 38: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/38.jpg)
void Time::printTime(){ cout<<"The time is : ("<<*hour<<":"<<*minute<<":"<<*second<<")"
<<endl;}
Time::~Time(){
delete hour; delete minute;delete second;}
void main(){
Time *t;t= new Time(3,55,54);t->printTime();
t->setHour(7);t->setMinute(17);t->setSecond(43);
t->printTime();
delete t;}
Output:The time is : (3:55:54)The time is : (7:17:43)Press any key to continue
Destructor: used here to de-allocate memory locations
When executed, the destructor is called
![Page 39: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/39.jpg)
Reasons for OOPReasons for OOP
1.1. Simplify programmingSimplify programming
2.2. InterfacesInterfaces Information hiding:Information hiding:
– Implementation details hidden within classes themselvesImplementation details hidden within classes themselves
3.3. Software reuseSoftware reuse Class objects included as members of other Class objects included as members of other
classesclasses
![Page 40: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/40.jpg)
for(i=0;i<3;i++)for(i=0;i<3;i++) { { for(j=0;j<3;j++)for(j=0;j<3;j++) { { for(m=0;m<3;m++)for(m=0;m<3;m++) {{ X[i][j][m]=A[i][m]*B[m][j];X[i][j][m]=A[i][m]*B[m][j]; C[i][j]+=X[i][j][m];C[i][j]+=X[i][j][m]; }} }} }}
![Page 41: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/41.jpg)
Class ActivityClass Activity
Write a program to computer an area of a Write a program to computer an area of a rectangle and triangle using the class rectangle and triangle using the class concept? concept?
![Page 42: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/42.jpg)
ProjectProject http://www.micro-examples.com/public/microex-navig/doc/077-picobat.htmlhttp://www.micro-examples.com/public/microex-navig/doc/077-picobat.html
![Page 43: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/43.jpg)
HowHow ? ? http://www.mikroe.com/eng/products/view/7/mikroc-pro-for-pic/
![Page 44: 1 C++ Structures Starting to think about objects](https://reader035.vdocument.in/reader035/viewer/2022062421/56649da75503460f94a935b6/html5/thumbnails/44.jpg)