- A class is an expansion of structures by bringing together data and functions/operations.
- A class is a user-defined data type that can hold variables and functions.
- A variable of the user-defined class is called an object.
- Declaring an object is called “creating an instance” or “instantiation”
Creating Classes
- Class: definition goes to header file, and implementation goes to source file.
Definition
class student{
private:
int ID;
string name;
public:
void setName(string s);
string getName();
void print();
};
studentis the class name
private and public are access control
- private: can only be accessed from within the class
- public: can be accessed from within and from outside the class
ID and name are the data members of the class
setName, getName, and print are called function members or methods
Implementation
#include <iostream>
using namespace std;
#include "student.h"
void student::setName(string s){
name = s;
}
string student::getName(){
return name;
}
void student::print(){
cout << "student name: " << name << endl;
cout << "student ID: " << ID << endl;
}
- the “student” in
void student is called the scope operator
- “setters” and “getters” are used to assign or retrieve values from private variables
Using the Class
#include "student.h"
int main(){
student x, y;
x.setName("Ayman");
y.setName("Mohammad");
x.print();
y.print();
}
- doing something like
x.ID = 2710; is forbidden because ID is a private variable
Constructors
- called by default when a new object is created
- it has the same name as the class
- it does not have a return type
class student{
private:
int ID;
string name;
public:
student();
void setName(string s);
string getName();
void print();
};
#include <iostream>
using namespace std;
#include "student.h"
student::student(){
ID = 0;
name = "";
}
void student::setName(string s){
name = s;
}
string student::getName(){
return name;
}
void student::print(){
cout << "student name: " << name << endl;
cout << "student ID: " << ID << endl;
}