Example to illustrate accessing member data and member functions for a class
#include <iostream.h>
//Declaration of Class
class Savings
{
public:
unsigned account_number;
float balance;
unsigned deposit(unsigned amount)
{
balance += amount;
return balance;
}
};
//main program which uses class Savings
main()
{
Savings a; // declare an object a of data type Savings
Savings b; // declare an object b of data type Savings
a.account_number = 1; // set account number for a to 1
a.balance = 0.0; // set balance for a to 0
a.deposit(10.0); // deposits 10 pounds to a
b.account_number = 2; // set account number for b to 2
}
Example
#include <iostream.h>
// class declaration
class Rational
{
public:
void assign (int, int);
double convert (); // convert fraction to double
void invert (); // invert fraction
void print (); // print as a fraction
private:
int num, den;
};
// main program
main()
{
Rational x;
x.assign(22,7);
cout << " x = " ;
x.print();
cout << " = " << x.convert() << "\n";
x.invert();
cout << "1/x = ";
x.print();
cout << "\n";
}
//Rational function definitions
void Rational::assign(int n, int d)
{
num = n;
den = d;
}
double Rational::convert()
{
return double(num)/den;
}
void Rational::invert()
{
int temp = num;
num = den;
den = temp;
}
void Rational::print()
{
cout << num << "/" << den;
}
Example - Constructor
Add Constructor to Student class example
#include >iostream.h<
class Student
{
public:
Student()
{
module_hours = 0;
average_marks = 0.0;
}
//marks - returns average marks
float marks()
{
return average_marks;
}
//hours_worked - returns number of study hours
float hours_worked()
{
return module_hours;
}
// other public functions
private:
int module_hours;
float average_marks;
};
int main()
{
Student s; // create the object and initialise it
// print out initialised values
cout << "hours " << s.hours_worked()
<< " average_marks " << s.marks() << "\n";
// rest of main
}
Constrcutor Example - Rational Class
class Rational
{
public:
Rational(int n, int d)
{
num = n;
den = d;
}
void print();
private:
int num,den;
};
main()
{
Rational x(22,7), y(-2,5);
cout << "x = ";
x.print();
cout << "y = ";
y.print();
}
Back to Main Page for Lecture 9 |