Why do we need classes, why can’t we just use structs?
structs don’t have methods
What are methods?
actions performed within a class… ie functions in the class.
How would you define a class?
a data type that encapsulates properties and methods relating to a specific type of object
or
class DateClass
{
public:
int m_year;
int m_month;
int m_day;
};
What is an object?
a virtual representation of a physical entity. An instantiation of a class.
Quiz time
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.
#include <iostream>
#include <string>
using namespace std;
class IntPair
{
public:
int m_one = 0;
int m_two = 0;
void set(int one, int two)
{
m_one = one;
m_two = two;
}
// Print employee information to the screen
void print()
{
std::cout << "Pair(" << m_one << ", " << m_two << ")" << endl;
}
};
int main()
{
IntPair p1;
p1.set(1, 1);
IntPair p2;
p2.m_one = 2;
p2.m_two = 2;
p1.print();
p2.print();
return 0;
}
1b) Why should we use a class for IntPair instead of a struct?
Best practices recommended by the article we read says that if the object requires a member function you should use a class.