Lab 08
Lab 08
Objectives
To expose students to different type of methods that can be used to implement behaviors:
Four basic type of behaviors:
1. Constructors
2. Queries
3. Updates
4. Destructors
Class Objects: C++ features
1. const Attributes, static Attributes, and static const Attributes
2. const Methods and static Methods
#include <iostream>
using namespace std;
class Employee {
string name;
double salary;
public:
Employee (); // default constructor
Employee (string name, double salary = 0); // overloaded constructor
void print() const;
};
int main() {
Employee e1; // call default constructor
Employee e2 ("Kelly"); // call overloaded constructor,
// use default argument for salary
Employee e3 ("Michael", 2000); // call overloaded constructor
Employee e4 = e2; // call copy constructor
Employee e5 (e3); // call copy constructor
e1.print();
e2.print();
e3.print();
e4.print(); // same output as e2
e5.print(); // same output as e3
return 0;
}
Employee::Employee() {
name = "[No name]";
salary = 0;
}
Compile and run the following program. Study how the program works.
#include <iostream>
using namespace std;
class Student {
int* marks; // dynamic attribute
public:
Student();
void print();
void setMark (int location, int newmark);
};
Student::Student () { // default constructor
marks = new int[SIZE];
marks[0] = 97;
marks[1] = 98;
marks[2] = 99;
}
void Student::print() {
cout << "Marks = ";
for (int i = 0; i < SIZE; i++)
cout << marks[i] << " ";
cout << endl;
}
void Student::setMark (int location, int newmark) {
marks[location] = newmark;
}
int main() {
Student s1;
Student s2 = s1;
s1.print(); // Output 97 98 99
s2.print(); // Output 97 98 99, looks okay
s1.setMark (0, 1);// set marks[0] = 1
s1.print(); // Output 1 98 99
s2.print(); // Output 1 98 99. Why?
return 0;
}
The following program has errors. The main function and the attribute declaration have nothing
wrong. Correct the methods and attribute initialization.
#include <iostream>
using namespace std;
class Employee {
public:
Employee (string name) { // overloaded constructor
name = name;
numEmployees++;
}
void print() {
cout << "Name = " << name << endl
<< "Company = " << company << endl;
}
int getNumEmployees() {
return numEmployees;
}
private:
const string name; // const attribute
static int numEmployees; // static attribute
static const string company; // static const attribute
};
int main() {
cout << "Count: " << Employee::getNumEmployees() << endl;
{
const Employee e1 ("Michael");
cout << "Count: " << e1.getNumEmployees() << endl;
e1.print();
Employee e2 ("Kelly");
cout << "Count: " << e2.getNumEmployees() << endl;
e2.print();
}
cout << "Count: " << Employee::getNumEmployees() << endl;
return 0;
}
Output:
Count: 0
Count: 1
Name = Michael
Company = XYZ
Count: 2
Name = Kelly
Company = XYZ
Count: 0