SDWU-Session 2
SDWU-Session 2
2
Objects and classes
• A class itself does not exist; it is merely a description of an object.
• A class can be considered a template for the creation of object
3
Methods
• A method is a function that is part of the class definition. The methods of a
class specify how its objects will respond to any particular message.
4
Defining a Base Class - Example
•A base class is not defined on, nor does it inherit members from, any
other class.
#include <iostream>
using std::cout; //this example “uses” only the necessary
using std::endl; // objects, not the entire std namespace
class Fraction {
public:
void assign (int, int); //member functions
double convert();
void invert();
void print();
private:
int num, den; //member data
};
Continued…
5
Using objects of a Class - Example
The main() function:
int main()
{
Fraction x;
x.assign (22, 7);
cout << "x = "; x.print();
cout << " = " << x.convert() << endl;
x.invert();
cout << "1/x = "; x.print(); cout << endl;
return 0;
}
Continued…
6
Defining a Class – Example
Class Implementation:
double Fraction::convert ()
{
return double (num)/(den);
}
void Fraction::invert()
{
int temp = num;
num = den;
den = temp;
}
void Fraction::print()
{
7
cout << num << '/' <