Академический Документы
Профессиональный Документы
Культура Документы
1 2
Chapter 3: Class
Lets Recall – chapter 2
Based on the given class diagram, write a program
by using OOP techniques to compute the area of a
box
Rectangle
- length Constructor and Destructor
- width
+ void setLength(double)
+ void setWidth(double)
+ double getLength()
+ double getWidth()
+ double getArea()
Chapter 3: Class Chapter 3: Class
Constructor Constructor
void main()
Constructor without any arguments/parameters
{ cout <<“This is displayed before the object is created.\n”;
Demo demoObj; Example Circle()
cout<<“This is displayed after the object is created.\n”; { radius = 0.0; }
}
Constructor Constructor
More than one constructor may be defined for a class. More than one constructor may be defined for a class.
Circle(double r, double p)
Example Circle(double r) Example { radius = r;
{ radius = r; }
pi = p; }
Chapter 3: Class Chapter 3: Class
Constructor Constructor
Example
Create objects depending on constructors class Student
{ private:
Student(char n[ ],int a, char m[ ])
char name[50];
class Circle { strcpy(name,n);
int age;
{ private: age = a;
char matric[10];
double radius; void main() strcpy(matric,m); }
public:
public: { Circle sphere1; };
Student()
Circle() //#1 Circle sphere2 (2.5); void main()
{ strcpy(name,”lela”);
{ radius = 0.0; } Circle sphere3; { Student DIT;
age = 19;
} Student BIT(“Aspa”,20,”AI950120”);
strcpy(matric,”AI970065”);
Circle(double r) //#2 }
}
{ radius = r;}
}; Which Which constructor?
constructor?
Destructor
Destructor
Concept Destructor must be a public member function.
Destructor must have same name with the class name.
A destructor is a member function that is automatically Destructor has no return type.
called when a class object is destroyed. Destructor cannot accept arguments, never has a parameter list.
A class can only have one destructor.
Use tilde character ( ~ ).
Purpose
To perform shutdown procedures when
the objects goes out of existence.
Format class_name ::~class_name ()
Chapter 3: Class