C++ Lesson 02: Classes and Objects
2.1 struct in C++
In C++, the struct is expanded to contain not only data (variables) but also functions. All the data and functions can be assigned to different access sections: private, protected, and public. It has the same capabilities as a class except that. By default, a structure's members are public. The general form of a C++ structure is:
struct class_name : inheritance_list {
public:
// public members by default
protected:
// private members that can be inherited
privated:
// private members
} object_list;
The class_name is the type name of the structure, which is a class type. The individual members are referenced using the dot (.) operator when acting on an object or by using the arrow (->) operator when acting through a pointer to the object. The object_list and inheritance_list are optional.
New struct in C++
#include <stdio.h> #include <iostream> using namespace std; typedef struct STUDENTINFO{ private: int age; string name; public: void SetAge(int a); void SetName(string n); void PrintInfo(); } STUDENTINFO; //------------------------------------------------------------------------------ int main() { STUDENTINFO Student; string name; int age; age = 16; name = "Ryan"; Student.SetAge(age); Student.SetName(name); Student.PrintInfo(); return 0; } //------------------------------------------------------------------------------ void STUDENTINFO::SetAge(int a) { age = a; } void STUDENTINFO::SetName(string n) { name = n; } void STUDENTINFO::PrintInfo() { cout << "Name: " << name << endl; cout << "Age: " << age << endl; } //------------------------------------------------------------------------------
2.2 Classes and Objects
C++ creates a new user-defined data type — class. It similar to the struct, but there are still some differences between both, we will discuss it in the 2.4 section.
A class is a basic unit of encapsulation in C++. Its general form is as below:
class class_name : inheritance_list {
// private members by default
private:
// private members
protected:
// private members that can be inherited
public:
// public members
} object_list;
A class in C++ is a user-defined data type, which can hold its own data members and member functions in a block. In the class, the member data and functions can be stored in different access sections: private, protected, and public. The default access section for the class is private. The class is similar to a struct, but the default access section is the public in a struct.