L06 Classes and Objects
Recall:
struct in C
A data structure: essentially the same as a dictionary in Python. See APS105 Textbook 12.1 - Data Structures Intro for further explanation.
Example (using C++ code):
struct Student {
string name;
int ID;
double height;
}
struct Student x;
x.name = "Cindy";
void print(string n) {
// code to print stuff
}
classes
A class is an expansion to structs that bundles together data and functions. It is a user-defined data type.
- A class is essentially a blueprint or a template
- Creating an instance of the class (creating a variable out of it) is an object.
- Each object is independent, meaning changes to one object don't affect other objects.
Classes in C++ are a lot like classes in Python
e.g. string class in C++
The definition of a Class goes inside a header file.
// student.h
class Student {
int ID;
string name;
void print();
};
abstraction
- private: access controller on members of a class that can only be used inside a class
- accessible anywhere inside of a function member of a class
- public: access controller on members allowing members to be accessed anywhere, both inside and outside the class.
// student.h
// header file that just defines the Student class
class Student {
private:
int ID;
string name;
public:
Student(); // constructor
void print();
void setName(string n);
string getName();
};
//students.cpp
#include <iostream>
#include "student.h"
using namespace std;
void Student::print() {
// adding logic to the print() function
// which was defined in the Student class
cout << "Student name " << name;
cout << "Student ID " << ID;
}
string Student::getName() {
// adding logic to the getName() function
// which was defined in the Student class
return name;
}
void Student::setName(string n) {
name = n;
}
Student::Student() { // constructor
ID = 0;
name = "no name";
}
//main.cpp
#include "Student.h"
int main(void) {
// create an object of Student
Student x; // so essentially Student is a data type here
Student y;
// another Student obj, independent of the other obj but using the same template
x.ID = 4078; // this doesn't work because ID is a private data member
// can't be accessed outside of the Student class
x.setName("abigail");
x.getName(); // returns "abigail"
y.print(); // this is an issue because name and ID are uninitialized
// so we can use a Constructor
}
By convention, we always make the data members private, and use public functions to alter those variables
constructor
A constructor is a function that always gets called when a new object of a class is created. To see more: L07 Constructors, Destructors, Dynamic Memory Allocation