Classes in C++ - Reading Assignment


#81

Why do we need classes, why can’t we just use structs?

  • Classes provides more flexibility than structs. Classes can hold functions as well as data.

What are methods?

  • Methods are functions defined inside of a class.

How would you define a class?

class DateClass
{
public:
int m_year;
int m_month;
int m_day;

void print()
{
std::cout << m_year;
}
};
What is an object?

  • A variable of a class type is called an object.

#82
  1. Why do we need classes, why can’t we just use structs?

    Classes can be used to hold data and provide functions that work with the data, whereas structs only hold data.

  2. What are methods?

    Methods are functions defined inside of a class.

  3. How would you define a class?

    class NameClass
    {
    public:
    int data1;
    int data2;
    int data3;
    };

  4. What is an object?

    A variable of the class type is an object.

Quiz: Part 1:

#include
using namespace std;

class IntPair {
public:
int number1;
int number2;
void set(int num1, int num2)
{
number1 =num1;
number2 =num2;
}
void print()
{
std::cout<<“Pair(”<<number1<<", “<<number2<<”)"<<endl;
}

};

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;

}

Part 2:

Both data and functions are included. Structs are for data only.


#83

1. Why do we need classes, why can’t we just use structs?
We need classes because they allow us to solve more complex problems than regular structs. Classes let us define our own data types. With classes, it’s possible to have objects that besides data include functions (called member functions).

2. What are methods?
Methods is another term for “member functions.”

3. How would you define a class?
By using the class keyword…
class ExampleClass

4. What is an object?
An object is a variable of a class type.


#84
  1. A class is a way of creating custom data type that can contain one or more data type and other type such as function etc. It is much more flexible than the struct type. A class allows the creation of objects.
  2. They are member functions in a class
  3. With the key word class
  4. An instance of a class

#85

Why do we need classes, why can’t we just use structs?
We often want our types to not only hold data, but provide functions that work with the data as well, and this is typically done via the class keyword in C++.

What are methods?
Functions defined inside of a class are sometimes called member functions or methods.

How would you define a class
A class in C++ is a user defined type or data structure declared with keyword class that has data and functions as its members whose access is governed by the three access specifiers private, protected or public. (wikipedia)

what is an object
An object can be referred to as a variable of a class type