Lecture 9 - Sept 26, 2023
Summary
In this lecture, we introduce classes, access controls: private and public, and initializing data members problem.
Last lecture
Using .fail()
and .eof()
flags.
Today
Introduction to classes.
Demo of stringstreams
Avoid using stream for reading and writing interchangeably. You can write and then read, but it gets confusing when you write again.
Introduction to clases
Recall structs in C
A class is an expansion to structs by bringing together data and functions/operations.
Consider that:
- Data is similar to structs.
- Functions/operations are different from structs.
A class is a user-defined data type. A variable of that user-defined data type is called an object.
Declaring an object is called creating an instance or instantiation.
Remember the diagram from lecture 8.
The definition of a class goes to a header file (e.g. Student.h
).
Student.h
class Student {
private:
int ID;
;
string name
public:
void setName(string name);
void getName();
void print();
};
Remember the diagram from lecture 8.
private members can only be accessed within the class.
public members can be accessed outside the class.
Why? This is called encapsulation
- Hide information related to the class (e.g., student ID).
- It is not available outside the class.
- It brings related data and functions together.
- It organizes the code.
Class implementation
The class implementation goes in a source file and it has function definitions.
Student.cpp
#include "Student.h"
#include <iostream>
// Setter or mutator function
// class name: Student
// scope operator: ::
// function name: setName
void Student::setName(string n) {
// private member of Student class can be accessed
// inside the class implementation
= n;
name }
// Getter or accessor function
::getName() {
string Studentreturn name;
}
void Student::print() {
<< "Student name: " << name << endl;
cout << "Student ID: " << ID << endl;
cout }
main.cpp
Instatiating and using objects here.
#include "Student.h"
int main() {
// declare 2 objects and allocate memory for them
,y;
Student x
.setName("Kenya");
x.setName("Christina");
y
// x.ID = 2730; gives an error because we cannot access a private member
// y.name = "Salma" same error
.print(); // wait! what is the value of ID in Student y?
y
return 0;
}
In the line that reads Student x,y
, ID
in x
and y
are not initialized.
The solution is to define a constructor.
Student.h
class Student {
private:
int ID;
;
string name
public:
(); // constructor
Studentvoid setName(string name);
...
}