Why do we need classes, why can’t we just use structs?
To begin with structs were originally designed to only hold data whereas classes hold data and member functions. Although structs in C++ can have member functions there is a risk to doing this as a class will deallocate memory when it was destroyed whereas this may not occur with a struct which can cause memory leaks.
What are methods?
Methods is another term for member functions (i.e. functions defined inside of a class).
How would you define a class?
A class is a user defined type or data structure that has data and member functions (methods). Access to the members of a class is governed by three access specifiers (private, protected or public). The private members are not accessible outside the class; they can be accessed only through methods of the class. The public members form an interface to the class and are accessible outside the class.
What is an object?
An object is an instance of a class data type.
1a) Create a class called IntPair that holds two integers. This class should have two member variables to hold the integers. You should also create two member functions: one named “set” that will let you assign values to the integers, and one named “print” that will print the values of the variables.
The following main function should execute:
1
2
3
4
5
6
7
8
9
10
11
12 int main()
{
IntPair p1;
p1.set(1, 1); // set p1 values to (1, 1)
IntPair p2{ 2, 2 }; // initialize p2 values to (2, 2)
p1.print();
p2.print();
return 0;
}
and produce the output:
Pair(1, 1)
Pair(2, 2)
class IntPair
{
public:
int m_integerOne;
int m_integerTwo;
void set(int a, int b)
{
m_integerOne = a;
m_integerTwo = b;
};
void print(){
std::cout << "Pair("<<m_integerOne << ","<<m_integerTwo<<")" << endl;
};
};
1b) Why should we use a class for IntPair instead of a struct?
Using a class enables us to also have member functions so that we can implicitly pass the object to the member functions. In the case of the function set we only need to explicitly pass the 2 integer values and in the case of print we don’t need to explicitly pass any values. This is a simpler and more efficient approach.